The document.createEvent
documentation says that "The createEvent method is deprecated. Use event constructors instead."
So you should use this method instead:
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
and fire it on an element like this:
element.dispatchEvent(clickEvent);
as shown here.
It is easy to modify the elements styles but kinda tricky to read the value.
JavaScript can't read any element style property (elem.style) coming from css(internal/external) unless you use the built in method call getComputedStyle in javascript.
getComputedStyle(element[, pseudo])
Element: The element to read the value for.
pseudo: A pseudo-element if required, for instance ::before. An empty string or no argument means the element itself.
The result is an object with style properties, like elem.style, but now with respect to all css classes.
For instance, here style doesn’t see the margin:
<head>
<style> body { color: red; margin: 5px } </style>
</head>
<body>
<script>
let computedStyle = getComputedStyle(document.body);
// now we can read the margin and the color from it
alert( computedStyle.marginTop ); // 5px
alert( computedStyle.color ); // rgb(255, 0, 0)
</script>
</body>
So modified your javaScript code to include the getComputedStyle of the element you wish to get it's width/height or other attribute
window.onload = function() {
var test = document.getElementById("test");
test.addEventListener("click", select);
function select(e) {
var elementID = e.target.id;
var element = document.getElementById(elementID);
let computedStyle = getComputedStyle(element);
var width = computedStyle.width;
console.log(element);
console.log(width);
}
}
Computed and resolved values
There are two concepts in CSS:
A computed style value is the value after all CSS rules and CSS inheritance is applied, as the result of the CSS cascade. It can look like height:1em or font-size:125%.
A resolved style value is the one finally applied to the element. Values like 1em or 125% are relative. The browser takes the computed value and makes all units fixed and absolute, for instance: height:20px or font-size:16px. For geometry properties resolved values may have a floating point, like width:50.5px.
A long time ago getComputedStyle was created to get computed values, but it turned out that resolved values are much more convenient, and the standard changed.
So nowadays getComputedStyle actually returns the resolved value of the property.
Please Note:
getComputedStyle requires the full property name
You should always ask for the exact property that you want, like paddingLeft or height or width. Otherwise the correct result is not guaranteed.
For instance, if there are properties paddingLeft/paddingTop, then what should we get for getComputedStyle(elem).padding? Nothing, or maybe a “generated” value from known paddings? There’s no standard rule here.
There are other inconsistencies. As an example, some browsers (Chrome) show 10px in the document below, and some of them (Firefox) – do not:
<style>
body {
margin: 30px;
height: 900px;
}
</style>
<script>
let style = getComputedStyle(document.body);
alert(style.margin); // empty string in Firefox
</script>
for more information https://javascript.info/styles-and-classes
Use a special Stylesheet for printing
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
and then add a class i.e. "noprint" to every tag which's content you don't want to print.
In the CSS use
.noprint {
display: none;
}
If You Have Multiple li
elements inside an li
element then this will definitely help you, and i have checked it and it works....
<script>
$("li").on('click', function() {
alert(this.id);
return false;
});
</script>
As others pointed out if you are allowed to use a framework like jQuery the best thing to do is use it, as it high likely will do it in the best possible way. If you are not allowed to use a framework then I guess manipulating the DOM is the best way to do it (and in my opinion, the right way to do it).
If you are looking for Hash modification, your solution works ok. However, if you want to change the query, you can use the pushState, as you said. Here it is an example that might help you to implement it properly. I tested and it worked fine:
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
window.history.pushState({path:newurl},'',newurl);
}
It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values. And of course that it requires modern browsers that can process HTML5 History API.
For more information:
http://diveintohtml5.info/history.html
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
Pure JavaScript with no need for temporary variables:
Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked")).map(e => e.value)
You may use for this YUI library or use this article to implement
To do it without using a JavaScript library such as jQuery, you'd do it like this:
var span = document.getElementById("myspan"),
text = document.createTextNode(''+intValue);
span.innerHTML = ''; // clear existing
span.appendChild(text);
If you do want to use jQuery, it's just this:
$("#myspan").text(''+intValue);
After jQuery 1.7 the preferred methods are .on() and .off()
Sean's answer shows an example.
Use the jQuery functions
.live()
and.die()
. Available in jQuery 1.3.xFrom the docs:
To display each paragraph's text in an alert box whenever it is clicked:
$("p").live("click", function(){ alert( $(this).text() ); });
Also, the livequery plugin does this and has support for more events.
@MIP is right, but with newer versions of Safari, you will need to add sandbox attribute(HTML5) to give redirect access to the iFrame. There are a few specific values that can be added with a space between them.
Reference(you will need to scroll): https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe
Ex:
<iframe sandbox="allow-top-navigation" src="http://google.com/"></iframe>
I faced the same problem and solve it by this method. html :
<div id="parentDiv">
<div id="childDiv">
AAA
</div>
BBBB
</div>
JS:
$(document).ready(function(){
$("#parentDiv").click(function(e){
if(e.target.id=="childDiv"){
childEvent();
} else {
parentEvent();
}
});
});
function childEvent(){
alert("child event");
}
function parentEvent(){
alert("paren event");
}
I'd recommend to replace all :hover
properties to :active
when you detect that device supports touch. Just call this function when you do so as touch()
function touch() {
if ('ontouchstart' in document.documentElement) {
for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
if (sheet.cssRules) {
for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
if (rule.selectorText) {
rule.selectorText = rule.selectorText.replace(':hover', ':active');
}
}
}
}
}
}
There is another consistent way (only for IE9+) in vanilla JavaScript for this:
const iframe = document.getElementById('iframe');
const handleLoad = () => console.log('loaded');
iframe.addEventListener('load', handleLoad, true)
And if you're interested in Observables this does the trick:
return Observable.fromEventPattern(
handler => iframe.addEventListener('load', handler, true),
handler => iframe.removeEventListener('load', handler)
);
This worked for me just now:
<canvas id="c" height="100" width="100" style="border:1px solid red"></canvas>
<script>
var c = document.getElementById('c');
alert(c.height + ' ' + c.width);
c.height = 200;
c.width = 200;
alert(c.height + ' ' + c.width);
</script>
Simply supplying the HTML of elements you want to add to a jQuery constructor $()
will return a jQuery object from newly built HTML, suitable for being appended into the DOM using jQuery's append()
method.
For example:
var t = $("<table cellspacing='0' class='text'></table>");
$.append(t);
You could then populate this table programmatically, if you wished.
This gives you the ability to specify any arbitrary HTML you like, including class names or other attributes, which you might find more concise than using createElement
and then setting attributes like cellSpacing
and className
via JS.
If you are using jQuery, use css to add CSS
$("#voltaic_holder").css({'position': 'absolute',
'top': '-75px'});
To remove CSS attributes
$("#voltaic_holder").css({'position': '',
'top': ''});
Device: iPad Mini
OS: iOS 9 Beta 3
App downloaded from: Hockey App
Provisioning profile with Trust issues: Enterprise
In my case, when I navigate to Settings > General > Profiles, I could not see on any Apple provisioning profile. All I could see is a Configuration Profile which is HockeyApp Config.
Here are the steps that I followed:
That's it! You're done! You can now go back to your app and open it successfully. Hope this helped. :)
This Worked for me as well.Instead of giving full path i gave path="Pictures" and it worked fine.
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path
name="images"
path="Pictures">
</external-files-path>
</paths>
Adding another entry for the debate about whether batch normalization should be called before or after the non-linear activation:
In addition to the original paper using batch normalization before the activation, Bengio's book Deep Learning, section 8.7.1 gives some reasoning for why applying batch normalization after the activation (or directly before the input to the next layer) may cause some issues:
It is natural to wonder whether we should apply batch normalization to the input X, or to the transformed value XW+b. Io?e and Szegedy (2015) recommend the latter. More speci?cally, XW+b should be replaced by a normalized version of XW. The bias term should be omitted because it becomes redundant with the ß parameter applied by the batch normalization reparameterization. The input to a layer is usually the output of a nonlinear activation function such as the recti?ed linear function in a previous layer. The statistics of the input are thus more non-Gaussian and less amenable to standardization by linear operations.
In other words, if we use a relu activation, all negative values are mapped to zero. This will likely result in a mean value that is already very close to zero, but the distribution of the remaining data will be heavily skewed to the right. Trying to normalize that data to a nice bell-shaped curve probably won't give the best results. For activations outside of the relu family this may not be as big of an issue.
Keep in mind that there are reports of models getting better results when using batch normalization after the activation, while others get best results when the batch normalization is placed before the activation. It is probably best to test your model using both configurations, and if batch normalization after activation gives a significant decrease in validation loss, use that configuration instead.
The -L
merely gives the path where to find the .a
or .so
file. What you're looking for is to add -lmine
to the LIBS
variable.
Make that -static -lmine
to force it to pick the static library (in case both static and dynamic library exist).
Addition: Suppose the path to the file has been conveyed to the linker (or compiler driver) via -L
you can also specifically tell it to link libfoo.a
by giving -l:libfoo.a
. Note that in this case the name includes the conventional lib
-prefix. You can also give a full path this way. Sometimes this is the better method to "guide" the linker to the right location.
There are moduli other than powers of 2 for which efficient algorithms exist.
For example, if x is 32 bits unsigned int then x % 3 = popcnt (x & 0x55555555) - popcnt (x & 0xaaaaaaaa)
This problem cost me one whole day. I finally downgraded the firebase-ui library version from 2.0.0 to 1.2.0 and added the following code inside Project level build.gradle file:
allprojects {
repositories {
jcenter()
// Add the following code to your project level build.gradle
maven {
url 'https://maven.fabric.io/public'
}
}
}
In my understanding, the way Android handles the MVC pattern is like:
You have an Activity, which serves as the controller. You have a class which responsibility is to get the data - the model, and then you have the View class which is the view.
When talking about the view most people think only for its visual part defined in the xml. Let's not forget that the View also has a program part with its constructors, methods and etc, defined in the java class.
Node.js
introduced async await
in 7.6
so this makes Javascript
more beautiful.
var results = [];
var config = JSON.parse(queries);
for (var key in config) {
var query = config[key].query;
results.push(await search(query));
}
res.writeHead( ... );
res.end(results);
For this to work search
fucntion has to return a promise
or it has to be async
function
If it is not returning a Promise
you can help it to return a Promise
function asyncSearch(query) {
return new Promise((resolve, reject) => {
search(query,(result)=>{
resolve(result);
})
})
}
Then replace this line await search(query);
by await asyncSearch(query);
Yes. Use OrderByDescending
instead of OrderBy
.
Super Duper Old I know but I would add my piece on using Linq and continuation lambdas on methods with using C# 7. I try to use named tuples as replacements for DTOs and anonymous projections when reused in a class. Yes for mocking and testing you still need classes but doing things inline and passing around in a class is nice to have this newer option IMHO. You can instantiate them from
- Direct Instantiation
var items = new List<(int Id, string Name)> { (1, "Me"), (2, "You")};
- Off of an existing collection, and now you can return well typed tuples similar to how anonymous projections used to be done.
public class Hold
{
public int Id { get; set; }
public string Name { get; set; }
}
//In some method or main console app:
var holds = new List<Hold> { new Hold { Id = 1, Name = "Me" }, new Hold { Id = 2, Name = "You" } };
var anonymousProjections = holds.Select(x => new { SomeNewId = x.Id, SomeNewName = x.Name });
var namedTuples = holds.Select(x => (TupleId: x.Id, TupleName: x.Name));
- Reuse the tuples later with grouping methods or use a method to construct them inline in other logic:
//Assuming holder class above making 'holds' object
public (int Id, string Name) ReturnNamedTuple(int id, string name) => (id, name);
public static List<(int Id, string Name)> ReturnNamedTuplesFromHolder(List<Hold> holds) => holds.Select(x => (x.Id, x.Name)).ToList();
public static void DoSomethingWithNamedTuplesInput(List<(int id, string name)> inputs) => inputs.ForEach(x => Console.WriteLine($"Doing work with {x.id} for {x.name}"));
var namedTuples2 = holds.Select(x => ReturnNamedTuple(x.Id, x.Name));
var namedTuples3 = ReturnNamedTuplesFromHolder(holds);
DoSomethingWithNamedTuplesInput(namedTuples.ToList());
It's a reserved keyword (like return, filter, function, break).
Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:
But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.
Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:
PS C:\> function ex{exit}
PS C:\> new-alias ^D ex
If you are interesting in modern api way, avoiding NSSearchPath and filter files in documents directory, before deletion, you can do like:
let fileManager = FileManager.default
let keys: [URLResourceKey] = [.nameKey, .isDirectoryKey]
let options: FileManager.DirectoryEnumerationOptions = [.skipsHiddenFiles, .skipsPackageDescendants]
guard let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).last,
let fileEnumerator = fileManager.enumerator(at: documentsUrl,
includingPropertiesForKeys: keys,
options: options) else { return }
let urls: [URL] = fileEnumerator.flatMap { $0 as? URL }
.filter { $0.pathExtension == "exe" }
for url in urls {
do {
try fileManager.removeItem(at: url)
} catch {
assertionFailure("\(error)")
}
}
List<Date> dates = new ArrayList<Date>();
String str_date = "DD/MM/YYYY";
String end_date = "DD/MM/YYYY";
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date startDate = (Date)formatter.parse(str_date);
Date endDate = (Date)formatter.parse(end_date);
long interval = 1000 * 60 * 60; // 1 hour in milliseconds
long endTime = endDate.getTime() ; // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime += interval;
}
for (int i = 0; i < dates.size(); i++){
Date lDate = (Date)dates.get(i);
String ds = formatter.format(lDate);
System.out.println("Date is ..." + ds);
//Write your code for storing dates to list
}
As stated already within another answer it is not recommended to catch a NullPointerException. However you definitely could catch it, like the following example shows.
public class Testclass{
public static void main(String[] args) {
try {
doSomething();
} catch (NullPointerException e) {
System.out.print("Caught the NullPointerException");
}
}
public static void doSomething() {
String nullString = null;
nullString.endsWith("test");
}
}
Although a NPE can be caught you definitely shouldn't do that but fix the initial issue, which is the Check_Circular method.
UPDATE My Answer here is now outdated. The Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See the modern solution in the Answer by Ole V.V..
The accepted answer by NidhishKrishnan is correct.
For fun, here is the same kind of code in Joda-Time 2.3.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
java.util.Date date = new Date(); // A Date object coming from other code.
// Pass the java.util.Date object to constructor of Joda-Time DateTime object.
DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );
When run…
dateTimeInKolkata formatted for date: 2013-12-17
dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30
You have to specify the projectBaseDir
if the module name doesn't match you module directory.
Since both your module are located in ".", you can simply add the following to your sonar-project properties:
module1.sonar.projectBaseDir=.
module2.sonar.projectBaseDir=.
Sonar will handle your modules as components of the project:
EDIT
If both of your modules are located in the same source directory, define the same source folder for both and exclude the unwanted packages with sonar.exclusions
:
module1.sonar.sources=src/main/java
module1.sonar.exclusions=app2code/**/*
module2.sonar.sources=src/main/java
module2.sonar.exclusions=app1code/**/*
Very old question, but just had to build this for an app today and found the settings shown in other answers do not result in a clean image (possibly as new options were added in later .Net versions).
Assuming you want the text in the centre of the bitmap, you can do this:
// Load the original image
Bitmap bmp = new Bitmap("filename.bmp");
// Create a rectangle for the entire bitmap
RectangleF rectf = new RectangleF(0, 0, bmp.Width, bmp.Height);
// Create graphic object that will draw onto the bitmap
Graphics g = Graphics.FromImage(bmp);
// ------------------------------------------
// Ensure the best possible quality rendering
// ------------------------------------------
// The smoothing mode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing).
// One exception is that path gradient brushes do not obey the smoothing mode.
// Areas filled using a PathGradientBrush are rendered the same way (aliased) regardless of the SmoothingMode property.
g.SmoothingMode = SmoothingMode.AntiAlias;
// The interpolation mode determines how intermediate values between two endpoints are calculated.
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Use this property to specify either higher quality, slower rendering, or lower quality, faster rendering of the contents of this Graphics object.
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
// This one is important
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// Create string formatting options (used for alignment)
StringFormat format = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
// Draw the text onto the image
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf, format);
// Flush all graphics changes to the bitmap
g.Flush();
// Now save or use the bitmap
image.Image = bmp;
In iTunes 11 you can go to the view menu, and "Show Sidebar", this will give you the sidebar, that you can drag 'n drop to.
You'll drag 'n drop to the open area that will be near the bottom of the sidebar (I'm typically doing this with both an IPA and a provisioning profile). After you do that, there will be an apps menu that appears in the sidebar with your app in it. Click on that, and you'll see your application in the main view. You can then drag your application from there to your device. Below, please find a video (it's private, so you'll need the URL) that outlines the steps visually: http://youtube.com/watch?v=0ACq4CRpEJ8&feature=youtu.be
List indexes of -x mean the xth item from the end of the list, so n[-1]
means the last item in the list n
. Any good Python tutorial should have told you this.
It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1]
to access the last item of a list.
If it might spare some time I was looking to get:
YYYYMMDD
for today, and got along with:
const dateDocumentID = new Date()
.toISOString()
.substr(0, 10)
.replace(/-/g, '');
Use waitpid() like this:
pid_t childPid; // the child process that the execution will soon run inside of.
childPid = fork();
if(childPid == 0) // fork succeeded
{
// Do something
exit(0);
}
else if(childPid < 0) // fork failed
{
// log the error
}
else // Main (parent) process after fork succeeds
{
int returnStatus;
waitpid(childPid, &returnStatus, 0); // Parent process waits here for child to terminate.
if (returnStatus == 0) // Verify child process terminated without error.
{
printf("The child process terminated normally.");
}
if (returnStatus == 1)
{
printf("The child process terminated with an error!.");
}
}
Use this:
var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
This will convert Stream
to MemoryStream
.
Wget currently only supports x-www-form-urlencoded data. --post-file
is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example
.
--post-data
and --post-file
work the same way: the only difference is that --post-data
allows you to specify the data in the command line, while --post-file
allows you to specify the path of the file that contain the data to send.
Here's the documentation:
--post-data=string
--post-file=file
Use POST as the method for all HTTP requests and send the specified data
in the request body. --post-data sends string as data, whereas
--post-file sends the contents of file. Other than that, they work in
exactly the same way. In particular, they both expect content of the
form "key1=value1&key2=value2", with percent-encoding for special
characters; the only difference is that one expects its content as a
command-line parameter and the other accepts its content from a file. In
particular, --post-file is not for transmitting files as form
attachments: those must appear as "key=value" data (with appropriate
percent-coding) just like everything else. Wget does not currently
support "multipart/form-data" for transmitting POST data; only
"application/x-www-form-urlencoded". Only one of --post-data and
--post-file should be specified.
Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.
Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN
.
wget --post-data 'user=foo&password=bar' http://example.com/auth.php
Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.
You can use IsNull function
select
isnull(rtrim(ltrim([FirstName]))+' ','') +
isnull(rtrim(ltrim([SecondName]))+' ','') +
isnull(rtrim(ltrim([Surname]))+' ','') +
isnull(rtrim(ltrim([SecondSurname])),'')
from TableDat
if one column is null you would get an empty char
Compatible with Microsoft SQL Server 2008+
In C# Predicates are simply delegates that return booleans. They're useful (in my experience) when you're searching through a collection of objects and want something specific.
I've recently run into them in using 3rd party web controls (like treeviews) so when I need to find a node within a tree, I use the .Find() method and pass a predicate that will return the specific node I'm looking for. In your example, if 'a' mod 2 is 0, the delegate will return true. Granted, when I'm looking for a node in a treeview, I compare it's name, text and value properties for a match. When the delegate finds a match, it returns the specific node I was looking for.
/*
Use Recursive and setTimeout
call below function will run loop loopFunctionNeedCheck until
conditionCheckAfterRunFn = true, if conditionCheckAfterRunFn == false : delay
reRunAfterMs miliseconds and continue loop
tested code, thanks
*/
function functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn,
loopFunctionNeedCheck) {
loopFunctionNeedCheck();
var result = conditionCheckAfterRunFn();
//check after run
if (!result) {
setTimeout(function () {
functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn, loopFunctionNeedCheck)
}, reRunAfterMs);
}
else console.log("completed, thanks");
//if you need call a function after completed add code call callback in here
}
//passing-parameters-to-a-callback-function
// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function () {
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function () {
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
//test code:
var result = 0;
console.log("---> init result is " + result);
var functionNeedRun = function (step) {
result+=step;
console.log("current result is " + result);
}
var checkResultFunction = function () {
return result==100;
}
//call this function will run loop functionNeedRun and delay 500 miliseconds until result=100
functionRepeatUntilConditionTrue(500, checkResultFunction , functionNeedRun.bind(null, 5));
//result log from console:
/*
---> init result is 0
current result is 5
undefined
current result is 10
current result is 15
current result is 20
current result is 25
current result is 30
current result is 35
current result is 40
current result is 45
current result is 50
current result is 55
current result is 60
current result is 65
current result is 70
current result is 75
current result is 80
current result is 85
current result is 90
current result is 95
current result is 100
completed, thanks
*/
I came up with something using HTML + CSS only. Hope it works for you
.mzhrttltp {
position: relative;
display: inline-block;
}
.mzhrttltp .hrttltptxt {
visibility: hidden;
width: 120px;
background-color: #040505;
font-size:13px;color:#fff;font-family:IranYekanWeb;
text-align: center;
border-radius: 3px;
padding: 4px 0;
position: absolute;
z-index: 1;
top: 105%;
left: 50%;
margin-left: -60px;
}
.mzhrttltp .hrttltptxt::after {
content: "";
position: absolute;
bottom: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent transparent #040505 transparent;
}
.mzhrttltp:hover .hrttltptxt {
visibility: visible;
}
_x000D_
<div class="mzhrttltp"><svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="#e2062c" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="feather feather-heart"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg><div class="hrttltptxt">?????‌????‌??</div></div>
_x000D_
If Ubuntu Docker image isn't recognizing 'ifconfig' inside of GNS3, you'll need to open Ubuntu docker image on your host.
Assuming you already have docker on your host pc and ubuntu pull'd from docker images. Enter these commands in your host OS (Linux, CentOS, etc.) CLI.
$docker images
$docker run -it ubuntu
$apt-get update
$apt-get install net-tools
(side note: you can add whatever other tools and services that you would like to add now, but for now this is just to get ifconfig to work.)
$exit
Now you will commit these changes to Docker. This link for committing changes is the best summary and works (skip to Step 4):
https://phoenixnap.com/kb/how-to-commit-changes-to-docker-image#htoc-step-3-modify-the-container
When you re-open the docker image in GNS3 you should now have the ifconfig command usable and whatever other tools or services you added to the container.
Enjoy!
I will correct usage for that method that @BullyWillPlaza suggested. Reason is that when I try to add add textArea to only contextMenu it's not visible, and if i add it to both to contextMenu and some panel it ecounters: Different parent double association if i try to switch to Design editor.
TexetObjcet.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)){
contextmenu.add(TexetObjcet);
contextmenu.show(TexetObjcet, 0, 0);
}
}
});
Make mouse listener like this for text object you need to have popup on. What this will do is when you right click on your text object it will then add that popup and display it. This way you don't encounter that error. Solution that @BullyWillPlaza made is very good, rich and fast to implement in your program so you should try it our see how you like it.
While this is usefull in rare cases (if that was not the case, the language would've allowed it directly), take a look at the Base from Member idiom. It's not a code free solution, you'd have to add an extra layer of inheritance, but it gets the job done. To avoid boilerplate code you could use boost's implementation
I generally prefer hyphens with lower case, but one thing not yet mentioned is that sometimes it's nice to have the file name exactly match the name of a single module or instantiable function contained within.
For example, I have a revealing module declared with var knockoutUtilityModule = function() {...}
within its own file named knockoutUtilityModule.js, although objectively I prefer knockout-utility-module.js.
Similarly, since I'm using a bundling mechanism to combine scripts, I've taken to defining instantiable functions (templated view models etc) each in their own file, C# style, for maintainability. For example, ProductDescriptorViewModel lives on its own inside ProductDescriptorViewModel.js (I use upper case for instantiable functions).
To trim a string down so it does not contain two or more spaces in a row. Every instance of 2 or more space will be trimmed down to 1 space. A simple solution:
While ImageText1.Contains(" ") '2 spaces.
ImageText1 = ImageText1.Replace(" ", " ") 'Replace with 1 space.
End While
I have looked at software protection in general for my own projects and the general philosophy is that complete protection is impossible. The only thing that you can hope to achieve is to add protection to a level that would cost your customer more to bypass than it would to purchase another license.
With that said I was just checking google for python obsfucation and not turning up a lot of anything. In a .Net solution, obsfucation would be a first approach to your problem on a windows platform, but I am not sure if anyone has solutions on Linux that work with Mono.
The next thing would be to write your code in a compiled language, or if you really want to go all the way, then in assembler. A stripped out executable would be a lot harder to decompile than an interpreted language.
It all comes down to tradeoffs. On one end you have ease of software development in python, in which it is also very hard to hide secrets. On the other end you have software written in assembler which is much harder to write, but is much easier to hide secrets.
Your boss has to choose a point somewhere along that continuum that supports his requirements. And then he has to give you the tools and time so you can build what he wants. However my bet is that he will object to real development costs versus potential monetary losses.
Internet Explorer doesn't fully support Flexbox due to:
Partial support is due to large amount of bugs present (see known issues).
Screenshot and infos taken from caniuse.com
Internet Explorer before 10 doesn't support Flexbox, while IE 11 only supports the 2012 syntax.
display: flex
and flex-direction: column
will not properly calculate their flexed childrens' sizes if the container has min-height
but no explicit height
property. See bug.flex
is 0 0 auto
rather than 0 1 auto
as defined in the latest spec.min-height
is used. See bug.Flexbugs is a community-curated list of Flexbox issues and cross-browser workarounds for them. Here's a list of all the bugs with a workaround available and the browsers that affect.
align-items: center
overflow their containermin-height
on a flex container won't apply to its flex itemsflex
shorthand declarations with unitless flex-basis
values are ignoredflex
items don't always preserve intrinsic aspect ratiosflex-basis
doesn't account for box-sizing: border-box
flex-basis
doesn't support calc()
align-items: baseline
doesn't work with nested flex containersflex-flow: column wrap
do not contain their itemsmargin: auto
on the cross axisflex-basis
cannot be animatedmax-width
is usedThe following code will work:
ComboBox1.SelectedIndex.Equals(String.Empty);
If your problem is so special that you really need to have more readers open simultaneously, and your requirements allow not older than SQL Server 2005 DB backend, then the magic word is MARS (Multiple Active Result Sets). http://msdn.microsoft.com/en-us/library/ms345109%28v=SQL.90%29.aspx. Bob Vale's linked topic's solution shows how to enable it: specify MultipleActiveResultSets=true
in your connection string. I just tell this as an interesting possibility, but you should rather transform your solution.
I encountered this problem as well and the other answers here were helpful, but I am using a Route::resource
which takes care of GET
, POST
, and other requests.
In my case I left my route as is:
Route::resource('file', 'FilesController');
And simply modified my form to submit to the store
function in my FilesController
{{ Form::open(array('route' => 'file.store')) }}
This fixed the issue, and I thought it was worth pointing out as a separate answer since various other answers suggest adding a new POST
route. This is an option but it's not necessary.
Follow these steps:
Microsoft Access Database Engine 2016 Redistributable
and installTo get a result in MB:
SELECT
SUM(ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024), 2)) AS "SIZE IN MB"
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_SCHEMA = "SCHEMA-NAME";
To get a result in GB:
SELECT
SUM(ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024 / 1024), 2)) AS "SIZE IN GB"
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_SCHEMA = "SCHEMA-NAME";
var s = '';
var num = parseInt(s) || 0;
When not used with boolean values, the logical OR (||
) operator returns the first expression (parseInt(s)
) if it can be evaluated to true, otherwise it returns the second expression (0). The return value of parseInt('')
is NaN. NaN evaluates to false, so num
ends up being set to 0.
If you are at the root of your working directory, you can do git checkout -- .
to check-out all files in the current HEAD and replace your local files.
You can also do git reset --hard
to reset your working directory and replace all changes (including the index).
I say const your value parameters.
Consider this buggy function:
bool isZero(int number)
{
if (number = 0) // whoops, should be number == 0
return true;
else
return false;
}
If the number parameter was const, the compiler would stop and warn us of the bug.
The answers that suggest using variations of $window.history.back()
have all missed a crucial part of the question: How to restore the application's state to the correct state-location as the history jumps (back/forward/refresh). With that in mind; please, read on.
Yes, it is possible to have the browser back/forward (history) and refresh whilst running a pure ui-router
state-machine but it takes a bit of doing.
You need several components:
Unique URLs. The browser only enables the back/forward buttons when you change urls, so you must generate a unique url per visited state. These urls need not contain any state information though.
A Session Service. Each generated url is correlated to a particular state so you need a way to store your url-state pairs so that you can retrieve the state information after your angular app has been restarted by back / forward or refresh clicks.
A State History. A simple dictionary of ui-router states keyed by unique url. If you can rely on HTML5 then you can use the HTML5 History API, but if, like me, you can't then you can implement it yourself in a few lines of code (see below).
A Location Service. Finally, you need to be able manage both ui-router state changes, triggered internally by your code, and normal browser url changes typically triggered by the user clicking browser buttons or typing stuff into the browser bar. This can all get a bit tricky because it is easy to get confused about what triggered what.
Here is my implementation of each of these requirements. I have bundled everything up into three services:
The Session Service
class SessionService
setStorage:(key, value) ->
json = if value is undefined then null else JSON.stringify value
sessionStorage.setItem key, json
getStorage:(key)->
JSON.parse sessionStorage.getItem key
clear: ->
@setStorage(key, null) for key of sessionStorage
stateHistory:(value=null) ->
@accessor 'stateHistory', value
# other properties goes here
accessor:(name, value)->
return @getStorage name unless value?
@setStorage name, value
angular
.module 'app.Services'
.service 'sessionService', SessionService
This is a wrapper for the javascript sessionStorage
object. I have cut it down for clarity here. For a full explanation of this please see: How do I handle page refreshing with an AngularJS Single Page Application
The State History Service
class StateHistoryService
@$inject:['sessionService']
constructor:(@sessionService) ->
set:(key, state)->
history = @sessionService.stateHistory() ? {}
history[key] = state
@sessionService.stateHistory history
get:(key)->
@sessionService.stateHistory()?[key]
angular
.module 'app.Services'
.service 'stateHistoryService', StateHistoryService
The StateHistoryService
looks after the storage and retrieval of historical states keyed by generated, unique urls. It is really just a convenience wrapper for a dictionary style object.
The State Location Service
class StateLocationService
preventCall:[]
@$inject:['$location','$state', 'stateHistoryService']
constructor:(@location, @state, @stateHistoryService) ->
locationChange: ->
return if @preventCall.pop('locationChange')?
entry = @stateHistoryService.get @location.url()
return unless entry?
@preventCall.push 'stateChange'
@state.go entry.name, entry.params, {location:false}
stateChange: ->
return if @preventCall.pop('stateChange')?
entry = {name: @state.current.name, params: @state.params}
#generate your site specific, unique url here
url = "/#{@state.params.subscriptionUrl}/#{Math.guid().substr(0,8)}"
@stateHistoryService.set url, entry
@preventCall.push 'locationChange'
@location.url url
angular
.module 'app.Services'
.service 'stateLocationService', StateLocationService
The StateLocationService
handles two events:
locationChange. This is called when the browsers location is changed, typically when the back/forward/refresh button is pressed or when the app first starts or when the user types in a url. If a state for the current location.url exists in the StateHistoryService
then it is used to restore the state via ui-router's $state.go
.
stateChange. This is called when you move state internally. The current state's name and params are stored in the StateHistoryService
keyed by a generated url. This generated url can be anything you want, it may or may not identify the state in a human readable way. In my case I am using a state param plus a randomly generated sequence of digits derived from a guid (see foot for the guid generator snippet). The generated url is displayed in the browser bar and, crucially, added to the browser's internal history stack using @location.url url
. Its adding the url to the browser's history stack that enables the forward / back buttons.
The big problem with this technique is that calling @location.url url
in the stateChange
method will trigger the $locationChangeSuccess
event and so call the locationChange
method. Equally calling the @state.go
from locationChange
will trigger the $stateChangeSuccess
event and so the stateChange
method. This gets very confusing and messes up the browser history no end.
The solution is very simple. You can see the preventCall
array being used as a stack (pop
and push
). Each time one of the methods is called it prevents the other method being called one-time-only. This technique does not interfere with the correct triggering of the $ events and keeps everything straight.
Now all we need to do is call the HistoryService
methods at the appropriate time in the state transition life-cycle. This is done in the AngularJS Apps .run
method, like this:
Angular app.run
angular
.module 'app', ['ui.router']
.run ($rootScope, stateLocationService) ->
$rootScope.$on '$stateChangeSuccess', (event, toState, toParams) ->
stateLocationService.stateChange()
$rootScope.$on '$locationChangeSuccess', ->
stateLocationService.locationChange()
Generate a Guid
Math.guid = ->
s4 = -> Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
"#{s4()}#{s4()}-#{s4()}-#{s4()}-#{s4()}-#{s4()}#{s4()}#{s4()}"
With all this in place, the forward / back buttons and the refresh button all work as expected.
In case, you want to rename _id in same collection (for instance, if you want to prefix some _ids):
db.someCollection.find().snapshot().forEach(function(doc) {
if (doc._id.indexOf("2019:") != 0) {
print("Processing: " + doc._id);
var oldDocId = doc._id;
doc._id = "2019:" + doc._id;
db.someCollection.insert(doc);
db.someCollection.remove({_id: oldDocId});
}
});
if (doc._id.indexOf("2019:") != 0) {... needed to prevent infinite loop, since forEach picks the inserted docs, even throught .snapshot() method used.
Yes, but you can select only one column in your subselect
SELECT (SELECT id FROM bla) AS my_select FROM bla2
I installed nodejs following this AngularJS tutorial. the npm command did work when I open a new cmd window but not in the current one.
So the fix was to close and open a new cmd window.
Using text/csv
is the most appropriate type.
You should also consider adding a Content-Disposition
header to the response. Often a text/csv will be loaded by a Internet Explorer directly into a hosted instance of Excel. This may or may not be a desirable result.
Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");
The above will cause a file "Save as" dialog to appear which may be what you intend.
I faced the same error, in my case I miss-spelled ng-model directive something like "ng-moel"
Wrong one: ng-moel="user.name" Right one: ng-model="user.name"
you need to make county_ID
as index for the right frame:
frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
on=[ 'countyid' ], how='left' )
for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.
so you need to verify integrity before joining by , verify_integrity=True
Regarding how you log messages within code, I would opt for the second approach:
ILog log = LogManager.GetLogger(typeof(Bar));
log.Info("message");
Where messages sent to the log above will be 'named' using the fully-qualifed type Bar
, e.g.
MyNamespace.Foo.Bar [INFO] message
The advantage of this approach is that it is the de-facto standard for organising logging, it also allows you to filter your log messages by namespace. For example, you can specify that you want to log INFO level message, but raise the logging level for Bar
specifically to DEBUG:
<log4net>
<!-- appenders go here -->
<root>
<level value="INFO" />
<appender-ref ref="myLogAppender" />
</root>
<logger name="MyNamespace.Foo.Bar">
<level value="DEBUG" />
</logger>
</log4net>
The ability to filter your logging via name is a powerful feature of log4net, if you simply log all your messages to "myLog"
, you loose much of this power!
Regarding the EPiServer CMS, you should be able to use the above approach to specify a different logging level for the CMS and your own code.
For further reading, here is a codeproject article I wrote on logging:
I use this one:
LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
For example, using a 1s interval:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
the time is in milliseconds, the distance is in meters.
This automatically calls:
public void onLocationChanged(Location location) {
//Code here, location.getAccuracy(), location.getLongitude() etc...
}
I also had these included in the script but didnt actually use them:
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
In short:
public class GPSClass implements LocationListener {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
}
}
As this is quite popular question that deals with live-editing of JS, I want to point out another useful option. As described by svjacob in his answer:
I realized I could attach a break-point in the debugger to some line of code before what I wanted to dynamically edit. And since break-points stay even after a reload of the page, I was able to edit the changes I wanted while paused at break-point and then continued to let the page load.
The above solution didn't work for me for quite large JS (webpack bundle - 3.21MB minified version, 130k lines of code in prettified version) - chrome crashed and asked for page reloading which reverted any saved changes. The way to go in this case was Fiddler where you can set AutoRespond option to replace any remote resource with any local file from your computer - see this SO question for details.
In my case I also had to add CORS headers to fiddler to successfully mock response.
Does c# have its own version of the java "synchronized" keyword?
No. In C#, you explicitly lock
resources that you want to work on synchronously across asynchronous threads. lock
opens a block; it doesn't work on method level.
However, the underlying mechanism is similar since lock
works by invoking Monitor.Enter
(and subsequently Monitor.Exit
) on the runtime. Java works the same way, according to the Sun documentation.
You dont need to give column names manually in xaml. Just set AutoGenerateColumns property to true and your list will be automatically binded to DataGrid. refer code. XAML Code:
<Grid>
<DataGrid x:Name="MyDatagrid" AutoGenerateColumns="True" Height="447" HorizontalAlignment="Left" Margin="20,85,0,0" VerticalAlignment="Top" Width="799" ItemsSource="{Binding Path=ListTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" CanUserAddRows="False"> </Grid>
C#
Public Class Test
{
public string m_field1_Test{get;set;}
public string m_field2_Test { get; set; }
public Test()
{
m_field1_Test = "field1";
m_field2_Test = "field2";
}
public MainWindow()
{
listTest = new List<Test>();
for (int i = 0; i < 10; i++)
{
obj = new Test();
listTest.Add(obj);
}
this.MyDatagrid.ItemsSource = ListTest;
InitializeComponent();
}
Above mentioned issue happened in my local system. Check in sql server configuration manager.
Step 1:
SQL server Network configuration
step 2:
.. after I made changes the sql server browser started working
# Switch delimiter to //, so phpMyAdmin will not execute it line by line.
DELIMITER //
CREATE PROCEDURE usp_rateChapter12
(IN numRating_Chapter INT(11) UNSIGNED,
IN txtRating_Chapter VARCHAR(250),
IN chapterName VARCHAR(250),
IN addedBy VARCHAR(250)
)
BEGIN
DECLARE numRating_Chapter INT;
DECLARE txtRating_Chapter VARCHAR(250);
DECLARE chapterName1 VARCHAR(250);
DECLARE addedBy1 VARCHAR(250);
DECLARE chapterId INT;
DECLARE studentId INT;
SET chapterName1 = chapterName;
SET addedBy1 = addedBy;
SET chapterId = (SELECT chapterId
FROM chapters
WHERE chaptername = chapterName1);
SET studentId = (SELECT Id
FROM students
WHERE email = addedBy1);
SELECT chapterId;
SELECT studentId;
INSERT INTO ratechapter (rateBy, rateText, rateLevel, chapterRated)
VALUES (studentId, txtRating_Chapter, numRating_Chapter,chapterId);
END //
//DELIMITER;
Three ways you can do this - from the form designer, select the form, and where you normally see the list of properties, just above it there should be a little lightning symbol - this shows you all the events of the form. Find the form load event in the list, and you should be able to pick ProgramViwer_Load
from the dropdown.
A second way to do it is programmatically - somewhere (constructor maybe) you'd need to add it, something like: ProgramViwer.Load += new EventHandler(ProgramViwer_Load);
A third way using the designer (probably the quickest) - when you create a new form, double click on the middle of it on it in design mode. It'll create a Form load event for you, hook it in, and take you to the event handler code. Then you can just add your two lines and you're good to go!
Assuming you are dealing with a single class per element:
function swapCssClass(a,b) {
while (document.querySelector('.' + a)) {
document.querySelector('.' + a).className = b;
}
}
and then call simply call it with
swapCssClass('x_visible','x_hidden');
This code uses distinct on 2 parameters and provides count of number of rows specific to those distinct values row count. It worked for me in MySQL like a charm.
select DISTINCT DocumentId as i, DocumentSessionId as s , count(*)
from DocumentOutputItems
group by i ,s;
I ran into this a couple times a quarter. This time I had a minimal change summary in my git diff and tracked the problem to a reset classpath (missing my WEB-INF/lib dependency) in eclipse. This seems to occur any time I pull in or pull out parent/sibling maven projects.
There are mentions of adding your spring jars to the tomcat web container lib - this is ok and is the way most EE servers run. However be aware that by placing spring higher in the classloader tree on tomcat you will be running higher than the classloader level of your war context. I recommend you leave the libs in a per/war lower level classloader.
We see the following after a truncated .classpath after a structural project change in eclipse.
Dec 18, 2016 11:13:39 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.web.context.request.RequestContextListener
java.lang.ClassNotFoundException: org.springframework.web.context.request.RequestContextListener
My classpath was reset and the WEB-INF/lib dependency was removed.
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
put back
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
and you will be OK.
thank you /michael
li = [0, 1, 2, 3]
for elem in li:
if (li.index(elem))+1 != len(li):
thiselem = elem
nextelem = li[li.index(elem)+1]
print 'thiselem',thiselem
print 'nextel',nextelem
else:
print 'thiselem',li[li.index(elem)]
print 'nextel',li[li.index(elem)]
*{
margin:0
padding:0
}
make sure your container's width:%100
The main
method is the entry point of a Java application.
Specifically?when the Java Virtual Machine is told to run an application by specifying its class (by using the java
application launcher), it will look for the main
method with the signature of public static void main(String[])
.
From Sun's java
command page:
The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.
The method must be declared public and static, it must not return any value, and it must accept a
String
array as a parameter. The method declaration must look like the following:public static void main(String args[])
For additional resources on how an Java application is executed, please refer to the following sources:
The run
method is the entry point for a new Thread
or an class implementing the Runnable
interface. It is not called by the Java Virutal Machine when it is started up by the java
command.
As a Thread
or Runnable
itself cannot be run directly by the Java Virtual Machine, so it must be invoked by the Thread.start()
method. This can be accomplished by instantiating a Thread
and calling its start
method in the main
method of the application:
public class MyRunnable implements Runnable
{
public void run()
{
System.out.println("Hello World!");
}
public static void main(String[] args)
{
new Thread(new MyRunnable()).start();
}
}
For more information and an example of how to start a subclass of Thread
or a class implementing Runnable
, see Defining and Starting a Thread from the Java Tutorials.
The init
method is the first method called in an Applet or JApplet.
When an applet is loaded by the Java plugin of a browser or by an applet viewer, it will first call the Applet.init
method. Any initializations that are required to use the applet should be executed here. After the init
method is complete, the start
method is called.
For more information about when the init
method of an applet is called, please read about the lifecycle of an applet at The Life Cycle of an Applet from the Java Tutorials.
See also: How to Make Applets from the Java Tutorial.
Yes, it worked for me like a way:
$("#radio_1").attr('checked', 'checked');
Well, as you are just looking to match the position of a character , regex is possibly overkill.
I presume all you want is, instead of "find first of these this character" , just find first of these characters.
This of course is the simple answer, but does what your question sets out to do, albeit without the regex part ( because you didn't clarify why specifically it had to be a regex )
function mIndexOf( str , chars, offset )
{
var first = -1;
for( var i = 0; i < chars.length; i++ )
{
var p = str.indexOf( chars[i] , offset );
if( p < first || first === -1 )
{
first = p;
}
}
return first;
}
String.prototype.mIndexOf = function( chars, offset )
{
return mIndexOf( this, chars, offset ); # I'm really averse to monkey patching.
};
mIndexOf( "hello world", ['a','o','w'], 0 );
>> 4
mIndexOf( "hello world", ['a'], 0 );
>> -1
mIndexOf( "hello world", ['a','o','w'], 4 );
>> 4
mIndexOf( "hello world", ['a','o','w'], 5 );
>> 6
mIndexOf( "hello world", ['a','o','w'], 7 );
>> -1
mIndexOf( "hello world", ['a','o','w','d'], 7 );
>> 10
mIndexOf( "hello world", ['a','o','w','d'], 10 );
>> 10
mIndexOf( "hello world", ['a','o','w','d'], 11 );
>> -1
Parameters in the URL are GET parameters, a request body, if present, is POST data. So your basic premise is by definition not achievable.
You should choose whether to use POST or GET based on the action. Any destructive action, i.e. something that permanently changes the state of the server (deleting, adding, editing) should always be invoked by POST requests. Any pure "information retrieval" should be accessible via an unchanging URL (i.e. GET requests).
To make a POST request, you need to create a <form>
. You could use Javascript to create a POST request instead, but I wouldn't recommend using Javascript for something so basic. If you want your submit button to look like a link, I'd suggest you create a normal form with a normal submit button, then use CSS to restyle the button and/or use Javascript to replace the button with a link that submits the form using Javascript (depending on what reproduces the desired behavior better). That'd be a good example of progressive enhancement.
if (code.indexOf("ST1")>=0) { location = "stoke central"; }
WordUtils.capitalizeFully(str)
from apache commons-lang has the exact semantics as required.
The answer below is apparently obsolete now, but works with older drivers. See comments.
If you have the connection string you could also use MongoDatabase directly:
var db = MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");
Here's my take on Carpetsmoker's answer (which I liked due to it being dynamic), cleaned up and updated for select2 v4:
$('#selectField').on('select2:open', function (e) {
var container = $(this).select('select2-container');
var position = container.offset().top;
var availableHeight = $(window).height() - position - container.outerHeight();
var bottomPadding = 50; // Set as needed
$('ul.select2-results__options').css('max-height', (availableHeight - bottomPadding) + 'px');
});
From the matplotlib docs on scatter 1:
cmap is only used if c is an array of floats
So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.
How does this work for you?
import matplotlib.pyplot as plt
cm = plt.cm.get_cmap('RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)
plt.colorbar(sc)
plt.show()
You can use the attribute selector here:
input[type="text"] {
font-family: Arial, sans-serif;
}
This is supported in IE7 and above. You can use IE7.js to add support for this if you need to support IE6.
See: http://reference.sitepoint.com/css/attributeselector for more information
Given returned json from your://site.com:
[{text:"Text1", val:"Value1"},
{text:"Text2", val:"Value2"},
{text:"Text3", val:"Value3"}]
Use this:
$.getJSON("your://site.com", function(json){
$('#select').empty();
$('#select').append($('<option>').text("Select"));
$.each(json, function(i, obj){
$('#select').append($('<option>').text(obj.text).attr('value', obj.val));
});
});
You can find an easy guide here
The step are 2: - Copy the icon in the correct folder/folders - Change the AndroidManifest.xml
A statement contains a keyword.
An expression does not contain a keyword.
print "hello"
is statement, because print
is a keyword.
"hello"
is an expression, but list compression is against this.
The following is an expression statement, and it is true without list comprehension:
(x*2 for x in range(10))
This was considered a bug in 2013: https://jira.spring.io/browse/SPR-10180
and was fixed with version 3.2.2. Problem shouldn't occur in any versions after that and your code should work just fine.
This error can occur if you project is compiling with JDK 1.6 and you have dependencies compiled with Java 7.
There is an in-built stopword list in NLTK
made up of 2,400 stopwords for 11 languages (Porter et al), see http://nltk.org/book/ch02.html
>>> from nltk import word_tokenize
>>> from nltk.corpus import stopwords
>>> stop = set(stopwords.words('english'))
>>> sentence = "this is a foo bar sentence"
>>> print([i for i in sentence.lower().split() if i not in stop])
['foo', 'bar', 'sentence']
>>> [i for i in word_tokenize(sentence.lower()) if i not in stop]
['foo', 'bar', 'sentence']
I recommend looking at using tf-idf to remove stopwords, see Effects of Stemming on the term frequency?
One option is to use a numbers/tally table to drive an iterative process via a pseudo-set based query.
The general idea of char replacement can be demonstrated with a simple character map table approach:
create table charMap (srcChar char(1), replaceChar char(1))
insert charMap values ('a', 'z')
insert charMap values ('b', 'y')
create table testChar(srcChar char(1))
insert testChar values ('1')
insert testChar values ('a')
insert testChar values ('2')
insert testChar values ('b')
select
coalesce(charMap.replaceChar, testChar.srcChar) as charData
from testChar left join charMap on testChar.srcChar = charMap.srcChar
Then you can bring in the tally table approach to do the lookup on each character position in the string.
create table tally (i int)
declare @i int
set @i = 1
while @i <= 256 begin
insert tally values (@i)
set @i = @i + 1
end
create table testData (testString char(10))
insert testData values ('123a456')
insert testData values ('123ab456')
insert testData values ('123b456')
select
i,
SUBSTRING(testString, i, 1) as srcChar,
coalesce(charMap.replaceChar, SUBSTRING(testString, i, 1)) as charData
from testData cross join tally
left join charMap on SUBSTRING(testString, i, 1) = charMap.srcChar
where i <= LEN(testString)
I suspect you don't actually have that problem - I suspect you've really got:
double a = callSomeFunction();
// Examine a in the debugger or via logging, and decide it's 3669.0
// Now cast
int b = (int) a;
// Now a is 3668
What makes me say that is that although it's true that many decimal values cannot be stored exactly in float
or double
, that doesn't hold for integers of this kind of magnitude. They can very easily be exactly represented in binary floating point form. (Very large integers can't always be exactly represented, but we're not dealing with a very large integer here.)
I strongly suspect that your double
value is actually slightly less than 3669.0, but it's being displayed to you as 3669.0 by whatever diagnostic device you're using. The conversion to an integer value just performs truncation, not rounding - hence the issue.
Assuming your double
type is an IEEE-754 64-bit type, the largest value which is less than 3669.0 is exactly
3668.99999999999954525264911353588104248046875
So if you're using any diagnostic approach where that value would be shown as 3669.0, then it's quite possible (probable, I'd say) that this is what's happening.
angular.element(domElement).triggerHandler('click');
EDIT: It appears that you have to break out of the current $apply() cycle. One way to do this is using $timeout():
$timeout(function() {
angular.element(domElement).triggerHandler('click');
}, 0);
See fiddle: http://jsfiddle.net/t34z7/
I also face the same issue. When I used right click in the query window and select Query Options. But header rows does not show up in output CSV file.
Then I logoff the server, login again and run the script. Then it worked.
Did you try:
$(this).is(':focus');
Take a look at Using jQuery to test if an input has focus it features some more examples
In this case you need to go up to the <tr>
then use .next()
, like this:
$(obj).closest('tr').next().find('.class');
Or if there may be rows in-between without the .class
inside, you can use .nextAll()
, like this:
$(obj).closest('tr').nextAll(':has(.class):first').find('.class');
Here is a simple one"
public class Palindrome {
public static void main(String [] args){
Palindrome pn = new Palindrome();
if(pn.isPalindrome("ABBA")){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
public boolean isPalindrome(String original){
int i = original.length()-1;
int j=0;
while(i > j) {
if(original.charAt(i) != original.charAt(j)) {
return false;
}
i--;
j++;
}
return true;
}
}
I am a happy boost user and would certainly use Andreas' solution. But if you didn't have access to the boost libs you can use the stream library:
ifstream file(argv[1]);
if (!file)
{
// Can't open file
}
It's not quite as nice as boost::filesystem::exists since the file will actually be opened...but then that's usually the next thing you want to do anyway.
js> s = "http://www.example.com/string with + and ? and & and spaces";
http://www.example.com/string with + and ? and & and spaces
js> encodeURI(s)
http://www.example.com/string%20with%20+%20and%20?%20and%20&%20and%20spaces
js> encodeURIComponent(s)
http%3A%2F%2Fwww.example.com%2Fstring%20with%20%2B%20and%20%3F%20and%20%26%20and%20spaces
Looks like encodeURI
produces a "safe" URI by encoding spaces and some other (e.g. nonprintable) characters, whereas encodeURIComponent
additionally encodes the colon and slash and plus characters, and is meant to be used in query strings. The encoding of + and ? and & is of particular importance here, as these are special chars in query strings.
Angular RC5 & RC6
If you are getting the above mentioned error in your Jasmine tests, it is most likely because you have to declare the unrenderable component in your TestBed.configureTestingModule({})
.
The TestBed configures and initializes an environment for unit testing and provides methods for mocking/creating/injecting components and services in unit tests.
If you don't declare the component before your unit tests are executed, Angular will not know what <courses></courses>
is in your template file.
Here is an example:
import {async, ComponentFixture, TestBed} from "@angular/core/testing";
import {AppComponent} from "../app.component";
import {CoursesComponent} from './courses.component';
describe('CoursesComponent', () => {
let component: CoursesComponent;
let fixture: ComponentFixture<CoursesComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
CoursesComponent
],
imports: [
BrowserModule
// If you have any other imports add them here
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CoursesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
In the other answers the proposed template function is a facade and doesn't offer any practical benefit.
The language doesn't allow virtual template functions but with a workaround it is possible to have both, e.g. one template implementation for each class and a virtual common interface.
It is however necessary to define for each template type combination a dummy virtual wrapper function:
#include <memory>
#include <iostream>
#include <iomanip>
//---------------------------------------------
// Abstract class with virtual functions
class Geometry {
public:
virtual void getArea(float &area) = 0;
virtual void getArea(long double &area) = 0;
};
//---------------------------------------------
// Square
class Square : public Geometry {
public:
float size {1};
// virtual wrapper functions call template function for square
virtual void getArea(float &area) { getAreaT(area); }
virtual void getArea(long double &area) { getAreaT(area); }
private:
// Template function for squares
template <typename T>
void getAreaT(T &area) {
area = static_cast<T>(size * size);
}
};
//---------------------------------------------
// Circle
class Circle : public Geometry {
public:
float radius {1};
// virtual wrapper functions call template function for circle
virtual void getArea(float &area) { getAreaT(area); }
virtual void getArea(long double &area) { getAreaT(area); }
private:
// Template function for Circles
template <typename T>
void getAreaT(T &area) {
area = static_cast<T>(radius * radius * 3.1415926535897932385L);
}
};
//---------------------------------------------
// Main
int main()
{
// get area of square using template based function T=float
std::unique_ptr<Geometry> geometry = std::make_unique<Square>();
float areaSquare;
geometry->getArea(areaSquare);
// get area of circle using template based function T=long double
geometry = std::make_unique<Circle>();
long double areaCircle;
geometry->getArea(areaCircle);
std::cout << std::setprecision(20) << "Square area is " << areaSquare << ", Circle area is " << areaCircle << std::endl;
return 0;
}
Output:
Square area is 1, Circle area is 3.1415926535897932385
Try it here
You can reference the image using relative path:
<img src="../images/logo.png">
__ ______ ________
| | |
| | |___ 3. Get the file named "logo.png"
| |
| |___ 2. Go inside "images/" subdirectory
|
|
|____ 1. Go one level up
Or you can use absolute path: /
means that this is an absolute path on the server, So if your server is at https://example.org/, referencing /images/logo.png
from any page would point to https://example.org/images/logo.png
<img src="/images/logo.png">
|______ ________
| | |
| | |___ 3. Get the file named "logo.png"
| |
| |___ 2. Go inside "images/" subdirectory
|
|
|____ 1. Go to the root folder
You could name the anonymous delegate :-)
And you can write the second as:
someList.ForEach(s => s.ToUpper())
Which I prefer, and saves a lot of typing.
As Joachim says, parallelism is easier to apply to the second form.
This works for making disabled select options act as headers. It doesnt remove the default text shadow of the :disabled option but it does remove the hover effect. In IE you wont get the font color but at least the text-shadow is gone. Here is the html and css:
select option.disabled:disabled{color: #5C3333;background-color: #fff;font-weight: bold;}_x000D_
select option.disabled:hover{color: #5C3333 !important;background-color: #fff;}_x000D_
select option:hover{color: #fde8c4;background-color: #5C3333;}
_x000D_
<select>_x000D_
<option class="disabled" disabled>Header1</option>_x000D_
<option>Item1</option>_x000D_
<option>Item1</option>_x000D_
<option>Item1</option>_x000D_
<option class="disabled" disabled>Header2</option>_x000D_
<option>Item2</option>_x000D_
<option>Item2</option>_x000D_
<option>Item2</option>_x000D_
<option class="disabled" disabled>Header3</option>_x000D_
<option>Item3</option>_x000D_
<option>Item3</option>_x000D_
<option>Item3</option>_x000D_
</select>
_x000D_
Using Counter would be the best way, but if you don't want to do that, you can implement it yourself this way.
# The list you already have
word_list = ['words', ..., 'other', 'words']
# Get a set of unique words from the list
word_set = set(word_list)
# create your frequency dictionary
freq = {}
# iterate through them, once per unique word.
for word in word_set:
freq[word] = word_list.count(word) / float(len(word_list))
freq will end up with the frequency of each word in the list you already have.
You need float
in there to convert one of the integers to a float, so the resulting value will be a float.
Edit:
If you can't use a dict or set, here is another less efficient way:
# The list you already have
word_list = ['words', ..., 'other', 'words']
unique_words = []
for word in word_list:
if word not in unique_words:
unique_words += [word]
word_frequencies = []
for word in unique_words:
word_frequencies += [float(word_list.count(word)) / len(word_list)]
for i in range(len(unique_words)):
print(unique_words[i] + ": " + word_frequencies[i])
The indicies of unique_words
and word_frequencies
will match.
You will not write code into a static block that needs to be invoked anywhere in your program. If the purpose of the code is to be invoked then you must place it in a method.
You can write static initializer blocks to initialize static variables when the class is loaded but this code can be more complex..
A static initializer block looks like a method with no name, no arguments, and no return type. Since you never call it it doesn't need a name. The only time its called is when the virtual machine loads the class.
&
is always evaluated in a string context, while +
may not concatenate if one of the operands is no string:
"1" + "2" => "12"
"1" + 2 => 3
1 + "2" => 3
"a" + 2 => type mismatch
This is simply a subtle source of potential bugs and therefore should be avoided. &
always means "string concatenation", even if its arguments are non-strings:
"1" & "2" => "12"
"1" & 2 => "12"
1 & "2" => "12"
1 & 2 => "12"
"a" & 2 => "a2"
The simpler way is:
with open("outfile", "w") as outfile:
outfile.write("\n".join(itemlist))
You could ensure that all items in item list are strings using a generator expression:
with open("outfile", "w") as outfile:
outfile.write("\n".join(str(item) for item in itemlist))
Remember that all itemlist
list need to be in memory, so, take care about the memory consumption.
One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:
test_json = { "a": 1, "b": 2}
Once you do this, adding a json element only involves the following line:
test_json["c"] = 3
This will result in:
{'a': 1, 'b': 2, 'c': 3}
Afterwards, you can add that json back into an array or a list of that is desired.
As aditional information on @Quentin answer, and as he rightly says,
background
CSS property itself, is a shorthand for:
background-color
background-image
background-repeat
background-attachment
background-position
That's mean, you can group all styles in one, like:
background: red url(../img.jpg) 0 0 no-repeat fixed;
This would be (in this example):
background-color: red;
background-image: url(../img.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;
So... when you set: background:none;
you are saying that all the background properties are set to none...
You are saying that background-image: none;
and all the others to the initial
state (as they are not being declared).
So, background:none;
is:
background-color: initial;
background-image: none;
background-repeat: initial;
background-attachment: initial;
background-position: initial;
Now, when you define only the color (in your case transparent
) then you are basically saying:
background-color: transparent;
background-image: initial;
background-repeat: initial;
background-attachment: initial;
background-position: initial;
I repeat, as @Quentin rightly says the default
transparent
and none
values in this case are the same, so in your example and for your original question, No, there's no difference between them.
But!.. if you say background:none
Vs background:red
then yes... there's a big diference, as I say, the first would set all properties to none/default
and the second one, will only change the color
and remains the rest in his default
state.
Short answer: No, there's no difference at all (in your example and orginal question)
Long answer: Yes, there's a big difference, but depends directly on the properties granted to attribute.
default
)Initial value the concatenation of the initial values of its longhand properties:
background-image: none
background-position: 0% 0%
background-size: auto auto
background-repeat: repeat
background-origin: padding-box
background-style: is itself a shorthand, its initial value is the concatenation of its own longhand properties
background-clip: border-box
background-color: transparent
background
descriptions hereUpd2: Clarify better the background:none;
specification.
Should be in
Program Files>Microsoft SQL Server>MSSQL 1.0>MSSQL>BACKUP>
In my case it is
C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup
If you use the gui or T-SQL you can specify where you want it T-SQL example
BACKUP DATABASE [YourDB] TO DISK = N'SomePath\YourDB.bak'
WITH NOFORMAT, NOINIT, NAME = N'YourDB Full Database Backup',
SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO
With T-SQL you can also get the location of the backup, see here Getting the physical device name and backup time for a SQL Server database
SELECT physical_device_name,
backup_start_date,
backup_finish_date,
backup_size/1024.0 AS BackupSizeKB
FROM msdb.dbo.backupset b
JOIN msdb.dbo.backupmediafamily m ON b.media_set_id = m.media_set_id
WHERE database_name = 'YourDB'
ORDER BY backup_finish_date DESC
Wanted to add numexpr into the mix:
import numpy as np
import numexpr as ne
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.where(ne.evaluate("(6 <= a) & (a <= 10)"))[0]
# array([3, 4, 5], dtype=int64)
Would only make sense for larger arrays with millions... or if you hitting a memory limits.
http://pinvoke.net/default.aspx/user32.EnumDesktopWindows
There is an example of using user.dll's EnumWindow in C# to list all open windows.
Set up invironment variable in Advanced System Settings. In Command prompt it should behave like this :
C:\Windows\system32>echo %http_proxy%
http://username:passowrd@proxy:port
C:\Windows\system32>echo %https_proxy%
Later , Simply
pip install whatEver
should work.
It is not possible to add comments to 'normal' Access queries, that is, a QueryDef in an mdb, which is why a number of people recommend storing the sql for queries in a table.
If the users enter an incorrect value, apply a 1px red color border to the input field:
document.getElementById('fName').style.border ="1px solid red";
If the user enters a correct value, remove the border from the input field:
document.getElementById('fName').style.border ="";
I would like to add an answer to this that hasn't been mentioned, as I have tried all of the above to no avail. My specific situation is that I am using semantic-ui, which has built in !important
attributes on elements (extremely annoying). I tried everything to override it, only in the end did one thing work (using jquery). It is as follows:
$('.active').css('cssText', 'border-radius: 0px !important');
SQlite does not have a specific datetime type. You can use TEXT
, REAL
or INTEGER
types, whichever suits your needs.
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
- TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
- REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
- INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
SQLite built-in Date and Time functions can be found here.
If the other answers don't work you can check if something else is using the port with netstat:
netstat -ano | findstr <your port number>
If nothing is already using it, the port might be excluded, try this command to see if the range is blocked by something else:
netsh interface ipv4 show excludedportrange protocol=tcp
I'm using Conda on Windows and this answer did not work for me. But I can suggest another solution:
rename enviroment folder (old_name
to new_name
)
open shell and activate env with custom folder:
conda.bat activate "C:\Users\USER_NAME\Miniconda3\envs\new_name"
now you can use this enviroment, but it's not on the enviroment list. Update\install\remove any package to fix it. For example, update numpy:
conda update numpy
after applying any action to package, the environment will show in env list. To check this, type:
conda env list
You can use the following code in modern browsers to efficiently check the storage quota (total & used) in real-time:
if ('storage' in navigator && 'estimate' in navigator.storage) {
navigator.storage.estimate()
.then(estimate => {
console.log("Usage (in Bytes): ", estimate.usage,
", Total Quota (in Bytes): ", estimate.quota);
});
}
Don'y forget that if you are mixing grouped (ie. SUM) fields and non-grouped fields, you need to GROUP BY one of the non-grouped fields.
Try this:
SELECT SUM(something) AS fieldname
FROM tablename
ORDER BY fieldname
OR this:
SELECT Field1, SUM(something) AS Field2
FROM tablename
GROUP BY Field1
ORDER BY Field2
And you can always do a derived query like this:
SELECT
f1, f2
FROM
(
SELECT SUM(x+y) as f1, foo as F2
FROM tablename
GROUP BY f2
) as table1
ORDER BY
f1
Many possibilities!
From the man page:
search, -S text|/text/ Perform a substring search of formula names for text. If text is surrounded with slashes, then it is interpreted as a regular expression. If no search term is given, all available formula are displayed.
For your purposes, brew search
will suffice.
I just felt like I'll add my $0.2 to those 2 good answers. I had a case when I had to move the last column all the way to the top in a 3-column situation.
[A][B][C]
to
[C]
[A]
[B]
Boostrap's class .col-xx-push-X
does nothing else but pushes a column to the right with left: XX%;
so all you have to do to push a column right is to add the number of pseudo columns going left.
In this case:
two columns (col-md-5
and col-md-3
) are going left, each with the value of the one that is going right;
one(col-md-4
) is going right by the sum of the first two going left (5+3=8);
<div class="row">
<div class="col-md-4 col-md-push-8 ">
C
</div>
<div class="col-md-5 col-md-pull-4">
A
</div>
<div class="col-md-3 col-md-pull-4">
B
</div>
</div>
This works for me like a charm
this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
this.router.navigate([<route>]));
I think nt86's solution is the most appropriate because it leverages the underlying Windows infrastructure (certificate store). But it doesn't explain how to install python-certifi-win32 to start with since pip is non functional.
The trick is to use --trustedhost
to install python-certifi-win32 and then after that, pip will automatically use the windows certificate store to load the certificate used by the proxy.
So in a nutshell, you should do:
pip install python-certifi-win32 -trustedhost pypi.org
and after that you should be good to go
Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.
I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.
If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.
app.get('*',function(req,res){
res.redirect('/login');
});
One thing i would like to add
In a signed int
, which is the default value in mysql
, 1 bit
will be used to represent sign
. -1 for negative and 0 for positive.
So if your application insert only positive value it should better specify unsigned.
ALTER TABLE <table_name> MODIFY <column_name> DEFAULT <defult_value>
EX: ALTER TABLE AAA MODIFY ID DEFAULT AAA_SEQUENCE.nextval
Tested on Oracle Database 12c Enterprise Edition Release 12.2.0.1.0
For documentation purpose, it's better to list the string values that are legal:
size: PropTypes.oneOfType([
PropTypes.number,
PropTypes.oneOf([ 'SMALL', 'LARGE' ]),
]),
Here's another possible reason besides the console.log
issue (at least in IE11):
When the console is not open, IE does pretty aggressive caching, so make sure that any $.ajax
calls or XMLHttpRequest
calls have caching set to false.
For example:
$.ajax({cache: false, ...})
When the developer console is open, caching is less aggressive. Seems to be a bug (or maybe a feature?)
;with C as
(
select Rel.t2ID,
Rel.t1ID,
t1.Price,
row_number() over(partition by Rel.t2ID order by t1.Price desc) as rn
from @t1 as T1
inner join @relation as Rel
on T1.ID = Rel.t1ID
)
select T2.ID as T2ID,
T2.Name as T2Name,
T2.Orders,
T1.ID as T1ID,
T1.Name as T1Name,
T1Sum.Price
from @t2 as T2
inner join (
select C1.t2ID,
sum(C1.Price) as Price,
C2.t1ID
from C as C1
inner join C as C2
on C1.t2ID = C2.t2ID and
C2.rn = 1
group by C1.t2ID, C2.t1ID
) as T1Sum
on T2.ID = T1Sum.t2ID
inner join @t1 as T1
on T1.ID = T1Sum.t1ID
There is comma missing in your tuple.
insert the comma between the tuples as shown:
pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))
Do the same for all
I realize this is quite late, but I needed something like this so I whipped up a quick and dirty method to do this.
+ (UIImage *) image:(UIImage *)image withAlpha:(CGFloat)alpha{
// Create a pixel buffer in an easy to use format
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
UInt8 * m_PixelBuf = malloc(sizeof(UInt8) * height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(m_PixelBuf, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
//alter the alpha
int length = height * width * 4;
for (int i=0; i<length; i+=4)
{
m_PixelBuf[i+3] = 255*alpha;
}
//create a new image
CGContextRef ctx = CGBitmapContextCreate(m_PixelBuf, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGImageRef newImgRef = CGBitmapContextCreateImage(ctx);
CGColorSpaceRelease(colorSpace);
CGContextRelease(ctx);
free(m_PixelBuf);
UIImage *finalImage = [UIImage imageWithCGImage:newImgRef];
CGImageRelease(newImgRef);
return finalImage;
}
I'm on Gson 2.8.6 and discovered this bug today.
My approach allows all our existing clients (mobile/web/etc) to continue functioning as they were, but adds some handling for those using 24h formats and allows millis too, for good measure.
Gson rawGson = new Gson();
SimpleDateFormat fmt = new SimpleDateFormat("MMM d, yyyy HH:mm:ss")
private class DateDeserializer implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
return new rawGson.fromJson(json, Date.class);
} catch (JsonSyntaxException e) {}
String timeString = json.getAsString();
log.warning("Standard date deserialization didn't work:" + timeString);
try {
return fmt.parse(timeString);
} catch (ParseException e) {}
log.warning("Parsing as json 24 didn't work:" + timeString);
return new Date(json.getAsLong());
}
}
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
I kept serialization the same as all clients understand the standard json date format.
Ordinarily, I don't think it's good practice to use try/catch blocks, but this should be a fairly rare case.
If we input something like [4, 2]
, we’ll get [2, 3, 4]
as output, we can work with that.
function createRange(array) {
var range = [];
var highest = array.reduce(function(a, b) {
return Math.max(a, b);
});
var lowest = array.reduce(function(a, b) {
return Math.min(a, b);
});
for (var i = lowest; i <= highest; i++) {
range.push(i);
}
return range;
}
If you are using IIS 7.5 or later you can generate the machine key from IIS and save it directly to your web.config, within the web farm you then just copy the new web.config to each server.
web.config
file of your application.web.config
file.Full Details can be seen @ Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS and .NET development…
The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html
user this full solution to convert gridview to datatable
public DataTable gridviewToDataTable(GridView gv)
{
DataTable dtCalculate = new DataTable("TableCalculator");
// Create Column 1: Date
DataColumn dateColumn = new DataColumn();
dateColumn.DataType = Type.GetType("System.DateTime");
dateColumn.ColumnName = "date";
// Create Column 3: TotalSales
DataColumn loanBalanceColumn = new DataColumn();
loanBalanceColumn.DataType = Type.GetType("System.Double");
loanBalanceColumn.ColumnName = "loanbalance";
DataColumn offsetBalanceColumn = new DataColumn();
offsetBalanceColumn.DataType = Type.GetType("System.Double");
offsetBalanceColumn.ColumnName = "offsetbalance";
DataColumn netloanColumn = new DataColumn();
netloanColumn.DataType = Type.GetType("System.Double");
netloanColumn.ColumnName = "netloan";
DataColumn interestratecolumn = new DataColumn();
interestratecolumn.DataType = Type.GetType("System.Double");
interestratecolumn.ColumnName = "interestrate";
DataColumn interestrateperdaycolumn = new DataColumn();
interestrateperdaycolumn.DataType = Type.GetType("System.Double");
interestrateperdaycolumn.ColumnName = "interestrateperday";
// Add the columns to the ProductSalesData DataTable
dtCalculate.Columns.Add(dateColumn);
dtCalculate.Columns.Add(loanBalanceColumn);
dtCalculate.Columns.Add(offsetBalanceColumn);
dtCalculate.Columns.Add(netloanColumn);
dtCalculate.Columns.Add(interestratecolumn);
dtCalculate.Columns.Add(interestrateperdaycolumn);
foreach (GridViewRow row in gv.Rows)
{
DataRow dr;
dr = dtCalculate.NewRow();
dr["date"] = DateTime.Parse(row.Cells[0].Text);
dr["loanbalance"] = double.Parse(row.Cells[1].Text);
dr["offsetbalance"] = double.Parse(row.Cells[2].Text);
dr["netloan"] = double.Parse(row.Cells[3].Text);
dr["interestrate"] = double.Parse(row.Cells[4].Text);
dr["interestrateperday"] = double.Parse(row.Cells[5].Text);
dtCalculate.Rows.Add(dr);
}
return dtCalculate;
}
This is how you do it, I have checked it and it works on my Laravel 4.2.
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
Hope this helps.
I made a fairly complete library of 3D mathematics for Python{2,3}. It still does not use Cython, but relies heavily on the efficiency of numpy. You can find it here with pip:
python[3] -m pip install math3d
Or have a look at my gitweb http://git.automatics.dyndns.dk/?p=pymath3d.git and now also on github: https://github.com/mortlind/pymath3d .
Once installed, in python you may create the orientation object which can rotate vectors, or be part of transform objects. E.g. the following code snippet composes an orientation that represents a rotation of 1 rad around the axis [1,2,3], applies it to the vector [4,5,6], and prints the result:
import math3d as m3d
r = m3d.Orientation.new_axis_angle([1,2,3], 1)
v = m3d.Vector(4,5,6)
print(r * v)
The output would be
<Vector: (2.53727, 6.15234, 5.71935)>
This is more efficient, by a factor of approximately four, as far as I can time it, than the oneliner using scipy posted by B. M. above. However, it requires installation of my math3d package.
<android.support.design.widget.TabLayout
android:id="@+id/tabList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:tabMode="scrollable"/>
hi how to delete from datagridview
1.make query delete by id
2.type
tabletableadaptor.delete
query(datagridwiewX1.selectedrows[0].cell[0].value.tostring);
You use:
class DerivedClassName(BaseClassName):
For details, see the Python docs, section 9.5.
I know the question is Old and already answered but this can also be a solution
\b[\w-]+$
and I checked these two URLs
http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos
Using the filter() function seems to work in your test cases (tested in Firefox). The selector would look like this:
$('#mySelect1 option').filter(function () {
return $(this).text() === 'Banana';
});
The below answer is in reference to the latest ng-bootstrap
Install
npm install --save @ng-bootstrap/ng-bootstrap
app.module.ts
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [
...
],
imports: [
...
NgbModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Component Controller
import { TemplateRef, ViewChild } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-app-registration',
templateUrl: './app-registration.component.html',
styleUrls: ['./app-registration.component.css']
})
export class AppRegistrationComponent implements OnInit {
@ViewChild('editModal') editModal : TemplateRef<any>; // Note: TemplateRef
constructor(private modalService: NgbModal) { }
openModal(){
this.modalService.open(this.editModal);
}
}
Component HTML
<ng-template #editModal let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Edit Form</h4>
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="dateOfBirth">Date of birth</label>
<div class="input-group">
<input id="dateOfBirth" class="form-control" placeholder="yyyy-mm-dd" name="dp" ngbDatepicker #dp="ngbDatepicker">
<div class="input-group-append">
<button class="btn btn-outline-secondary calendar" (click)="dp.toggle()" type="button"></button>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="modal.close()">Save</button>
</div>
</ng-template>
This code work
pwindo = new PopupWindow(layout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
pwindo.setOutsideTouchable(false);
View container = (View) pwindo.getContentView().getParent();
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams();
p.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
p.dimAmount = 0.3f;
wm.updateViewLayout(container, p);
try this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""FileTreeMaker.py: ..."""
__author__ = "legendmohe"
import os
import argparse
import time
class FileTreeMaker(object):
def _recurse(self, parent_path, file_list, prefix, output_buf, level):
if len(file_list) == 0 \
or (self.max_level != -1 and self.max_level <= level):
return
else:
file_list.sort(key=lambda f: os.path.isfile(os.path.join(parent_path, f)))
for idx, sub_path in enumerate(file_list):
if any(exclude_name in sub_path for exclude_name in self.exn):
continue
full_path = os.path.join(parent_path, sub_path)
idc = "??"
if idx == len(file_list) - 1:
idc = "??"
if os.path.isdir(full_path) and sub_path not in self.exf:
output_buf.append("%s%s[%s]" % (prefix, idc, sub_path))
if len(file_list) > 1 and idx != len(file_list) - 1:
tmp_prefix = prefix + "? "
else:
tmp_prefix = prefix + " "
self._recurse(full_path, os.listdir(full_path), tmp_prefix, output_buf, level + 1)
elif os.path.isfile(full_path):
output_buf.append("%s%s%s" % (prefix, idc, sub_path))
def make(self, args):
self.root = args.root
self.exf = args.exclude_folder
self.exn = args.exclude_name
self.max_level = args.max_level
print("root:%s" % self.root)
buf = []
path_parts = self.root.rsplit(os.path.sep, 1)
buf.append("[%s]" % (path_parts[-1],))
self._recurse(self.root, os.listdir(self.root), "", buf, 0)
output_str = "\n".join(buf)
if len(args.output) != 0:
with open(args.output, 'w') as of:
of.write(output_str)
return output_str
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--root", help="root of file tree", default=".")
parser.add_argument("-o", "--output", help="output file name", default="")
parser.add_argument("-xf", "--exclude_folder", nargs='*', help="exclude folder", default=[])
parser.add_argument("-xn", "--exclude_name", nargs='*', help="exclude name", default=[])
parser.add_argument("-m", "--max_level", help="max level",
type=int, default=-1)
args = parser.parse_args()
print(FileTreeMaker().make(args))
you will get this:
root:.
[.]
??[.idea]
? ??[scopes]
? ? ??scope_settings.xml
? ??.name
? ??Demo.iml
? ??encodings.xml
? ??misc.xml
? ??modules.xml
? ??vcs.xml
? ??workspace.xml
??[test1]
? ??test1.txt
??[test2]
? ??[test2-2]
? ? ??[test2-3]
? ? ??test2
? ? ??test2-3-1
? ??test2
??folder_tree_maker.py
??tree.py
You can also do:
return InternalServerError(new Exception("SOME CUSTOM MESSAGE"));
If you are using Maven, you can run it from the cmd line really easy, cd into the directory with the testng.xml (or whatever yours is called, the xml that has all the classes that will run) and run this cmd:
mvn clean test -DsuiteXmlFile=testng.xml
This page explains it in much more detail: How to run testng.xml from Maven command line
I didn't know it mattered if you were using Maven or not so I didn't include it in my search terms, I thought I would mention it here in case others are in the same situation as I was.
use:
$scope.users.length;
Instead of:
$scope.users.lenght;
And next time "spell-check" your code.
Add
<mvc:default-servlet-handler/>
to spring-servlet.xml
~/Desktop $ ng serve
Local workspace file ('angular.json') could not be found.
Error: Local workspace file ('angular.json') could not be found.
at WorkspaceLoader._getProjectWorkspaceFilePath (/usr/lib/node_modules/@angular/cli/models/workspace-loader.js:37:19)
at WorkspaceLoader.loadWorkspace (/usr/lib/node_modules/@angular/cli/models/workspace-loader.js:24:21)
at ServeCommand._loadWorkspaceAndArchitect (/usr/lib/node_modules/@angular/cli/models/architect-command.js:180:32)
at ServeCommand.<anonymous> (/usr/lib/node_modules/@angular/cli/models/architect-command.js:47:25)
at Generator.next (<anonymous>)
at /usr/lib/node_modules/@angular/cli/models/architect-command.js:7:71
at new Promise (<anonymous>)
at __awaiter (/usr/lib/node_modules/@angular/cli/models/architect-command.js:3:12)
at ServeCommand.initialize (/usr/lib/node_modules/@angular/cli/models/architect-command.js:46:16)
at Object.<anonymous> (/usr/lib/node_modules/@angular/cli/models/command-runner.js:87:23)
This is because I haven't choose the Angular project directory.
It should be like:
~/Desktop/angularproject $ ng serve
As other people have said, the reason this happens is that the parent repo only contains a reference to (the SHA1 of) a specific commit in the submodule – it doesn't know anything about branches. This is how it should work: the branch that was at that commit may have moved forward (or backwards), and if the parent repo had referenced the branch then it could easily break when that happens.
However, especially if you are actively developing in both the parent repo and the submodule, detached HEAD
state can be confusing and potentially dangerous. If you make commits in the submodule while it's in detached HEAD
state, these become dangling and you can easily lose your work. (Dangling commits can usually be rescued using git reflog
, but it's much better to avoid them in the first place.)
If you're like me, then most of the time if there is a branch in the submodule that points to the commit being checked out, you would rather check out that branch than be in detached HEAD state at the same commit. You can do this by adding the following alias to your gitconfig
file:
[alias]
submodule-checkout-branch = "!f() { git submodule -q foreach 'branch=$(git branch --no-column --format=\"%(refname:short)\" --points-at `git rev-parse HEAD` | grep -v \"HEAD detached\" | head -1); if [[ ! -z $branch && -z `git symbolic-ref --short -q HEAD` ]]; then git checkout -q \"$branch\"; fi'; }; f"
Now, after doing git submodule update
you just need to call git submodule-checkout-branch
, and any submodule that is checked out at a commit which has a branch pointing to it will check out that branch. If you don't often have multiple local branches all pointing to the same commit, then this will usually do what you want; if not, then at least it will ensure that any commits you do make go onto an actual branch instead of being left dangling.
Furthermore, if you have set up git to automatically update submodules on checkout (using git config --global submodule.recurse true
, see this answer), you can make a post-checkout hook that calls this alias automatically:
$ cat .git/hooks/post-checkout
#!/bin/sh
git submodule-checkout-branch
Then you don't need to call either git submodule update
or git submodule-checkout-branch
, just doing git checkout
will update all submodules to their respective commits and check out the corresponding branches (if they exist).
I needed to be able to "border" any element by adding a class and not affect its dimensions. A good solution for me was to use box-shadow. But in some cases the effect was not visible due to other siblings. So I combined both typical box-shadow as well as inset box-shadow. The result is a border look without changing any dimensions.
Values separated by comma. Here's a simple example:
.add_border {
box-shadow:-1px 0 1px 1px rgba(0, 0, 0, 0.75), inset -1px 0 0 1px rgba(0, 0, 0, 0.75);
}
Adjust for your preferred look and you're good to go!
winutils.exe are required for hadoop to perform hadoop related commands. please download hadoop-common-2.2.0 zip file. winutils.exe can be found in bin folder. Extract the zip file and copy it in the local hadoop/bin folder.
SELECT emp.LoginID, emp.JobTitle, emp.BirthDate, emp.ModifiedDate ,
CASE WHEN emp.JobTitle NOT LIKE '%Document Control%' THEN emp.JobTitle
ELSE SUBSTRING(emp.JobTitle,CHARINDEX('Document Control',emp.JobTitle),LEN('Document Control'))
END
,emp.gender,emp.MaritalStatus
FROM HumanResources.Employee [emp]
WHERE JobTitle LIKE '[C-F]%'
Invariant is a linguistically appropriate type of comparison.
Ordinal is a binary type of comparison. (faster)
See http://www.siao2.com/2004/12/29/344136.aspx
Session.Abandon()
destroys the session and the Session_OnEnd event is triggered.
Session.Clear()
just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon()
, you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear()
, if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.
Github documentation contains a script that replaces the committer info for all commits in a branch.
Run the following script from terminal after changing the variable values
#!/bin/sh
git filter-branch --env-filter '
OLD_EMAIL="[email protected]"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="[email protected]"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags
Push the corrected history to GitHub:
git push --force --tags origin 'refs/heads/*'
OR if you like to push selected references of the branches then use
git push --force --tags origin 'refs/heads/develop'
Hope this will help!
@OneToOne(optional = false)
@JoinColumn(name = "department_id", insertable = false, updatable = false)
@JsonManagedReference
private Department department;
@JsonIgnore
public Department getDepartment() {
return department;
}
@OneToOne(mappedBy = "department")
private Designation designation;
@JsonIgnore
public Designation getDesignation() {
return designation;
}
Go to MySQL installation directory and open cmd from there. Then execute the below command to get a backup of your database.
mysqldump -u root -p --add-drop-database --databases db> C:\db-dontdelete\db.sql
The problem was the table width. I had used width: 100%
for the table. The table columns are adjusted automatically after removing the width tag.
Check out this POC or MVP of running in parallel one-host-from-every-group (for all hosts) https://github.com/sirkubax/szkolenie3/tree/master/playbooks/playgroups
you may get the inspiration
Because, it is not supposed to do that.
input[type=text] { }
is an attribute selector, and will only select those element, with the matching attribute.
MySQL uses CONCAT() to concatenate strings
SELECT * FROM tableOne
LEFT JOIN tableTwo
ON tableTwo.query = CONCAT('category_id=', tableOne.category_id)
You can combine both in the same date function call
date("d-m-Y H:i:s");
For a quick solution, you can use AtomicInteger or any of the atomic variables which will let you change the value inside the method using the inbuilt methods. Here is sample code:
import java.util.concurrent.atomic.AtomicInteger;
public class PrimitivePassByReferenceSample {
/**
* @param args
*/
public static void main(String[] args) {
AtomicInteger myNumber = new AtomicInteger(0);
System.out.println("MyNumber before method Call:" + myNumber.get());
PrimitivePassByReferenceSample temp = new PrimitivePassByReferenceSample() ;
temp.changeMyNumber(myNumber);
System.out.println("MyNumber After method Call:" + myNumber.get());
}
void changeMyNumber(AtomicInteger myNumber) {
myNumber.getAndSet(100);
}
}
Output:
MyNumber before method Call:0
MyNumber After method Call:100
Use the -S (note: capital S) switch to GCC, and it will emit the assembly code to a file with a .s extension. For example, the following command:
gcc -O2 -S foo.c
will leave the generated assembly code on the file foo.s.
Ripped straight from http://www.delorie.com/djgpp/v2faq/faq8_20.html (but removing erroneous -c
)
The best practice would be to create a module separately which has only one method whose task we be to give a logger handler to the the calling method. Save this file as m_logger.py
import logger, logging
def getlogger():
# logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
#ch = logging.StreamHandler()
ch = logging.FileHandler(r'log.txt')
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
return logger
Now call the getlogger() method whenever logger handler is needed.
from m_logger import getlogger
logger = getlogger()
logger.info('My mssg')
If you use PHP7, use Throwable in catch
for catching user exceptions and fatal errors.
For example:
DB::beginTransaction();
try {
DB::insert(...);
DB::commit();
} catch (\Throwable $e) {
DB::rollback();
throw $e;
}
If your code must be compartable with PHP5, use Exception
and Throwable
:
DB::beginTransaction();
try {
DB::insert(...);
DB::commit();
} catch (\Exception $e) {
DB::rollback();
throw $e;
} catch (\Throwable $e) {
DB::rollback();
throw $e;
}
Reference link: http://www.programering.com/a/MTNyUDMwATA.html
Steps I followed
1) Execute the command adb nodaemon server
in command prompt
Output at command prompt will be: The following error occurred cannot bind 'tcp:5037'
The original ADB server port binding failed
2) Enter the following command query which using port 5037
netstat -ano | findstr "5037"
The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288
3) View the task manager, close all adb.exe
4) Restart eclipse or other IDE
The above steps worked for me.
You can get rid of the first line. You don't need import java.lang.*;
Just change your 5th line to:
public static void main(String [] args) throws Exception
Your query should look like
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
You can check the below question for help
Since you want to append elements to existing list, you can use var List[Int] and then keep on adding elements to the same list. Note -> You have to make sure that you insert an element into existing list as follows:-
var l: List[int] = List() // creates an empty list
l = 3 :: l // adds 3 to the head of the list
l = 4 :: l // makes int 4 as the head of the list
// Now when you will print l, you will see two elements in the list ( 4, 3)
Try this.
var dateAsString = DateTime.Now.ToString("dd/MM/yyyy");
// dateAsString = "09/07/2013"
If youR data was in A1:C100
then:
Excel - all versions
=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))
Excel - 2007 onwards
=COUNTIFS(A1:A100,"M",C1:C100,"Yes")
There is a subtle issue here that is a bit of a gotcha.
The toString()
method has a base implementation in Object
. CharSequence
is an interface; and although the toString()
method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence
toString()
method's javadoc puts on the toString()
method; ie that it should return a string containing the characters in the order returned by charAt()
.
Your IDE won't even help you out by reminding that you that you probably should override toString()
. For example, in intellij, this is what you'll see if you create a new CharSequence
implementation: http://puu.sh/2w1RJ. Note the absence of toString()
.
If you rely on toString()
on an arbitrary CharSequence
, it should work provided the CharSequence
implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder
and append()
, like so:
final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();
Always safe to use either Comparator or Comparable interface to provide sorting implementation (if the object is not a String or Wrapper classes for primitive data types) . As an example for a comparator implementation to sort employees based on name
List<Employees> empList = new LinkedList<Employees>(EmpSet);
class EmployeeComparator implements Comparator<Employee> {
public int compare(Employee e1, Employee e2) {
return e1.getName().compareTo(e2.getName());
}
}
Collections.sort(empList , new EmployeeComparator ());
Comparator is useful when you need to have different sorting algorithm on same object (Say emp name, emp salary, etc). Single mode sorting can be implemented by using Comparable interface in to the required object.
request.META.get('HTTP_AUTHORIZATION')
/python3.6/site-packages/rest_framework/authentication.py
you can get that from this file though...
For MySQL you can directly put conditions in SUM()
function and it will be evaluated as Boolean 0
or 1
and thus you can have your count based on your criteria without using IF/CASE
statements
SELECT
company_name,
SUM(action = 'EMAIL')AS Email,
SUM(action = 'PRINT' AND pagecount = 1)AS Print1Pages,
SUM(action = 'PRINT' AND pagecount = 2)AS Print2Pages,
SUM(action = 'PRINT' AND pagecount = 3)AS Print3Pages
FROM t
GROUP BY company_name
DEMO
You can add a little syntax sugar to the above solution with the following:
class Time
def to_ms
(self.to_f * 1000.0).to_i
end
end
start_time = Time.now
sleep(3)
end_time = Time.now
elapsed_time = end_time.to_ms - start_time.to_ms # => 3004
This is my solution:
public class Foo : IDisposable
{
private event EventHandler _statusChanged;
public event EventHandler StatusChanged
{
add
{
_statusChanged += value;
}
remove
{
_statusChanged -= value;
}
}
public void Dispose()
{
_statusChanged = null;
}
}
You need to call Dispose()
or use using(new Foo()){/*...*/}
pattern to unsubscribe all members of invocation list.
Use
[A-Z]?
to make the letter optional. {1}
is redundant. (Of course you could also write [A-Z]{0,1}
which would mean the same, but that's what the ?
is there for.)
You could improve your regex to
^([0-9]{5})+\s+([A-Z]?)\s+([A-Z])([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})
And, since in most regex dialects, \d
is the same as [0-9]
:
^(\d{5})+\s+([A-Z]?)\s+([A-Z])(\d{3})(\d{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])\d{3}(\d{4})(\d{2})(\d{2})
But: do you really need 11 separate capturing groups? And if so, why don't you capture the fourth-to-last group of digits?
Something I recently discovered for styling Radio Buttons AND Checkboxes. Before, I had to use jQuery and other things. But this is stupidly simple.
input[type=radio] {
padding-left:5px;
padding-right:5px;
border-radius:15px;
-webkit-appearance:button;
border: double 2px #00F;
background-color:#0b0095;
color:#FFF;
white-space: nowrap;
overflow:hidden;
width:15px;
height:15px;
}
input[type=radio]:checked {
background-color:#000;
border-left-color:#06F;
border-right-color:#06F;
}
input[type=radio]:hover {
box-shadow:0px 0px 10px #1300ff;
}
You can do the same for a checkbox, obviously change the input[type=radio]
to input[type=checkbox]
and change border-radius:15px;
to border-radius:4px;
.
Hope this is somewhat useful to you.
In my case,
word-break: break-all;
worked perfecly, hope it helps any other newcomer like me.
Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.
In Access, there are two types:
2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.
3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.
Minor quibble with the answers:
There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:
?Me!MyCheckBox.Value
?Me!MyCheckBox
The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:
If Me!MyCheckBox Then
...write one of these options:
If (Me!MyCheckBox) Then ' forces evaluation of the control
If Me!MyCheckBox = True Then
If (Me!MyCheckBox = True) Then
If (Me!MyCheckBox = Not False) Then
Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.
Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.
You can use the isNaN function to determine if a value does not convert to a number. Example as below:
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
if (isNaN(x))
{
alert("Must input numbers");
return false;
}
}
What about something like this?
>>> bin(int('ff', base=16))
'0b11111111'
This will convert the hexadecimal string you have to an integer and that integer to a string in which each byte is set to 0/1 depending on the bit-value of the integer.
As pointed out by a comment, if you need to get rid of the 0b
prefix, you can do it this way:
>>> bin(int('ff', base=16)).lstrip('0b')
'11111111'
or this way:
>>> bin(int('ff', base=16))[2:]
'11111111'
If you really just have lock-step iteration over a range, you can do it one of several ways:
for i in range(x):
j = i
…
# or
for i, j in enumerate(range(x)):
…
# or
for i, j in ((i,i) for i in range(x)):
…
All of the above are equivalent to for i, j in zip(range(x), range(y))
if x <= y
.
If you want a nested loop and you only have two iterables, just use a nested loop:
for i in range(x):
for i in range(y):
…
If you have more than two iterables, use itertools.product
.
Finally, if you want lock-step iteration up to x
and then to continue to y
, you have to decide what the rest of the x
values should be.
for i, j in itertools.zip_longest(range(x), range(y), fillvalue=float('nan')):
…
# or
for i in range(min(x,y)):
j = i
…
for i in range(min(x,y), max(x,y)):
j = float('nan')
…
I can think of three options:
RFC 2217 covers a com port to TCP/IP standard that allows a client on one system to emulate a serial port to the local programs, while transparently sending and receiving data and control signals to a server on another system which actually has the serial port. Here's a high-level overview.
What you would do is find or implement a client com port driver that would implement the client side of the system on your PC - appearing to be a real serial port but in reality shuttling everything to a server. You might be able to get this driver for free from Digi, Lantronix, etc in support of their real standalone serial port servers.
You would then implement the server side of the connection locally in another program - allowing the client to connect and issuing the data and control commands as needed.
It's probably non trivial, but the RFC is out there, and you might be able to find an open source project that implements one or both sides of the connection.
Alternately, the serial port driver source for Linux is readily available. Take that, gut the hardware control pieces, and have that one driver run two /dev/ttySx ports, as a simple loopback. Then connect your real program to the ttyS2 and your simulator to the other ttySx.
But the easiest thing to do right now? Spend $40 on two serial port USB devices, wire them together (null modem) and actually have two real serial ports - one for the program you're testing, one for your simulator.
-Adam
When I try:
<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!" />
It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.
Pls try:
<script type="text/javascript">
function moreFields() {
alert("The text will be show");
}
</script>
<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!" />
Hope it helped.
$('#theiframe').on("load", function() {
alert(1);
});
In windows users: open task manager
and end task
the nodejs.exe
file, It works fine.
This is great for creating sample data. Example: put all testing data in a directory called "test-create-volume-123", then after your test is done, zap the entire directory. By generating exactly three digits, you don't have weird sorting issues.
printf '%02d\n' $((1 + RANDOM % 100))
This scales down, e.g. to one digit:
printf '%01d\n' $((1 + RANDOM % 10))
It scales up, but only to four digits. See above as to why :)
Try this:
if(myString != "-1")
The opperand is !=
and not =!
You can also use Equals
if(!myString.Equals("-1"))
Note the !
before myString
Yes. It calls the render() method every time we call setState only except when "shouldComponentUpdate" returns false.
One can also use the following syntax in typescript. Note the backtick " ` "
window.location.hash = `${page_number}`
You'll have to use the "userInfo" variant and pass a NSDictionary object that contains the messageTotal integer:
NSDictionary* userInfo = @{@"total": @(messageTotal)};
NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];
On the receiving end you can access the userInfo dictionary as follows:
-(void) receiveTestNotification:(NSNotification*)notification
{
if ([notification.name isEqualToString:@"TestNotification"])
{
NSDictionary* userInfo = notification.userInfo;
NSNumber* total = (NSNumber*)userInfo[@"total"];
NSLog (@"Successfully received test notification! %i", total.intValue);
}
}
As describe here
Open your php.ini
file (look for it)
Add the following line of code on the top of the file:
date.timezone = "US/Central"
Verify the changes by going to phpinfo.php
When using the official PHP images of Docker, use docker-php-ext-install bcmath
.
Source: https://hub.docker.com/_/php?tab=description#php-core-extensions
Based on @Halil great answer, here is simple function how to insert new element after a specific key, while preserving integer keys:
private function arrayInsertAfterKey($array, $afterKey, $key, $value){
$pos = array_search($afterKey, array_keys($array));
return array_merge(
array_slice($array, 0, $pos, $preserve_keys = true),
array($key=>$value),
array_slice($array, $pos, $preserve_keys = true)
);
}
I prefer instanceof
:
if (obj instanceof SomeType) { ... }
which is much more common and readable than SomeType.isInstance(obj)
Another alternative using reorder to order the levels of a factor. In ascending (n) or descending order (-n) based on the count. Very similar to the one using fct_reorder
from the forcats
package:
Descending order
df %>%
count(Position) %>%
ggplot(aes(x = reorder(Position, -n), y = n)) +
geom_bar(stat = 'identity') +
xlab("Position")
Ascending order
df %>%
count(Position) %>%
ggplot(aes(x = reorder(Position, n), y = n)) +
geom_bar(stat = 'identity') +
xlab("Position")
Data frame:
df <- structure(list(Position = structure(c(3L, 3L, 1L, 1L, 1L, 2L), .Label = c("Defense",
"Striker", "Zoalkeeper"), class = "factor"), Name = structure(c(2L,
1L, 3L, 5L, 4L, 6L), .Label = c("Frank", "James", "Jean", "John",
"Steve", "Tim"), class = "factor")), class = "data.frame", row.names = c(NA,
-6L))
SQL Server(2012) provides another way to generate script for the SQL Server databases with its objects and data. This script can be used to copy the tables’ schema and data from the source database to the destination one in our case.
SQL Scripting method is useful to generate one single script for the tables’ schema and data, including the indexes and keys. But again this method doesn’t generate the tables’ creation script in the correct order if there are relations between the tables.
The solutions here didn't work for me as I'm styling react components.
What worked though for the sidebar was
.sidebar{
position: sticky;
top: 0;
}
Hope this helps someone.
I know that this is a bit of an old question, but I had this error recently so I thought I would pass my solution along.
My errors seem to stem from a old App.Config file and the "in place" upgrade from .Net 4.0 to .Net 4.5.1.
When I started the older project up after upgrading to Framework 4.5.1 I got the TypeInitializationException... right off the bat... not even able to step through one line of code.
After creating a brand new wpf project to test, I found that the newer App.Config file wants the following.
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="YourAppName.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
Once I dropped that in, I was in business.
Note that your need might be slightly different. I would create a dummy project, check out the generated App.Config file and see if you have anything else missing.
Hope this helps someone. Happy Coding!