How to get coordinates of an svg element?
The way to determine the coordinates depends on what element you're working with. For circle
s for example, the cx
and cy
attributes determine the center position. In addition, you may have a translation
applied through the transform
attribute which changes the reference point of any coordinates.
Most of the ways used in general to get screen coordinates won't work for SVGs. In addition, you may not want absolute coordinates if the line you want to draw is in the same container as the elements it connects.
Edit:
In your particular code, it's quite difficult to get the position of the node because its determined by a translation of the parent element. So you need to get the transform attribute of the parent node and extract the translation from that.
d3.transform(d3.select(this.parentNode).attr("transform")).translate
Working jsfiddle here.
How to increase size of DOSBox window?
Looking again at your question, I think I see what's wrong with your conf file. You set:
fullresolution=1366x768
windowresolution=1366x768
That's why you're getting the letterboxing (black on either side). You've essentially told Dosbox that your screen is the same size as your window, but your screen is actually bigger, 1600x900 (or higher) per the Googled specs for that computer. So the 'difference' shows up in black. So you either should change fullresolution to your actual screen resolution, or revert to fullresolution=original default, and only specify the window resolution.
So now I wonder if you really want fullscreen, though your question asks about only a window. For you are getting a window, but you sized it short of your screen, hence the two black stripes (letterboxing). If you really want fullscreen, then you need to specify the actual resolution of your screen. 1366x768 is not big enough.
The next issue is, what's the resolution of the program itself? It won't go past its own resolution. So if the program/game is (natively) say 1280x720 (HD), then your window resolution setting shouldn't be bigger than that (remember, it's fixed not dynamic when you use AxB as windowresolution).
Example: DOS Lotus 123 will only extend eight columns and 20 rows. The bigger the Dosbox, the bigger the text, but not more columns and rows. So setting a higher windowresolution for that, only results in bigger text, not more columns and rows. After that you'll have letterboxing.
Hope this helps you better.
How do I uniquely identify computers visiting my web site?
Cookies won't be useful for determining unique visitors. A user could clear cookies and refresh the site - he then is classed as a new user again.
I think that the best way to go about doing this is to implement a server side solution (as you will need somewhere to store your data). Depending on the complexity of your needs for such data, you will need to determine what is classed as a unique visit. A sensible method would be to allow an IP address to return the following day and be given a unique visit. Several visits from one IP address in one day shouldn't be counted as uniques.
Using PHP, for example, it is trivial to get the IP address of a visitor, and store it in a text file (or a sql database).
A server side solution will work on all machines, because you are going to track the user when he first loads up your site. Don't use javascript, as that is meant for client side scripting, plus the user may have disabled it in any case.
Hope that helps.
TortoiseGit save user authentication / credentials
For TortoiseGit 1.8.1.2 or later, there is a GUI to switch on/off credential helper.
It supports git-credential-wincred
and git-credential-winstore
.
TortoiseGit 1.8.16 add support for git-credential-manager
(Git Credential Manager, the successor of git-credential-winstore
)
For the first time you sync you are asked for user and password, you enter them and they will be saved to Windows credential store. It won't ask for user or password the next time you sync.
To use: Right click → TortoiseGit → Settings → Git → Credential. Select Credential helper: wincred - this repository only / wincred - current Windows user
How do I find the length/number of items present for an array?
Do you mean how long is the array itself, or how many customerids are in it?
Because the answer to the first question is easy: 5 (or if you don't want to hard-code it, Ben Stott's answer).
But the answer to the other question cannot be automatically determined. Presumably you have allocated an array of length 5, but will initially have 0 customer IDs in there, and will put them in one at a time, and your question is, "how many customer IDs have I put into the array?"
C can't tell you this. You will need to keep a separate variable, int numCustIds
(for example). Every time you put a customer ID into the array, increment that variable. Then you can tell how many you have put in.
Custom Python list sorting
I know many have already posted some good answers. However I want to suggest one nice and easy method without importing any library.
l = [(2, 3), (3, 4), (2, 4)]
l.sort(key = lambda x: (-x[0], -x[1]) )
print(l)
l.sort(key = lambda x: (x[0], -x[1]) )
print(l)
Output will be
[(3, 4), (2, 4), (2, 3)]
[(2, 4), (2, 3), (3, 4)]
The output will be sorted based on the order of the parameters we provided in the tuple format
try/catch with InputMismatchException creates infinite loop
YOu can also try the following
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.next());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.next());
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
input.reset();
}
} while (bError);
How to use font-awesome icons from node-modules
Install as npm install font-awesome --save-dev
In your development less file, you can either import the whole font awesome less using @import "node_modules/font-awesome/less/font-awesome.less"
, or look in that file and import just the components that you need. I think this is the minimum for basic icons:
/* adjust path as needed */
@fa_path: "../node_modules/font-awesome/less";
@import "@{fa_path}/variables.less";
@import "@{fa_path}/mixins.less";
@import "@{fa_path}/path.less";
@import "@{fa_path}/core.less";
@import "@{fa_path}/icons.less";
As a note, you still aren't going to save that many bytes by doing this. Either way, you're going to end up including between 2-3k lines of unminified CSS.
You'll also need to serve the fonts themselves from a folder called/fonts/
in your public directory. You could just copy them there with a simple gulp task, for example:
gulp.task('fonts', function() {
return gulp.src('node_modules/font-awesome/fonts/*')
.pipe(gulp.dest('public/fonts'))
})
How to get current route
With angular 2.2.1 (in an angular2-webpack-starter based project) works this:
export class AppComponent {
subscription: Subscription;
activeUrl: string;
constructor(public appState: AppState,
private router: Router) {
console.log('[app] constructor AppComponent');
}
ngOnInit() {
console.log('[app] ngOnInit');
let _this = this;
this.subscription = this.router.events.subscribe(function (s) {
if (s instanceof NavigationEnd) {
_this.activeUrl = s.urlAfterRedirects;
}
});
}
ngOnDestroy() {
console.log('[app] ngOnDestroy: ');
this.subscription.unsubscribe();
}
}
In AppComponent's template you can use e.g. {{activeUrl}}.
This solution is inspired by RouterLinkActive's code.
Should I add the Visual Studio .suo and .user files to source control?
These files are user-specific options, which should be independent of the solution itself. Visual Studio will create new ones as necessary, so they do not need to be checked in to source control. Indeed, it would probably be better not to as this allows individual developers to customize their environment as they see fit.
Pass Javascript variable to PHP via ajax
To test if the POST variable has an element called 'userID' you would be better off using array_key_exists .. which actually tests for the existence of the array key not whether its value has been set .. a subtle and probably only semantic difference, but it does improve readability.
and right now your $uid is being set to a boolean value depending whether $__POST['userID'] is set or not ... If I recall from memory you might want to try ...
$uid = (array_key_exists('userID', $_POST)?$_POST['userID']:'guest';
Then you can use an identifiable 'guest' user and render your code that much more readable :)
Another point re isset() even though it is unlikely to apply in this scenario, it's worth remembering if you don't want to get caught out later ... an array element can be legitimately set to NULL ... i.e. it can exist, but be as yet unpopulated, and this could be a valid, acceptable, and testable condition. but :
a = array('one'=>1, 'two'=>null, 'three'=>3);
isset(a['one']) == true
isset(a['two']) == false
array_key_exists(a['one']) == true
array_key_exists(a['two']) == true
Bw sure you know which function you want to use for which purpose.
Is there any "font smoothing" in Google Chrome?
Ok you can use this simply
-webkit-text-stroke-width: .7px;
-webkit-text-stroke-color: #34343b;
-webkit-font-smoothing:antialiased;
Make sure your text color and upper text-stroke-width must me same and that's it.
How to target the href to div
if you use
angularjs
you have just to write the right css in order to frame you div
html code
<div
style="height:51px;width:111px;margin-left:203px;"
ng-click="nextDetail()">
</div>
JS Code(in your controller):
$scope.nextDetail = function()
{
....
}
Capturing "Delete" Keypress with jQuery
event.key === "Delete"
More recent and much cleaner: use event.key
. No more arbitrary number codes!
NOTE: The old properties (.keyCode
and .which
) are Deprecated.
document.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Delete") {
// Do things
}
});
Mozilla Docs
Supported Browsers
What is a word boundary in regex, does \b match hyphen '-'?
I ran into an even worse problem when searching text for words like .NET
, C++
, C#
, and C
. You would think that computer programmers would know better than to name a language something that is hard to write regular expressions for.
Anyway, this is what I found out (summarized mostly from http://www.regular-expressions.info, which is a great site): In most flavors of regex, characters that are matched by the short-hand character class \w
are the characters that are treated as word characters by word boundaries. Java is an exception. Java supports Unicode for \b
but not for \w
. (I'm sure there was a good reason for it at the time).
The \w
stands for "word character". It always matches the ASCII characters [A-Za-z0-9_]
. Notice the inclusion of the underscore and digits (but not dash!). In most flavors that support Unicode, \w
includes many characters from other scripts. There is a lot of inconsistency about which characters are actually included. Letters and digits from alphabetic scripts and ideographs are generally included. Connector punctuation other than the underscore and numeric symbols that aren't digits may or may not be included. XML Schema and XPath even include all symbols in \w
. But Java, JavaScript, and PCRE match only ASCII characters with \w
.
Which is why Java-based regex searches for C++
, C#
or .NET
(even when you remember to escape the period and pluses) are screwed by the \b
.
Note: I'm not sure what to do about mistakes in text, like when someone doesn't put a space after a period at the end of a sentence. I allowed for it, but I'm not sure that it's necessarily the right thing to do.
Anyway, in Java, if you're searching text for the those weird-named languages, you need to replace the \b
with before and after whitespace and punctuation designators. For example:
public static String grep(String regexp, String multiLineStringToSearch) {
String result = "";
String[] lines = multiLineStringToSearch.split("\\n");
Pattern pattern = Pattern.compile(regexp);
for (String line : lines) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
result = result + "\n" + line;
}
}
return result.trim();
}
Then in your test or main function:
String beforeWord = "(\\s|\\.|\\,|\\!|\\?|\\(|\\)|\\'|\\\"|^)";
String afterWord = "(\\s|\\.|\\,|\\!|\\?|\\(|\\)|\\'|\\\"|$)";
text = "Programming in C, (C++) C#, Java, and .NET.";
System.out.println("text="+text);
// Here is where Java word boundaries do not work correctly on "cutesy" computer language names.
System.out.println("Bad word boundary can't find because of Java: grep with word boundary for .NET="+ grep("\\b\\.NET\\b", text));
System.out.println("Should find: grep exactly for .NET="+ grep(beforeWord+"\\.NET"+afterWord, text));
System.out.println("Bad word boundary can't find because of Java: grep with word boundary for C#="+ grep("\\bC#\\b", text));
System.out.println("Should find: grep exactly for C#="+ grep("C#"+afterWord, text));
System.out.println("Bad word boundary can't find because of Java:grep with word boundary for C++="+ grep("\\bC\\+\\+\\b", text));
System.out.println("Should find: grep exactly for C++="+ grep(beforeWord+"C\\+\\+"+afterWord, text));
System.out.println("Should find: grep with word boundary for Java="+ grep("\\bJava\\b", text));
System.out.println("Should find: grep for case-insensitive java="+ grep("?i)\\bjava\\b", text));
System.out.println("Should find: grep with word boundary for C="+ grep("\\bC\\b", text)); // Works Ok for this example, but see below
// Because of the stupid too-short cutsey name, searches find stuff it shouldn't.
text = "Worked on C&O (Chesapeake and Ohio) Canal when I was younger; more recently developed in Lisp.";
System.out.println("text="+text);
System.out.println("Bad word boundary because of C name: grep with word boundary for C="+ grep("\\bC\\b", text));
System.out.println("Should be blank: grep exactly for C="+ grep(beforeWord+"C"+afterWord, text));
// Make sure the first and last cases work OK.
text = "C is a language that should have been named differently.";
System.out.println("text="+text);
System.out.println("grep exactly for C="+ grep(beforeWord+"C"+afterWord, text));
text = "One language that should have been named differently is C";
System.out.println("text="+text);
System.out.println("grep exactly for C="+ grep(beforeWord+"C"+afterWord, text));
//Make sure we don't get false positives
text = "The letter 'c' can be hard as in Cat, or soft as in Cindy. Computer languages should not require disambiguation (e.g. Ruby, Python vs. Fortran, Hadoop)";
System.out.println("text="+text);
System.out.println("Should be blank: grep exactly for C="+ grep(beforeWord+"C"+afterWord, text));
P.S. My thanks to http://regexpal.com/ without whom the regex world would be very miserable!
How can I check for Python version in a program that uses new language features?
Although the question is:
How do I get control early enough to issue an error message and exit?
The question that I answer is:
How do I get control early enough to issue an error message before starting the app?
I can answer it a lot differently then the other posts.
Seems answers so far are trying to solve your question from within Python.
I say, do version checking before launching Python. I see your path is Linux or unix.
However I can only offer you a Windows script. I image adapting it to linux scripting syntax wouldn't be too hard.
Here is the DOS script with version 2.7:
@ECHO OFF
REM see http://ss64.com/nt/for_f.html
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
IF NOT ErrorLevel 1 GOTO Python27
ECHO must use python2.7 or greater
GOTO EOF
:Python27
python.exe tern.py
GOTO EOF
:EOF
This does not run any part of your application and therefore will not raise a Python Exception. It does not create any temp file or add any OS environment variables. And it doesn't end your app to an exception due to different version syntax rules. That's three less possible security points of access.
The FOR /F
line is the key.
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
For multiple python version check check out url:
http://www.fpschultze.de/modules/smartfaq/faq.php?faqid=17
And my hack version:
[MS script; Python version check prelaunch of Python module]
http://pastebin.com/aAuJ91FQ
PHP check if file is an image
Using file extension and getimagesize
function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.
for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one.
Also its possible to get uploaded file content and search it for special character like <?php
to find the file is image or not.
HTML5 Video // Completely Hide Controls
<video width="320" height="240" autoplay="autoplay">
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
Html code as IFRAME source rather than a URL
You can do this with a data URL. This includes the entire document in a single string of HTML. For example, the following HTML:
<html><body>foo</body></html>
can be encoded as this:
data:text/html;charset=utf-8,%3Chtml%3E%3Cbody%3Efoo%3C/body%3E%3C/html%3E
and then set as the src
attribute of the iframe. Example.
Edit: The other alternative is to do this with Javascript. This is almost certainly the technique I'd choose. You can't guarantee how long a data URL the browser will accept. The Javascript technique would look something like this:
var iframe = document.getElementById('foo'),
iframedoc = iframe.contentDocument || iframe.contentWindow.document;
iframedoc.body.innerHTML = 'Hello world';
Example
Edit 2 (December 2017): use the Html5's srcdoc attribute, just like in Saurabh Chandra Patel's answer, who now should be the accepted answer! If you can detect IE/Edge efficiently, a tip is to use srcdoc-polyfill library only for them and the "pure" srcdoc attribute in all non-IE/Edge browsers (check caniuse.com to be sure).
<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>
PowerShell Script to Find and Replace for all Files with a Specific Extension
I have written a little helper function to replace text in a file:
function Replace-TextInFile
{
Param(
[string]$FilePath,
[string]$Pattern,
[string]$Replacement
)
[System.IO.File]::WriteAllText(
$FilePath,
([System.IO.File]::ReadAllText($FilePath) -replace $Pattern, $Replacement)
)
}
Example:
Get-ChildItem . *.config -rec | ForEach-Object {
Replace-TextInFile -FilePath $_ -Pattern 'old' -Replacement 'new'
}
Getting a POST variable
Use this for GET values:
Request.QueryString["key"]
And this for POST values
Request.Form["key"]
Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:
Request["key"]
Another thing to note (if you need it) is you can check the type of request by using:
Request.RequestType
Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack
will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.
Why are only a few video games written in Java?
Performance issue is the first reason. When you see the kind of hyper optimized C++ code that are in the Quake engines ( http://www.codemaestro.com/reviews/9 ), you know they're not gonna waste their time with a virtual machine.
Sure there may be some .NET games (which ones ? I'm interested. Are there some really CPU/GPU-intensive ones ?), but I guess it's more because lot of people are experts in MS technologies and followed Microsoft when they launched their new technology.
Oh and cross-platform just isn't in the mind of video games companies. Linux is just around 1% of market, Mac OS a few % more. They definitely think it's not worth dumping Windows-only technologies and librairies such as DirectX.
Update one MySQL table with values from another
UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id
That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read
As for running slow, how large are the tables? You should have indexes on tobeupdated.value
and original.value
EDIT:
we can also simplify the query
UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id
USING
is shorthand when both tables of a join have an identical named key
such as id
. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join
Using OR & AND in COUNTIFS
There is probably a more efficient solution to your question, but following formula should do the trick:
=SUM(COUNTIFS(J1:J196,"agree",A1:A196,"yes"),COUNTIFS(J1:J196,"agree",A1:A196,"no"))
JavaScript - Hide a Div at startup (load)
Using CSS you can just set display:none for the element in a CSS file or in a style attribute
#div { display:none; }
<div id="div"></div>
<div style="display:none"></div>
or having the js just after the div might be fast enough too, but not as clean
Examples of good gotos in C or C++
My gripe about this is that you lose block scoping; any local variables declared between the gotos remains in force if the loop is ever broken out of. (Maybe you're assuming the loop runs forever; I don't think that's what the original question writer was asking, though.)
The problem of scoping is more of an issue with C++, as some objects may be depending on their dtor being called at appropriate times.
For me, the best reason to use goto is during a multi-step initialization process where the it's vital that all inits are backed out of if one fails, a la:
if(!foo_init())
goto bye;
if(!bar_init())
goto foo_bye;
if(!xyzzy_init())
goto bar_bye;
return TRUE;
bar_bye:
bar_terminate();
foo_bye:
foo_terminate();
bye:
return FALSE;
Dropdown using javascript onchange
easy
<script>
jQuery.noConflict()(document).ready(function() {
$('#hide').css('display','none');
$('#plano').change(function(){
if(document.getElementById('plano').value == 1){
$('#hide').show('slow');
}else
if(document.getElementById('plano').value == 0){
$('#hide').hide('slow');
}else
if(document.getElementById('plano').value == 0){
$('#hide').css('display','none');
}
});
$('#plano').change();
});
</script>
this example shows and hides the div if selected in combobox some specific value
IIS: Where can I find the IIS logs?
I think the default place for access logs is
%SystemDrive%\inetpub\logs\LogFiles
Otherwise, check under IIS Manager, select the computer on the left pane, and in the middle pane, go under "Logging" in the IIS area. There you will se the default location for all sites (this is however overridable on all sites)
You could also look into
%SystemDrive%\Windows\System32\LogFiles\HTTPERR
Which will contain similar log files that only represents errors.
How do I reflect over the members of dynamic object?
There are several scenarios to consider.
First of all, you need to check the type of your object. You can simply call GetType() for this.
If the type does not implement IDynamicMetaObjectProvider, then you can use reflection same as for any other object. Something like:
var propertyInfo = test.GetType().GetProperties();
However, for IDynamicMetaObjectProvider implementations, the simple reflection doesn't work. Basically, you need to know more about this object. If it is ExpandoObject (which is one of the IDynamicMetaObjectProvider implementations), you can use the answer provided by itowlson. ExpandoObject stores its properties in a dictionary and you can simply cast your dynamic object to a dictionary.
If it's DynamicObject (another IDynamicMetaObjectProvider implementation), then you need to use whatever methods this DynamicObject exposes. DynamicObject isn't required to actually "store" its list of properties anywhere. For example, it might do something like this (I'm reusing an example from my blog post):
public class SampleObject : DynamicObject
{
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = binder.Name;
return true;
}
}
In this case, whenever you try to access a property (with any given name), the object simply returns the name of the property as a string.
dynamic obj = new SampleObject();
Console.WriteLine(obj.SampleProperty);
//Prints "SampleProperty".
So, you don't have anything to reflect over - this object doesn't have any properties, and at the same time all valid property names will work.
I'd say for IDynamicMetaObjectProvider implementations, you need to filter on known implementations where you can get a list of properties, such as ExpandoObject, and ignore (or throw an exception) for the rest.
How to add Google Maps Autocomplete search box?
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(poenter code heresition) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
What is the difference between Swing and AWT?
Swing:
- Swing is part of the java foundation classes.
- Swing components are platform-independent.
- Swing components are lightweight components because swing sits on the top of awt.
AWT:
- AWT is called the abstract window tool.
- AWT components are platform-dependent.
- AWT components are heavyweight components.
HttpClient won't import in Android Studio
Error:(30, 0) Gradle DSL method not found: 'classpath()'
Possible causes:
The project 'cid' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0).
Upgrade plugin to version 2.3.3 and sync projectThe project 'cid' may be using a version of Gradle that does not contain the method.
Open Gradle wrapper fileThe build file may be missing a Gradle plugin.
Apply Gradle plugin
how to realize countifs function (excel) in R
Table is the obvious choice, but it returns an object of class table
which takes a few annoying steps to transform back into a data.frame
So, if you're OK using dplyr, you use the command tally
:
library(dplyr)
df = data.frame(sex=sample(c("M", "F"), 100000, replace=T), occupation=sample(c('Analyst', 'Student'), 100000, replace=T)
df %>% group_by_all() %>% tally()
# A tibble: 4 x 3
# Groups: sex [2]
sex occupation `n()`
<fct> <fct> <int>
1 F Analyst 25105
2 F Student 24933
3 M Analyst 24769
4 M Student 25193
MATLAB, Filling in the area between two sets of data, lines in one figure
You can accomplish this using the function FILL to create filled polygons under the sections of your plots. You will want to plot the lines and polygons in the order you want them to be stacked on the screen, starting with the bottom-most one. Here's an example with some sample data:
x = 1:100; %# X range
y1 = rand(1,100)+1.5; %# One set of data ranging from 1.5 to 2.5
y2 = rand(1,100)+0.5; %# Another set of data ranging from 0.5 to 1.5
baseLine = 0.2; %# Baseline value for filling under the curves
index = 30:70; %# Indices of points to fill under
plot(x,y1,'b'); %# Plot the first line
hold on; %# Add to the plot
h1 = fill(x(index([1 1:end end])),... %# Plot the first filled polygon
[baseLine y1(index) baseLine],...
'b','EdgeColor','none');
plot(x,y2,'g'); %# Plot the second line
h2 = fill(x(index([1 1:end end])),... %# Plot the second filled polygon
[baseLine y2(index) baseLine],...
'g','EdgeColor','none');
plot(x(index),baseLine.*ones(size(index)),'r'); %# Plot the red line
And here's the resulting figure:
You can also change the stacking order of the objects in the figure after you've plotted them by modifying the order of handles in the 'Children'
property of the axes object. For example, this code reverses the stacking order, hiding the green polygon behind the blue polygon:
kids = get(gca,'Children'); %# Get the child object handles
set(gca,'Children',flipud(kids)); %# Set them to the reverse order
Finally, if you don't know exactly what order you want to stack your polygons ahead of time (i.e. either one could be the smaller polygon, which you probably want on top), then you could adjust the 'FaceAlpha'
property so that one or both polygons will appear partially transparent and show the other beneath it. For example, the following will make the green polygon partially transparent:
set(h2,'FaceAlpha',0.5);
How to store .pdf files into MySQL as BLOBs using PHP?
//Pour inserer :
$pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
$filetype = addslashes($_FILES['inputname']['type']);//pour le test
$namepdf = addslashes($_FILES['inputname']['name']);
if (substr($filetype, 0, 11) == 'application'){
$mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
}
//Pour afficher :
$row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
foreach($row as $result){
$file=$result['pdf'];
}
header('Content-type: application/pdf');
echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));
Convert a hexadecimal string to an integer efficiently in C?
For AVR Microcontrollers I wrote the following function, including relevant comments to make it easy to understand:
/**
* hex2int
* take a hex string and convert it to a 32bit number (max 8 hex digits)
*/
uint32_t hex2int(char *hex) {
uint32_t val = 0;
while (*hex) {
// get current character then increment
char byte = *hex++;
// transform hex character to the 4bit equivalent number, using the ascii table indexes
if (byte >= '0' && byte <= '9') byte = byte - '0';
else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;
// shift 4 to make space for new digit, and add the 4 bits of the new digit
val = (val << 4) | (byte & 0xF);
}
return val;
}
Example:
char *z ="82ABC1EF";
uint32_t x = hex2int(z);
printf("Number is [%X]\n", x);
Will output:
JavaScript seconds to time string with format hh:mm:ss
Here is my vision of solution. You can try my snippet below.
_x000D_
_x000D_
function secToHHMM(sec) {_x000D_
var d = new Date();_x000D_
d.setHours(0);_x000D_
d.setMinutes(0);_x000D_
d.setSeconds(0);_x000D_
d = new Date(d.getTime() + sec*1000);_x000D_
return d.toLocaleString('en-GB').split(' ')[1];_x000D_
};_x000D_
_x000D_
alert( 'One hour: ' + secToHHMM(60*60) ); // '01:00:00'_x000D_
alert( 'One hour five minutes: ' + secToHHMM(60*60 + 5*60) ); // '01:05:00'_x000D_
alert( 'One hour five minutes 23 seconds: ' + secToHHMM(60*60 + 5*60 + 23) ); // '01:05:23'
_x000D_
_x000D_
_x000D_
Is it possible to forward-declare a function in Python?
TL;DR: Python does not need forward declarations. Simply put your function calls inside function def definitions, and you'll be fine.
def foo(count):
print("foo "+str(count))
if(count>0):
bar(count-1)
def bar(count):
print("bar "+str(count))
if(count>0):
foo(count-1)
foo(3)
print("Finished.")
recursive function definitions, perfectly successfully gives:
foo 3
bar 2
foo 1
bar 0
Finished.
However,
bug(13)
def bug(count):
print("bug never runs "+str(count))
print("Does not print this.")
breaks at the top-level invocation of a function that hasn't been defined yet, and gives:
Traceback (most recent call last):
File "./test1.py", line 1, in <module>
bug(13)
NameError: name 'bug' is not defined
Python is an interpreted language, like Lisp. It has no type checking, only run-time function invocations, which succeed if the function name has been bound and fail if it's unbound.
Critically, a function def definition does not execute any of the funcalls inside its lines, it simply declares what the function body is going to consist of. Again, it doesn't even do type checking. So we can do this:
def uncalled():
wild_eyed_undefined_function()
print("I'm not invoked!")
print("Only run this one line.")
and it runs perfectly fine (!), with output
Only run this one line.
The key is the difference between definitions and invocations.
The interpreter executes everything that comes in at the top level, which means it tries to invoke it. If it's not inside a definition.
Your code is running into trouble because you attempted to invoke a function, at the top level in this case, before it was bound.
The solution is to put your non-top-level function invocations inside a function definition, then call that function sometime much later.
The business about "if __ main __" is an idiom based on this principle, but you have to understand why, instead of simply blindly following it.
There are certainly much more advanced topics concerning lambda functions and rebinding function names dynamically, but these are not what the OP was asking for. In addition, they can be solved using these same principles: (1) defs define a function, they do not invoke their lines; (2) you get in trouble when you invoke a function symbol that's unbound.
CSS Printing: Avoiding cut-in-half DIVs between pages?
In my case I managed to fix the page break difficulties in webkit by setting my selected divs to page-break-inside:avoid, and also setting all elements to display:inline. So like this:
@media print{
* {
display:inline;
}
script, style {
display:none;
}
div {
page-break-inside:avoid;
}
}
It seems like page-break-properties can only be applied to inline elements (in webkit). I tried to only apply display:inline to the particular elements I needed, but this didn't work. The only thing that worked was applying inline to all elements. I guess it's one of the large container div' that's messing things up.
Maybe someone could expand on this.
How to set variables in HIVE scripts
You can store the output of another query in a variable and latter you can use the same in your code:
set var=select count(*) from My_table;
${hiveconf:var};
Uploading both data and files in one form using Ajax?
A Simple but more effective way:
new FormData()
is itself like a container (or a bag). You can put everything attr or file in itself.
The only thing you'll need to append the attribute, file, fileName
eg:
let formData = new FormData()
formData.append('input', input.files[0], input.files[0].name)
and just pass it in AJAX request. Eg:
let formData = new FormData()
var d = $('#fileid')[0].files[0]
formData.append('fileid', d);
formData.append('inputname', value);
$.ajax({
url: '/yourroute',
method: 'POST',
contentType: false,
processData: false,
data: formData,
success: function(res){
console.log('successfully')
},
error: function(){
console.log('error')
}
})
You can append n number of files or data with FormData.
and if you're making AJAX Request from Script.js file to Route file in Node.js beware of using
req.body
to access data (ie text)
req.files
to access file (ie image, video etc)
How does the @property decorator work in Python?
property
is a class behind @property
decorator.
You can always check this:
print(property) #<class 'property'>
I rewrote the example from help(property)
to show that the @property
syntax
class C:
def __init__(self):
self._x=None
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
c = C()
c.x="a"
print(c.x)
is functionally identical to property()
syntax:
class C:
def __init__(self):
self._x=None
def g(self):
return self._x
def s(self, v):
self._x = v
def d(self):
del self._x
prop = property(g,s,d)
c = C()
c.x="a"
print(c.x)
There is no difference how we use the property as you can see.
To answer the question @property
decorator is implemented via property
class.
So, the question is to explain the property
class a bit.
This line:
prop = property(g,s,d)
Was the initialization. We can rewrite it like this:
prop = property(fget=g,fset=s,fdel=d)
The meaning of fget
, fset
and fdel
:
| fget
| function to be used for getting an attribute value
| fset
| function to be used for setting an attribute value
| fdel
| function to be used for del'ing an attribute
| doc
| docstring
The next image shows the triplets we have, from the class property
:
__get__
, __set__
, and __delete__
are there to be overridden. This is the implementation of the descriptor pattern in Python.
In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol.
We can also use property setter
, getter
and deleter
methods to bind the function to property. Check the next example. The method s2
of the class C
will set the property doubled.
class C:
def __init__(self):
self._x=None
def g(self):
return self._x
def s(self, x):
self._x = x
def d(self):
del self._x
def s2(self,x):
self._x=x+x
x=property(g)
x=x.setter(s)
x=x.deleter(d)
c = C()
c.x="a"
print(c.x) # outputs "a"
C.x=property(C.g, C.s2)
C.x=C.x.deleter(C.d)
c2 = C()
c2.x="a"
print(c2.x) # outputs "aa"
Is there any kind of hash code function in JavaScript?
Here's my simple solution that returns a unique integer.
function hashcode(obj) {
var hc = 0;
var chars = JSON.stringify(obj).replace(/\{|\"|\}|\:|,/g, '');
var len = chars.length;
for (var i = 0; i < len; i++) {
// Bump 7 to larger prime number to increase uniqueness
hc += (chars.charCodeAt(i) * 7);
}
return hc;
}
Use of PUT vs PATCH methods in REST API real life scenarios
Though Dan Lowe's excellent answer very thoroughly answered the OP's question about the difference between PUT and PATCH, its answer to the question of why PATCH is not idempotent is not quite correct.
To show why PATCH isn't idempotent, it helps to start with the definition of idempotence (from Wikipedia):
The term idempotent is used more comprehensively to describe an operation that will produce the same results if executed once or multiple times [...] An idempotent function is one that has the property f(f(x)) = f(x) for any value x.
In more accessible language, an idempotent PATCH could be defined as: After PATCHing a resource with a patch document, all subsequent PATCH calls to the same resource with the same patch document will not change the resource.
Conversely, a non-idempotent operation is one where f(f(x)) != f(x), which for PATCH could be stated as: After PATCHing a resource with a patch document, subsequent PATCH calls to the same resource with the same patch document do change the resource.
To illustrate a non-idempotent PATCH, suppose there is a /users resource, and suppose that calling GET /users
returns a list of users, currently:
[{ "id": 1, "username": "firstuser", "email": "[email protected]" }]
Rather than PATCHing /users/{id}, as in the OP's example, suppose the server allows PATCHing /users. Let's issue this PATCH request:
PATCH /users
[{ "op": "add", "username": "newuser", "email": "[email protected]" }]
Our patch document instructs the server to add a new user called newuser
to the list of users. After calling this the first time, GET /users
would return:
[{ "id": 1, "username": "firstuser", "email": "[email protected]" },
{ "id": 2, "username": "newuser", "email": "[email protected]" }]
Now, if we issue the exact same PATCH request as above, what happens? (For the sake of this example, let's assume that the /users resource allows duplicate usernames.) The "op" is "add", so a new user is added to the list, and a subsequent GET /users
returns:
[{ "id": 1, "username": "firstuser", "email": "[email protected]" },
{ "id": 2, "username": "newuser", "email": "[email protected]" },
{ "id": 3, "username": "newuser", "email": "[email protected]" }]
The /users resource has changed again, even though we issued the exact same PATCH against the exact same endpoint. If our PATCH is f(x), f(f(x)) is not the same as f(x), and therefore, this particular PATCH is not idempotent.
Although PATCH isn't guaranteed to be idempotent, there's nothing in the PATCH specification to prevent you from making all PATCH operations on your particular server idempotent. RFC 5789 even anticipates advantages from idempotent PATCH requests:
A PATCH request can be issued in such a way as to be idempotent,
which also helps prevent bad outcomes from collisions between two
PATCH requests on the same resource in a similar time frame.
In Dan's example, his PATCH operation is, in fact, idempotent. In that example, the /users/1 entity changed between our PATCH requests, but not because of our PATCH requests; it was actually the Post Office's different patch document that caused the zip code to change. The Post Office's different PATCH is a different operation; if our PATCH is f(x), the Post Office's PATCH is g(x). Idempotence states that f(f(f(x))) = f(x)
, but makes no guarantes about f(g(f(x)))
.
How to append multiple values to a list in Python
You can use the sequence method list.extend
to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.
>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
So you can use list.append()
to append a single value, and list.extend()
to append multiple values.
Java 8 LocalDate Jackson format
Simplest and shortest so far:
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate localDate;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime localDateTime;
no dependency required with Spring boot >= 2.2+
Use string.Contains() with switch()
If you just want to use switch/case
, you can do something like this, pseudo-code:
string message = "test of mine";
string[] keys = new string[] {"test2", "test" };
string sKeyResult = keys.FirstOrDefault<string>(s=>message.Contains(s));
switch (sKeyResult)
{
case "test":
Console.WriteLine("yes for test");
break;
case "test2":
Console.WriteLine("yes for test2");
break;
}
But if the quantity of keys is a big, you can just replace it with dictionary, like this:
static Dictionary<string, string> dict = new Dictionary<string, string>();
static void Main(string[] args)
{
string message = "test of mine";
// this happens only once, during initialization, this is just sample code
dict.Add("test", "yes");
dict.Add("test2", "yes2");
string sKeyResult = dict.Keys.FirstOrDefault<string>(s=>message.Contains(s));
Console.WriteLine(dict[sKeyResult]); //or `TryGetValue`...
}
How to add elements of a Java8 stream into an existing List
Lets say we have existing list, and gonna use java 8 for this activity
`
import java.util.*;
import java.util.stream.Collectors;
public class AddingArray {
public void addArrayInList(){
List<Integer> list = Arrays.asList(3, 7, 9);
// And we have an array of Integer type
int nums[] = {4, 6, 7};
//Now lets add them all in list
// converting array to a list through stream and adding that list to previous list
list.addAll(Arrays.stream(nums).map(num ->
num).boxed().collect(Collectors.toList()));
}
}
`
iOS 8 UITableView separator inset 0 not working
This is my solution. This applies to the custom cell subclass, just add them both to the subclass.
- (UIEdgeInsets)layoutMargins {
return UIEdgeInsetsMake(0, 10, 0, 10);
}
2.
self.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
And it is convenient that you can customize the position of the separator without asking your designer to draw one for you..........
Request is not available in this context
In visual studio 2012, When I published the solution mistakenly with 'debug' option I got this exception. With 'release' option it never occurred. Hope it helps.
db.collection is not a function when using MongoClient v3.0
I encountered the same thing. In package.json, change mongodb line to "mongodb": "^2.2.33". You will need to npm uninstall mongodb; then npm install to install this version.
This resolved the issue for me. Seems to be a bug or docs need to be updated.
php function mail() isn't working
I think you are not configured properly,
if you are using XAMPP then you can easily send mail from localhost.
for example you can configure C:\xampp\php\php.ini
and c:\xampp\sendmail\sendmail.ini
for gmail to send mail.
in C:\xampp\php\php.ini
find extension=php_openssl.dll
and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
in php.ini file find [mail function]
and change
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(use the above send mail path only and it will work)
Now Open C:\xampp\sendmail\sendmail.ini
. Replace all the existing code in sendmail.ini with following code
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]
Now you have done!! create php file with mail function and send mail from localhost.
Update
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
When to use RabbitMQ over Kafka?
The short answer is "message acknowledgements". RabbitMQ can be configured to require message acknowledgements. If a receiver fails the message goes back on the queue and another receiver can try again. While you can accomplish this in Kafka with your own code, it works with RabbitMQ out of the box.
In my experience, if you have an application that has requirements to query a stream of information, Kafka and KSql are your best bet. If you want a queueing system you are better off with RabbitMQ.
Combining CSS Pseudo-elements, ":after" the ":last-child"
I do like this for list items in <menu> elements. Consider the following markup:
<menu>
<li><a href="/member/profile">Profile</a></li>
<li><a href="/member/options">Options</a></li>
<li><a href="/member/logout">Logout</a></li>
</menu>
I style it with the following CSS:
menu > li {
display: inline;
}
menu > li::after {
content: ' | ';
}
menu > li:last-child::after {
content: '';
}
This will display:
Profile | Options | Logout
And this is possible because of what Martin Atkins explained on his comment
Note that in CSS 2 you would use :after
, not ::after
. If you use CSS 3, use ::after
(two semi-columns) because ::after
is a pseudo-element (a single semi-column is for pseudo-classes).
Delete statement in SQL is very slow
open CMD and run this commands
NET STOP MSSQLSERVER
NET START MSSQLSERVER
this will restart the SQL Server instance.
try to run again after your delete command
I have this command in a batch script and run it from time to time if I'm encountering problems like this. A normal PC restart will not be the same so restarting the instance is the most effective way if you are encountering some issues with your sql server.
pip install returning invalid syntax
Chances are you are in the Python interpreter. Happens sometimes if you give
this (Python) command in cmd.exe just to check the version of Python and you so happen to forget to come out.
Try this command
exit()
pip install xyz
iOS Launching Settings -> Restrictions URL Scheme
As of iOS8 you can open the built-in Settings app with:
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
The actual URL string is @"app-settings:"
. I tried appending different sections to the string ("Bluetooth", "GENERAL", etc.) but seems only linking to the main Settings screen works. Post a reply if you find out otherwise.
Modify request parameter with servlet filter
Try request.setAttribute("param",value);
. It worked fine for me.
Please find this code sample:
private void sanitizePrice(ServletRequest request){
if(request.getParameterValues ("price") != null){
String price[] = request.getParameterValues ("price");
for(int i=0;i<price.length;i++){
price[i] = price[i].replaceAll("[^\\dA-Za-z0-9- ]", "").trim();
System.out.println(price[i]);
}
request.setAttribute("price", price);
//request.getParameter("numOfBooks").re
}
}
Excluding directory when creating a .tar.gz file
tar -pczf <target_file.tar.gz> --exclude /path/to/exclude --exclude /another/path/to/exclude/* /path/to/include/ /another/path/to/include/*
Tested in Ubuntu 19.10.
- The
=
after exclude
is optional. You can use =
instead of space after keyword exclude
if you like.
- Parameter
exclude
must be placed before the source.
- The difference between use folder name (like the 1st) or the * (like the 2nd) is: the 2nd one will include an empty folder in package but the 1st will not.
Drawing Circle with OpenGL
There is another way to draw a circle - draw it in fragment shader.
Create a quad:
float right = 0.5;
float bottom = -0.5;
float left = -0.5;
float top = 0.5;
float quad[20] = {
//x, y, z, lx, ly
right, bottom, 0, 1.0, -1.0,
right, top, 0, 1.0, 1.0,
left, top, 0, -1.0, 1.0,
left, bottom, 0, -1.0, -1.0,
};
Bind VBO:
unsigned int glBuffer;
glGenBuffers(1, &glBuffer);
glBindBuffer(GL_ARRAY_BUFFER, glBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*20, quad, GL_STATIC_DRAW);
and draw:
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
glEnableVertexAttribArray(ATTRIB_VERTEX);
glEnableVertexAttribArray(ATTRIB_VALUE);
glVertexAttribPointer(ATTRIB_VERTEX , 3, GL_FLOAT, GL_FALSE, 20, 0);
glVertexAttribPointer(ATTRIB_VALUE , 2, GL_FLOAT, GL_FALSE, 20, BUFFER_OFFSET(12));
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
Vertex shader
attribute vec2 value;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
varying vec2 val;
void main() {
val = value;
gl_Position = projectionMatrix*viewMatrix*vertex;
}
Fragment shader
varying vec2 val;
void main() {
float R = 1.0;
float R2 = 0.5;
float dist = sqrt(dot(val,val));
if (dist >= R || dist <= R2) {
discard;
}
float sm = smoothstep(R,R-0.01,dist);
float sm2 = smoothstep(R2,R2+0.01,dist);
float alpha = sm*sm2;
gl_FragColor = vec4(0.0, 0.0, 1.0, alpha);
}
Don't forget to enable alpha blending:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
UPDATE: Read more
How to sort an array of ints using a custom comparator?
How about using streams (Java 8)?
int[] ia = {99, 11, 7, 21, 4, 2};
ia = Arrays.stream(ia).
boxed().
sorted((a, b) -> b.compareTo(a)). // sort descending
mapToInt(i -> i).
toArray();
Or in-place:
int[] ia = {99, 11, 7, 21, 4, 2};
System.arraycopy(
Arrays.stream(ia).
boxed().
sorted((a, b) -> b.compareTo(a)). // sort descending
mapToInt(i -> i).
toArray(),
0,
ia,
0,
ia.length
);
Switch statement: must default be the last case?
There are cases when you are converting ENUM to a string or converting string to enum in case where you are writing/reading to/from a file.
You sometimes need to make one of the values default to cover errors made by manually editing files.
switch(textureMode)
{
case ModeTiled:
default:
// write to a file "tiled"
break;
case ModeStretched:
// write to a file "stretched"
break;
}
How to get the current URL within a Django template?
This is an old question but it can be summed up as easily as this if you're using django-registration.
In your Log In and Log Out link (lets say in your page header) add the next parameter to the link which will go to login or logout. Your link should look like this.
<li><a href="http://www.noobmovies.com/accounts/login/?next={{ request.path | urlencode }}">Log In</a></li>
<li><a href="http://www.noobmovies.com/accounts/logout/?next={{ request.path | urlencode }}">Log Out</a></li>
That's simply it, nothing else needs to be done, upon logout they will immediately be redirected to the page they are at, for log in, they will fill out the form and it will then redirect to the page that they were on. Even if they incorrectly try to log in it still works.
Using Mockito to stub and execute methods for testing
You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.
Think of it like this…
- I need to test a function of a class - let's call it myFunction
- That function makes a call to a function on another class/service/database
- That function also calls another method on the CUT
In the unit test
- Should create a concrete CUT or
@Spy
on it
- You can
@Mock
all of the other class/service/database (i.e. external dependencies)
- You could stub the other function called in the CUT but it is not really how unit testing should be done
In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mock
ed.
In this very simple example, a function that creates an object will be difficult to test
public void doSomethingCool(String foo) {
MyObject obj = new MyObject(foo);
// can't do much with obj in a unit test unless it is returned
}
But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.
public void doSomethingCool(String foo) {
MyObject obj = MyObjectService.getMeAnObject(foo);
}
as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.
How do I start an activity from within a Fragment?
I done it, below code is working for me....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
Button newPage = (Button)v.findViewById(R.id.click);
newPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
});
return v;
}
and Please make sure that your destination activity should be register in Manifest.xml file,
but in my case all tabs are not shown in HomeActivity, is any solution for that ?
How to determine the version of android SDK installed in computer?
While some responses have shown how to get the versions of the installed Android SDKs and various Android SDK related tools using the Android SDK Manager GUI, here's a way to get the same information from the command line:
%ANDROID_HOME%\tools\bin\sdkmanager.bat --list
You can redirect the output to a file to ease review and sharing.
Note: In my corporate environment, I also had to use the --proxy
, --proxy_host
, and --proxy_port
command line options. You may need to use them as well.
How to find elements by class
This works for me to access the class attribute (on beautifulsoup 4, contrary to what the documentation says). The KeyError comes a list being returned not a dictionary.
for hit in soup.findAll(name='span'):
print hit.contents[1]['class']
scrollable div inside container
Adding position: relative
to the parent, and a max-height:100%
; on div2 works.
_x000D_
_x000D_
<body>_x000D_
<div id="div1" style="height: 500px;position:relative;">_x000D_
<div id="div2" style="max-height:100%;overflow:auto;border:1px solid red;">_x000D_
<div id="div3" style="height:1500px;border:5px solid yellow;">hello</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</body>?
_x000D_
_x000D_
_x000D_
Update: The following shows the "updated" example and answer. http://jsfiddle.net/Wcgvt/181/
The secret there is to use box-sizing: border-box
, and some padding to make the second div height 100%, but move it's content down 50px. Then wrap the content in a div with overflow: auto
to contain the scrollbar. Pay attention to z-indexes to keep all the text selectable - hope this helps, several years later.
TypeError: 'bool' object is not callable
Actually you can fix it with following steps -
- Do
cls.__dict__
- This will give you dictionary format output which will contain
{'isFilled':True}
or {'isFilled':False}
depending upon what you have set.
- Delete this entry -
del cls.__dict__['isFilled']
- You will be able to call the method now.
In this case, we delete the entry which overrides the method as mentioned by BrenBarn.
How to calculate the angle between a line and the horizontal axis?
A formula for an angle from 0 to 2pi.
There is x=x2-x1 and y=y2-y1.The formula is working for
any value of x and y. For x=y=0 the result is undefined.
f(x,y)=pi()-pi()/2*(1+sign(x))*(1-sign(y^2))
-pi()/4*(2+sign(x))*sign(y)
-sign(x*y)*atan((abs(x)-abs(y))/(abs(x)+abs(y)))
How to query between two dates using Laravel and Eloquent?
Another option if your field is datetime
instead of date
(although it works for both cases):
$fromDate = "2016-10-01";
$toDate = "2016-10-31";
$reservations = Reservation::whereRaw(
"(reservation_from >= ? AND reservation_from <= ?)",
[$fromDate." 00:00:00", $toDate." 23:59:59"]
)->get();
Set line spacing
Try line-height
property; there are many ways to assign line height
Closing JFrame with button click
You will need a reference to the specific frame you want to close but assuming you have the reference dispose()
should close the frame.
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frameToClose.dispose();
}
});
How to get the caret column (not pixels) position in a textarea, in characters, from the start?
I modified the above function to account for carriage returns in IE. It's untested but I did something similar with it in my code so it should be workable.
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
var add_newlines = 0;
for (var i=0; i<rc.text.length; i++) {
if (rc.text.substr(i, 2) == '\r\n') {
add_newlines += 2;
i++;
}
}
//return rc.text.length + add_newlines;
//We need to substract the no. of lines
return rc.text.length - add_newlines;
}
return 0;
}
Using $window or $location to Redirect in AngularJS
It might help you! demo
AngularJs Code-sample
var app = angular.module('urlApp', []);
app.controller('urlCtrl', function ($scope, $log, $window) {
$scope.ClickMeToRedirect = function () {
var url = "http://" + $window.location.host + "/Account/Login";
$log.log(url);
$window.location.href = url;
};
});
HTML Code-sample
<div ng-app="urlApp">
<div ng-controller="urlCtrl">
Redirect to <a href="#" ng-click="ClickMeToRedirect()">Click Me!</a>
</div>
</div>
How do I set a Windows scheduled task to run in the background?
As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.
It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.
What's default HTML/CSS link color?
Entirely depends on the website you are visiting, and in absence of an overwrite on the website, on the browser. There is no standard for that.
How to Right-align flex item?
margin-left: auto works well. But clean flex box solution would be space-between in the main class. Space between works well if there is two or more elements. I have added a solution for single element as well.
_x000D_
_x000D_
.main { display: flex; justify-content: space-between; }
.a, .b, .c { background: #efefef; border: 1px solid #999; padding: 0.25rem; margin: 0.25rem;}
.b { flex: 1; text-align: center; }
.c-wrapper {
display: flex;
flex: 1;
justify-content: flex-end;
}
.c-wrapper2 {
display: flex;
flex: 1;
flex-flow: row-reverse;
}
_x000D_
<div class="main">
<div class="a"><a href="#">Home</a></div>
<div class="b"><a href="#">Some title centered</a></div>
<div class="c"><a href="#">Contact</a></div>
</div>
<div class="main">
<div class="a"><a href="#">Home</a></div>
<div class="c"><a href="#">Contact</a></div>
</div>
<div class="main">
<div class="c-wrapper">
<a class="c" href="#">Contact</a>
<a class="c" href="#">Contact2</a>
</div>
</div>
<div class="main">
<div class="c-wrapper2">
<span class="c">Contact</span>
<span class="c">Contact2</span>
</div>
</div>
_x000D_
_x000D_
_x000D_
Java program to find the largest & smallest number in n numbers without using arrays
Try the code mentioned below
public static void main(String[] args) {
int smallest=0; int large=0; int num;
System.out.println("enter the number");
Scanner input=new Scanner(System.in);
int n=input.nextInt();
num=input.nextInt();
smallest = num;
for(int i=0;i<n-1;i++)
{
num=input.nextInt();
if(num<smallest)
{
smallest=num;
}
}
System.out.println("the smallest is:"+smallest);
}
C# 4.0: Convert pdf to byte[] and vice versa
// loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.
// note that for Linux, you will not need the c: part
// just swap out the example folder here with your actual full file path
string pdfFilePath = "c:/pdfdocuments/myfile.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);
// munge bytes with whatever pdf software you want, i.e. http://sourceforge.net/projects/itextsharp/
// bytes = MungePdfBytes(bytes); // MungePdfBytes is your custom method to change the PDF data
// ...
// make sure to cleanup after yourself
// and save back - System.IO.File.WriteAll* makes sure all bytes are written properly - this will overwrite the file, if you don't want that, change the path here to something else
System.IO.File.WriteAllBytes(pdfFilePath, bytes);
Use jQuery to get the file input's selected filename without the path
Here you can call like this
Let this is my Input File control
<input type="file" title="search image" id="file" name="file" onchange="show(this)" />
Now here is my Jquery which get called once you select the file
<script type="text/javascript">
function show(input) {
var fileName = input.files[0].name;
alert('The file "' + fileName + '" has been selected.');
}
</script>
Import SQL dump into PostgreSQL database
I'm not sure if this works for the OP's situation, but I found that running the following command in the interactive console was the most flexible solution for me:
\i 'path/to/file.sql'
Just make sure you're already connected to the correct database. This command executes all of the SQL commands in the specified file.
How can I get the intersection, union, and subset of arrays in Ruby?
Utilizing the fact that you can do set operations on arrays by doing &
(intersection), -
(difference), and |
(union).
Obviously I didn't implement the MultiSet to spec, but this should get you started:
class MultiSet
attr_accessor :set
def initialize(set)
@set = set
end
# intersection
def &(other)
@set & other.set
end
# difference
def -(other)
@set - other.set
end
# union
def |(other)
@set | other.set
end
end
x = MultiSet.new([1,1,2,2,3,4,5,6])
y = MultiSet.new([1,3,5,6])
p x - y # [2,2,4]
p x & y # [1,3,5,6]
p x | y # [1,2,3,4,5,6]
Error: Cannot match any routes. URL Segment: - Angular 2
please modify your router.module.ts as:
const routes: Routes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'two',
component: ClassTwo, children: [
{
path: 'three',
component: ClassThree,
outlet: 'nameThree',
},
{
path: 'four',
component: ClassFour,
outlet: 'nameFour'
},
{
path: '',
redirectTo: 'two',
pathMatch: 'full'
}
]
},];
and in your component1.html
<h3>In One</h3>
<nav>
<a routerLink="/two" class="dash-item">...Go to Two...</a>
<a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
<a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>
<router-outlet></router-outlet> // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
Get LatLng from Zip Code - Google Maps API
This is just an improvement to the previous answers because it didn't work for me with some zipcodes even when in https://www.google.com/maps it does, I fixed just adding the word "zipcode " before to put the zipcode, like this:
_x000D_
_x000D_
function getLatLngByZipcode(zipcode) _x000D_
{_x000D_
var geocoder = new google.maps.Geocoder();_x000D_
var address = zipcode;_x000D_
geocoder.geocode({ 'address': 'zipcode '+address }, function (results, status) {_x000D_
if (status == google.maps.GeocoderStatus.OK) {_x000D_
var latitude = results[0].geometry.location.lat();_x000D_
var longitude = results[0].geometry.location.lng();_x000D_
alert("Latitude: " + latitude + "\nLongitude: " + longitude);_x000D_
} else {_x000D_
alert("Request failed.")_x000D_
}_x000D_
});_x000D_
return [latitude, longitude];_x000D_
}
_x000D_
_x000D_
_x000D_
Why am I getting tree conflicts in Subversion?
If you encounter tree conflicts which do not make sense because you didn't edit/delete/come anywhere near the file, there is also a good chance that there was an error in the merge command.
What can happen is that you previously already merged a bunch of the changes you are including in your current merge. For instance, in trunk someone edited a file, and then later renames it. If in your first merge you include the edit, and then in a second merge include both the edit and the rename (essentially a remove), it will also give you a tree conflict. The reason for this is that the previously merged edit then appears as your own, and thus the remove will not be performed automatically.
This can occur on 1.4 repositories at least, I'm not sure whether the mergetracking introduced in 1.5 helps here.
OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?
Here I have loaded 2200 markers. It takes around 1 min to add 2200 locations.
https://jsfiddle.net/suchg/qm1pqunz/11/
//function to get random element from an array
(function($) {
$.rand = function(arg) {
if ($.isArray(arg)) {
return arg[$.rand(arg.length)];
} else if (typeof arg === "number") {
return Math.floor(Math.random() * arg);
} else {
return 4; // chosen by fair dice roll
}
};
})(jQuery);
//start code on document ready
$(document).ready(function () {
var map;
var elevator;
var myOptions = {
zoom: 0,
center: new google.maps.LatLng(35.392738, -100.019531),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
//get place from inputfile.js
var placesObject = place;
errorArray = [];
//will fire 20 ajax request at a time and other will keep in queue
var queuCounter = 0, setLimit = 20;
//keep count of added markers and update at top
totalAddedMarkers = 0;
//make an array of geocode keys to avoid the overlimit error
var geoCodKeys = [
'AIzaSyCF82XXUtT0vzMTcEPpTXvKQPr1keMNr_4',
'AIzaSyAYPw6oFHktAMhQqp34PptnkDEdmXwC3s0',
'AIzaSyAwd0OLvubYtKkEWwMe4Fe0DQpauX0pzlk',
'AIzaSyDF3F09RkYcibDuTFaINrWFBOG7ilCsVL0',
'AIzaSyC1dyD2kzPmZPmM4-oGYnIH_0x--0hVSY8'
];
//funciton to add marker
var addMarkers = function(address, queKey){
var key = jQuery.rand(geoCodKeys);
var url = 'https://maps.googleapis.com/maps/api/geocode/json?key='+key+'&address='+address+'&sensor=false';
var qyName = '';
if( queKey ) {
qyName = queKey;
} else {
qyName = 'MyQueue'+queuCounter;
}
$.ajaxq (qyName, {
url: url,
dataType: 'json'
}).done(function( data ) {
var address = getParameterByName('address', this.url);
var index = errorArray.indexOf(address);
try{
var p = data.results[0].geometry.location;
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map
});
totalAddedMarkers ++;
//update adde marker count
$("#totalAddedMarker").text(totalAddedMarkers);
if (index > -1) {
errorArray.splice(index, 1);
}
}catch(e){
if(data.status = 'ZERO_RESULTS')
return false;
//on error call add marker function for same address
//and keep in Error ajax queue
addMarkers( address, 'Errror' );
if (index == -1) {
errorArray.push( address );
}
}
});
//mentain ajax queue set
queuCounter++;
if( queuCounter == setLimit ){
queuCounter = 0;
}
}
//function get url parameter from url string
getParameterByName = function ( name,href )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
//call add marker function for each address mention in inputfile.js
for (var x = 0; x < placesObject.length; x++) {
var address = placesObject[x]['City'] + ', ' + placesObject[x]['State'];
addMarkers(address);
}
});
Redis command to get all available keys?
It can happen that using redis-cli, you connect to your remote redis-server, and then the command:
KEYS *
is not showing anything, or better, it shows:
(empty list or set)
If you are absolutely sure that the Redis server you use is the one you have the data, then maybe your redis-cli is not connecting to the Redis correct database instance.
As it is mentioned in the Redis docs, new connections connect as default to the db 0.
In my case KEYS
command was not retrieving results because my database was 1. In order to select the db you want, use SELECT.
The db is identified by an integer.
SELECT 1
KEYS *
I post this info because none of the previous answers was solving my issue.
D3 Appending Text to a SVG Rectangle
A rect
can't contain a text
element. Instead transform a g
element with the location of text and rectangle, then append both the rectangle and the text to it:
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
http://bl.ocks.org/mbostock/7341714
Multi-line labels are also a little tricky, you might want to check out this wrap function.
How do I convert a pandas Series or index to a Numpy array?
To get a NumPy array, you should use the values
attribute:
In [1]: df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c']); df
A B
a 1 4
b 2 5
c 3 6
In [2]: df.index.values
Out[2]: array(['a', 'b', 'c'], dtype=object)
This accesses how the data is already stored, so there's no need for a conversion.
Note: This attribute is also available for many other pandas' objects.
In [3]: df['A'].values
Out[3]: Out[16]: array([1, 2, 3])
To get the index as a list, call tolist
:
In [4]: df.index.tolist()
Out[4]: ['a', 'b', 'c']
And similarly, for columns.
Swap two variables without using a temporary variable
Here is some different process to swap two variables
//process one
a=b+a;
b=a-b;
a=a-b;
printf("a= %d b= %d",a,b);
//process two
a=5;
b=10;
a=a+b-(b=a);
printf("\na= %d b= %d",a,b);
//process three
a=5;
b=10;
a=a^b;
b=a^b;
a=b^a;
printf("\na= %d b= %d",a,b);
//process four
a=5;
b=10;
a=b-~a-1;
b=a+~b+1;
a=a+~b+1;
printf("\na= %d b= %d",a,b);
How to install pip for Python 3.6 on Ubuntu 16.10?
This answer assumes that you have python3.6
installed. For python3.7
, replace 3.6
with 3.7
. For python3.8
, replace 3.6
with 3.8
, but it may also first require the python3.8-distutils
package.
Installation with sudo
With regard to installing pip
, using curl
(instead of wget
) avoids writing the file to disk.
curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6
The -H
flag is evidently necessary with sudo
in order to prevent errors such as the following when installing pip for an updated python interpreter:
The directory '/home/someuser/.cache/pip/http' or its parent directory
is not owned by the current user and the cache has been disabled.
Please check the permissions and owner of that directory. If executing
pip with sudo, you may want sudo's -H flag.
The directory
'/home/someuser/.cache/pip' or its parent directory is not owned by the
current user and caching wheels has been disabled. check the
permissions and owner of that directory. If executing pip with sudo,
you may want sudo's -H flag.
Installation without sudo
curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user
This may sometimes give a warning such as:
WARNING: The script wheel is installed in '/home/ubuntu/.local/bin'
which is not on PATH. Consider adding this directory to PATH or, if
you prefer to suppress this warning, use --no-warn-script-location.
Verification
After this, pip
, pip3
, and pip3.6
can all be expected to point to the same target:
$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)
Of course you can alternatively use python3.6 -m pip
as well.
$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)
Return empty cell from formula in Excel
What I used was a small hack.
I used T(1), which returned an empty cell.
T is a function in excel that returns its argument if its a string and an empty cell otherwise. So, what you can do is:
=IF(condition,T(1),value)
Objective-C: Extract filename from path string
If you're displaying a user-readable file name, you do not want to use lastPathComponent
. Instead, pass the full path to NSFileManager's displayNameAtPath:
method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.
How to wait till the response comes from the $http request, in angularjs?
FYI, this is using Angularfire so it may vary a bit for a different service or other use but should solve the same isse $http has. I had this same issue only solution that fit for me the best was to combine all services/factories into a single promise on the scope. On each route/view that needed these services/etc to be loaded I put any functions that require loaded data inside the controller function i.e. myfunct() and the main app.js on run after auth i put
myservice.$loaded().then(function() {$rootScope.myservice = myservice;});
and in the view I just did
ng-if="myservice" ng-init="somevar=myfunct()"
in the first/parent view element/wrapper so the controller can run everything inside
myfunct()
without worrying about async promises/order/queue issues. I hope that helps someone with the same issues I had.
Installing OpenCV 2.4.3 in Visual C++ 2010 Express
1. Installing OpenCV 2.4.3
First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\
.
Wait until all files get extracted. It will create a new directory C:\opencv
which
contains OpenCV header files, libraries, code samples, etc.
Now you need to add the directory C:\opencv\build\x86\vc10\bin
to your system PATH. This directory contains OpenCV DLLs required for running your code.
Open Control Panel → System → Advanced system settings → Advanced Tab → Environment variables...
On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin;
(3), then click Ok.
On some computers, you may need to restart your computer for the system to recognize the environment path variables.
This will completes the OpenCV 2.4.3 installation on your computer.
2. Create a new project and set up Visual C++
Open Visual C++ and select File → New → Project... → Visual C++ → Empty Project. Give a name for your project (e.g: cvtest
) and set the project location (e.g: c:\projects
).
Click Ok. Visual C++ will create an empty project.
Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest
and select Properties → VC++ Directories.
Select Include Directories to add a new entry and type C:\opencv\build\include
.
Click Ok to close the dialog.
Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib
.
Click Ok to close the dialog.
Back to the property dialog, select Linker → Input → Additional Dependencies to add new entries. On the popup dialog, type the files below:
opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib
Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).
Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.
NOTE:
These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to
repeat adding the OpenCV directories and in Additional
Dependencies section, use:
opencv_core243.lib
opencv_imgproc243.lib
...
instead of:
opencv_core243d.lib
opencv_imgproc243d.lib
...
You've done setting up Visual C++, now is the time to write the real code. Right click your project and select Add → New Item... → Visual C++ → C++ File.
Name your file (e.g: loadimg.cpp
) and click Ok. Type the code below in the editor:
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat im = imread("c:/full/path/to/lena.jpg");
if (im.empty())
{
cout << "Cannot load image!" << endl;
return -1;
}
imshow("Image", im);
waitKey(0);
}
The code above will load c:\full\path\to\lena.jpg
and display the image. You can
use any image you like, just make sure the path to the image is correct.
Type F5 to compile the code, and it will display the image in a nice window.
And that is your first OpenCV program!
3. Where to go from here?
Now that your OpenCV environment is ready, what's next?
- Go to the samples dir →
c:\opencv\samples\cpp
.
- Read and compile some code.
- Write your own code.
pthread_join() and pthread_exit()
In pthread_exit
, ret
is an input parameter. You are simply passing the address of a variable to the function.
In pthread_join
, ret
is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL
.
Long explanation:
In pthread_join
, you get back the address passed to pthread_exit
by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.
how concatenate two variables in batch script?
You can do it without setlocal
, because of the setlocal
command the variable won't survive an endlocal
because it was created in setlocal
. In this way the variable will be defined the right way.
To do that use this code:
set var1=A
set var2=B
set AB=hi
call set newvar=%%%var1%%var2%%%
echo %newvar%
Note: You MUST use call
before you set the variable or it won't work.
findAll() in yii
Use the below code. This should work.
$comments = EmailArchive::find()->where(['email_id' => $id])->all();
How to select the first element with a specific attribute using XPath
As an explanation to Jonathan Fingland's answer:
- multiple conditions in the same predicate (
[position()=1 and @location='US']
) must be true as a whole
- multiple conditions in consecutive predicates (
[position()=1][@location='US']
) must be true one after another
- this implies that
[position()=1][@location='US']
!= [@location='US'][position()=1]
while [position()=1 and @location='US']
== [@location='US' and position()=1]
- hint: a lone
[position()=1]
can be abbreviated to [1]
You can build complex expressions in predicates with the Boolean operators "and
" and "or
", and with the Boolean XPath functions not()
, true()
and false()
. Plus you can wrap sub-expressions in parentheses.
Find everything between two XML tags with RegEx
this can capture most outermost layer pair of tags, even with attribute in side or without end tags
(<!--((?!-->).)*-->|<\w*((?!\/<).)*\/>|<(?<tag>\w+)[^>]*>(?>[^<]|(?R))*<\/\k<tag>\s*>)
edit: as mentioned in comment above, regex is always not enough to parse xml, trying to modify the regex to fit more situation only makes it longer but still useless
How does one add keyboard languages and switch between them in Linux Mint 16?
This assumes you have other languages already added in Language Support.
(To check this, Menu > Language Support)
Now to make the keyboard language appear in the Panel:
- Menu > Keyboard > Layouts > Add (+)
The icon 'en' or your language should now appear in the right panel tray.
Click it to switch language.
In previous Mint versions, the shortcut for switching language was LEFT SHIFT + CAPS.
It seems now there is no default, and it must be added:
- System settings > Keyboard > Layouts > Options > Switching to another layout
Keyboard Preferences is also accessible by right-clicking the language icon in the Panel.
ERROR 1148: The used command is not allowed with this MySQL version
Also struggled with this issue, trying to upload .csv data into AWS RDS instance from my local machine using MySQL Workbench on Windows.
The addition I needed was adding OPT_LOCAL_INFILE=1
in: Connection > Advanced > Others. Note CAPS was required.
I found this answer by PeterMag in AWS Developer Forums.
For further info:
SHOW VARIABLES LIKE 'local_infile';
already returned ON
and the query was:
LOAD DATA LOCAL INFILE 'filepath/file.csv'
INTO TABLE `table_name`
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
Copying from the answer source referenced above:
Apparently this is a bug in MYSQL Workbench V8.X. In addition to the
configurations shown earlier in this thread, you also need to change
the MYSQL Connection in Workbench as follows:
- Go to the Welcome page of MYSQL which displays all your connections
- Select Manage Server Connections (the little spanner icon)
- Select your connection
- Select Advanced tab
- In the Others box, add OPT_LOCAL_INFILE=1
Now I can use the LOAD DATA LOCAL INFILE query on MYSQL RDS. It seems
that the File_priv permission is not required.*
JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory
I found some issue about that kind of error
- Database username or password not match in the mysql or other other database. Please set application.properties like this
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
# Connection url for the database please let me know "[email protected]"
spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc
# Username and secret
spring.datasource.username = root
spring.datasource.password =
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# ===============================
# = JPA / HIBERNATE
# ===============================
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = update
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Issue no 2.
Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine
Git pull after forced update
Pull with rebase
A regular pull is fetch + merge, but what you want is fetch + rebase. This is an option with the pull
command:
git pull --rebase
__init__() missing 1 required positional argument
Your constructor is expecting one parameter (data). You're not passing it in the call. I guess you wanted to initialise a field in the object. That would look like this:
class DHT:
def __init__(self):
self.data = {}
self.data['one'] = '1'
self.data['two'] = '2'
self.data['three'] = '3'
def showData(self):
print(self.data)
if __name__ == '__main__':
DHT().showData()
Or even just:
class DHT:
def __init__(self):
self.data = {'one': '1', 'two': '2', 'three': '3'}
def showData(self):
print(self.data)
How can I switch to another branch in git?
I am using this to switch one branch to another anyone you can use it works for me like charm.
git switch [branchName] OR
git checkout [branchName]
ex: git switch develop OR
git checkout develop
Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"
The problem is that the META-INF folder won't get filtered so multiple entries of NOTICE
or LICENSE
cause duplicates when building and it is tryed to copy them together.
Dirty Quick Fix:
Open the .jar
file in your .gradle/caches/...
folder (with a zip compatible tool) and remove or rename the files in the META-INF
folder that cause the error (usally NOTICE
or LICENSE
).
(I know thats also in the OP, but for me it was not really clear until I read the google forum)
EDIT:
This was fixed in 0.7.1. Just add the confilcting files to exclude.
android {
packagingOptions {
exclude 'META-INF/LICENSE'
}
}
Oracle query execution time
One can issue the SQL*Plus command SET TIMING ON
to get wall-clock times, but one can't take, for example, fetch time out of that trivially.
The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY
will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.
Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".
did you specify the right host or port? error on Kubernetes
Reinitialising gcloud with proper account and project worked for me.
gcloud init
After this retrying the below command was successful and kubeconfig entry was generated.
gcloud container clusters get-credentials "cluster_name"
check the cluster info with
kubectl cluster-info
Add a dependency in Maven
I'd do this:
add the dependency as you like in your pom:
<dependency>
<groupId>com.stackoverflow...</groupId>
<artifactId>artifactId...</artifactId>
<version>1.0</version>
</dependency>
run mvn install
it will try to download the jar and fail. On the process, it
will give you the complete command of installing the jar with the error message. Copy that command and run it! easy huh?!
"column not allowed here" error in INSERT statement
INSERT INTO LOCATION VALUES(PQ95VM,'HAPPY_STREET','FRANCE');
the above mentioned code is not correct because your first parameter POSTCODE is of type VARCHAR(10)
. you should have used ' '
.
try INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');
How do I view cookies in Internet Explorer 11 using Developer Tools
Sorry to break the news to ya, but there is no way to do this in IE11.
I have been troubling with this for some time, but I finally had to see it as a lost course, and just navigate to the files manually.
But where are the files? That depends on a lot of things, I have found them these places on different machines:
In the the Internet Explorer cache.
This can be done via "run" (Windows+r) and then typing in shell:cache
or by navigating to it through the internet options in IE11 (AskLeo has a fine guide to this, I'm not affiliated in any way).
- Click on the gear icon, then Internet options.
- In the General tab, underneath “Browsing history”, click on Settings.
- In the resulting “Website Data” dialog, click on View files.
- This will open the folder we’re interested in: your Internet Explorer cache.
Make a search for "cookie" to see the cookies only
In the Cookies folder
The path for cookies can be found here via regedit:
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cookies
Common path (in 7 & 8)
%APPDATA%\Microsoft\Windows\Cookies
%APPDATA%\Microsoft\Windows\Cookies\Low
Common path (Win 10)
shell:cookies
shell:cookies\low
%userprofile%\AppData\Local\Microsoft\Windows\INetCookies
%userprofile%\AppData\Local\Microsoft\Windows\INetCookies\Low
Select last row in MySQL
You can combine two queries suggested by @spacepille into single query that looks like this:
SELECT * FROM `table_name` WHERE id=(SELECT MAX(id) FROM `table_name`);
It should work blazing fast, but on INNODB tables it's fraction of milisecond slower than ORDER+LIMIT.
How to serve up a JSON response using Go?
Other users commenting that the Content-Type
is plain/text
when encoding. You have to set the Content-Type
first w.Header().Set
, then the HTTP response code w.WriteHeader
.
If you call w.WriteHeader
first then call w.Header().Set
after you will get plain/text
.
An example handler might look like this;
func SomeHandler(w http.ResponseWriter, r *http.Request) {
data := SomeStruct{}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(data)
}
How do I output coloured text to a Linux terminal?
As others have stated, you can use escape characters.
You can use my header in order to make it easier:
#ifndef _COLORS_
#define _COLORS_
/* FOREGROUND */
#define RST "\x1B[0m"
#define KRED "\x1B[31m"
#define KGRN "\x1B[32m"
#define KYEL "\x1B[33m"
#define KBLU "\x1B[34m"
#define KMAG "\x1B[35m"
#define KCYN "\x1B[36m"
#define KWHT "\x1B[37m"
#define FRED(x) KRED x RST
#define FGRN(x) KGRN x RST
#define FYEL(x) KYEL x RST
#define FBLU(x) KBLU x RST
#define FMAG(x) KMAG x RST
#define FCYN(x) KCYN x RST
#define FWHT(x) KWHT x RST
#define BOLD(x) "\x1B[1m" x RST
#define UNDL(x) "\x1B[4m" x RST
#endif /* _COLORS_ */
An example using the macros of the header could be:
#include <iostream>
#include "colors.h"
using namespace std;
int main()
{
cout << FBLU("I'm blue.") << endl;
cout << BOLD(FBLU("I'm blue-bold.")) << endl;
return 0;
}
Proper Linq where clauses
EDIT: LINQ to Objects doesn't behave how I'd expected it to. You may well be interested in the blog post I've just written about this...
They're different in terms of what will be called - the first is equivalent to:
Collection.Where(x => x.Age == 10)
.Where(x => x.Name == "Fido")
.Where(x => x.Fat == true)
wheras the latter is equivalent to:
Collection.Where(x => x.Age == 10 &&
x.Name == "Fido" &&
x.Fat == true)
Now what difference that actually makes depends on the implementation of Where
being called. If it's a SQL-based provider, I'd expect the two to end up creating the same SQL. If it's in LINQ to Objects, the second will have fewer levels of indirection (there'll be just two iterators involved instead of four). Whether those levels of indirection are significant in terms of speed is a different matter.
Typically I would use several where
clauses if they feel like they're representing significantly different conditions (e.g. one is to do with one part of an object, and one is completely separate) and one where
clause when various conditions are closely related (e.g. a particular value is greater than a minimum and less than a maximum). Basically it's worth considering readability before any slight performance difference.
How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?
Also set ${COMMAND}
to g++
on Linux
Under:
- Project
- Properties
- C/C++ General
- Preprocessor Include Paths, Macros, etc.
- Providers
- CDT GCC Built-in Compiler Settings
- Command to get compiler specs
Replace:
${COMMAND} ${FLAGS} -E -P -v -dD "${INPUTS}"
with:
g++ -std=c++11 -E -P -v -dD "${INPUTS}"
If you don't do this, the Eclipse stdout shows:
Unable to find full path for "-E"
and logs under ${HOME}/eclipse-workspace/.metadata/.log
show:
!ENTRY org.eclipse.cdt.core 4 0 2020-04-23 20:17:07.288
!MESSAGE Error: Cannot run program "-E": Unknown reason
because ${COMMAND} ${FLAGS}
are empty, and so Eclipse tries to execute the -E
that comes next.
I wonder if we can properly define the COMMAND
and FLAGS
variables on the settings, but I tried to add them as build variables and it didn't work.
C version of the question: "Unresolved inclusion" error with Eclipse CDT for C standard library headers
Tested on Eclipse 2020-03 (4.15.0), Ubuntu 19.10, and this minimal Makefile project with existing sources.
proper way to sudo over ssh
Depending on your usage, I had success with the following:
ssh root@server "script"
This will prompt for the root password and then execute the command correctly.
Way to *ngFor loop defined number of times instead of repeating over array?
Within your component, you can define an array of number (ES6) as described below:
export class SampleComponent {
constructor() {
this.numbers = Array(5).fill(0).map((x,i)=>i);
}
}
See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.
You can then iterate over this array with ngFor
:
@View({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Or shortly:
@View({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Hope it helps you,
Thierry
Edit: Fixed the fill statement and template syntax.
In Javascript, how to conditionally add a member to an object?
i prefere, using code this it, you can run this code
const three = {
three: 3
}
// you can active this code, if you use object `three is null`
//const three = {}
const number = {
one: 1,
two: 2,
...(!!three && three),
four: 4
}
console.log(number);
Sort a list of Class Instances Python
In addition to the solution you accepted, you could also implement the special __lt__()
("less than") method on the class. The sort()
method (and the sorted()
function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.
class Foo(object):
def __init__(self, score):
self.score = score
def __lt__(self, other):
return self.score < other.score
l = [Foo(3), Foo(1), Foo(2)]
l.sort()
Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio
Thank @Ironman for his complete answer, however I should add my solution according to what I've experienced facing this issue.
In build.gradle (Module: app):
compile 'com.android.support:multidex:1.0.1'
...
dexOptions {
javaMaxHeapSize "4g"
}
...
defaultConfig {
multiDexEnabled true
}
Also, put the following in gradle.properties file:
org.gradle.jvmargs=-Xmx4096m -XX\:MaxPermSize\=512m -XX\:+HeapDumpOnOutOfMemoryError -Dfile.encoding\=UTF-8
I should mention, these numbers are for my laptop config (MacBook Pro with 16 GB RAM) therefore please edit them as your config.
Stop mouse event propagation
This solved my problem, from preventign that an event gets fired by a children:
_x000D_
_x000D_
doSmth(){_x000D_
// what ever_x000D_
}
_x000D_
<div (click)="doSmth()">_x000D_
<div (click)="$event.stopPropagation()">_x000D_
<my-component></my-component>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Bootstrap Navbar toggle button not working
If you will change the ID then Toggle will not working same problem was with me i just change
<div class="collapse navbar-collapse" id="defaultNavbar1">
<ul class="nav navbar-nav">
id="defaultNavbar1" then toggle is working
Maintain/Save/Restore scroll position when returning to a ListView
A very simple way:
/** Save the position **/
int currentPosition = listView.getFirstVisiblePosition();
//Here u should save the currentPosition anywhere
/** Restore the previus saved position **/
listView.setSelection(savedPosition);
The method setSelection will reset the list to the supplied item. If not in touch mode the item will actually be selected if in touch mode the item will only be positioned on screen.
A more complicated approach:
listView.setOnScrollListener(this);
//Implements the interface:
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
mCurrentX = view.getScrollX();
mCurrentY = view.getScrollY();
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
//Save anywere the x and the y
/** Restore: **/
listView.scrollTo(savedX, savedY);
How to override maven property in command line?
See Introduction to the POM
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
Does Go have "if x in" construct similar to Python?
Just had similar question and decided to try out some of the suggestions in this thread.
I've benchmarked best and worst case scenarios of 3 types of lookup:
- using a map
- using a list
- using a switch statement
here's the function code:
func belongsToMap(lookup string) bool {
list := map[string]bool{
"900898296857": true,
"900898302052": true,
"900898296492": true,
"900898296850": true,
"900898296703": true,
"900898296633": true,
"900898296613": true,
"900898296615": true,
"900898296620": true,
"900898296636": true,
}
if _, ok := list[lookup]; ok {
return true
} else {
return false
}
}
func belongsToList(lookup string) bool {
list := []string{
"900898296857",
"900898302052",
"900898296492",
"900898296850",
"900898296703",
"900898296633",
"900898296613",
"900898296615",
"900898296620",
"900898296636",
}
for _, val := range list {
if val == lookup {
return true
}
}
return false
}
func belongsToSwitch(lookup string) bool {
switch lookup {
case
"900898296857",
"900898302052",
"900898296492",
"900898296850",
"900898296703",
"900898296633",
"900898296613",
"900898296615",
"900898296620",
"900898296636":
return true
}
return false
}
best case scenarios pick the first item in lists, worst case ones use nonexistant value.
here are the results:
BenchmarkBelongsToMapWorstCase-4 2000000 787 ns/op
BenchmarkBelongsToSwitchWorstCase-4 2000000000 0.35 ns/op
BenchmarkBelongsToListWorstCase-4 100000000 14.7 ns/op
BenchmarkBelongsToMapBestCase-4 2000000 683 ns/op
BenchmarkBelongsToSwitchBestCase-4 100000000 10.6 ns/op
BenchmarkBelongsToListBestCase-4 100000000 10.4 ns/op
Switch wins all the way, worst case is surpassingly quicker than best case.
Maps are the worst and list is closer to switch.
So the moral is:
If you have a static, reasonably small list, switch statement is the way to go.
Retrieving values from nested JSON Object
Maybe you're not using the latest version of a JSON for Java Library.
json-simple
has not been updated for a long time, while JSON-Java
was updated 2 month ago.
JSON-Java
can be found on GitHub, here is the link to its repo: https://github.com/douglascrockford/JSON-java
After switching the library, you can refer to my sample code down below:
public static void main(String[] args) {
String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
JSONObject jsonObject = new JSONObject(JSON);
JSONObject getSth = jsonObject.getJSONObject("LanguageLevels");
Object level = getSth.get("2");
System.out.println(level);
}
And as JSON-Java
open-sourced, you can read the code and its document, they will guide you through.
Hope that it helps.
ASP.NET MVC: No parameterless constructor defined for this object
You can get this exception at many different places in the MVC framework (e.g. it can't create the controller, or it can't create a model to give that controller).
The only easy way I've found to diagnose this problem is to override MVC as close to the exception as possible with your own code. Then your code will break inside Visual Studio when this exception occurs, and you can read the Type causing the problem from the stack trace.
This seems like a horrible way to approach this problem, but it's very fast, and very consistent.
For example, if this error is occurring inside the MVC DefaultModelBinder (which you will know by checking the stack trace), then replace the DefaultModelBinder with this code:
public class MyDefaultModelBinder : System.Web.Mvc.DefaultModelBinder
{
protected override object CreateModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext, Type modelType)
{
return base.CreateModel(controllerContext, bindingContext, modelType);
}
}
And update your Global.asax.cs:
public class MvcApplication : System.Web.HttpApplication
{
...
protected void Application_Start(object sender, EventArgs e)
{
ModelBinders.Binders.DefaultBinder = new MyDefaultModelBinder();
}
}
Now the next time you get that exception, Visual Studio will stop inside your MyDefaultModelBinder class, and you can check the "modelType" property to see what type caused the problem.
The example above works for when you get the "No parameterless constructor defined for this object" exception during model binding, only. But similar code can be written for other extension points in MVC (e.g. controller construction).