Android Center text on canvas
I create a method to simplify this:
public static void drawCenterText(String text, RectF rectF, Canvas canvas, Paint paint) {
Paint.Align align = paint.getTextAlign();
float x;
float y;
//x
if (align == Paint.Align.LEFT) {
x = rectF.centerX() - paint.measureText(text) / 2;
} else if (align == Paint.Align.CENTER) {
x = rectF.centerX();
} else {
x = rectF.centerX() + paint.measureText(text) / 2;
}
//y
metrics = paint.getFontMetrics();
float acent = Math.abs(metrics.ascent);
float descent = Math.abs(metrics.descent);
y = rectF.centerY() + (acent - descent) / 2f;
canvas.drawText(text, x, y, paint);
Log.e("ghui", "top:" + metrics.top + ",ascent:" + metrics.ascent
+ ",dscent:" + metrics.descent + ",leading:" + metrics.leading + ",bottom" + metrics.bottom);
}
rectF is the area you want draw the text,That's it.
Details
Android Canvas.drawText
Worked this out, turns out that android.R.color.black is not the same as Color.BLACK. Changed the code to:
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
canvas.drawPaint(paint);
paint.setColor(Color.BLACK);
paint.setTextSize(20);
canvas.drawText("Some Text", 10, 25, paint);
and it all works fine now!!
jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)
Try this:
(function ( $ ) {
// put all that "wl_alert" code here
}( jQuery ));
So, the $
variable is apparently corrupted, but the jQuery
variable should still refer to the jQuery object. (In normal circumstances, both the $
and jQuery
variables refer to the (same) jQuery object.)
Instead of having to replace the $
name with the jQuery
name in your entire code, you can simply use an IIFE to alias the name manually. So, the outside-variable jQuery
is aliased with the $
variable inside the function.
Here's a simple example to help you understand this concept:
var foo = 'Peter';
(function ( bar ) {
bar // evaluates to 'Peter'
}( foo ));
Change action bar color in android
if you have in your layout activity_main
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
you have to put
in your Activity this code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setBackgroundColor(Color.CYAN);
}
How do I export (and then import) a Subversion repository?
Excerpt from my Blog-Note-to-myself:
Now you can import a dump file e.g. if you are migrating between machines / subversion versions. e.g. if I had created a dump file from the source repository and load it into the new repository as shown below.
Commands for Unix-like systems (from terminal):
svnadmin dump /path/to/your/old/repo > backup.dump
svnadmin load /path/to/your/new/repo < backup.dump.dmp
Commands for Microsoft Windows systems (from cmd shell):
svnadmin dump C:\path\to\your\old\repo > backup.dump
svnadmin load C:\path\to\your\old\repo < backup.dump
excel plot against a date time x series
I know this is an old question, but I was struggling to do this with a time period over 2 hours, so this might help someone. Also, several of the answers don't actually plot against time, giving equal space whatever the duration.
Firstly, as @jameswarren says, use a scatter graph. Then right-click the horizontal axis and choose Format Axis.
Under Number, select Time, and at this point you may find your scale goes a bit crazy, because it chooses to scale the axis by days. So go back to Axis Options and select Fixed for the Minimum, Maximum and Major unit scales.
To set the unit to hours, type in 1/24 = 0.0416667 (I used half that to get half-hourly increments).
To make this start at a round number, multiply it by your preferred number of hours and type that into the Minimum box. In my case 08:00 = 0.333333
LaTeX: remove blank page after a \part or \chapter
I believe that in the book class all \part and \chapter are set to start on a recto page.
from book.cls:
\newcommand\part{%
\if@openright
\cleardoublepage
\else
\clearpage
\fi
\thispagestyle{plain}%
\if@twocolumn
\onecolumn
\@tempswatrue
\else
\@tempswafalse
\fi
\null\vfil
\secdef\@part\@spart}
you should be able to renew that command, and something similar for the \chapter.
How to print struct variables in console?
Maybe this shouldn't be applied for production requests but if you are on debugging mode I suggest you follow the below approach.
marshalledText, _ := json.MarshalIndent(inputStruct, "", " ")
fmt.Println(string(marshalledText))
This results in formatting the data in json format with increased readability.
The requested URL /about was not found on this server
FWIW: I rebuilt a LAMP server from scratch and installed WordPress. I had the same issue after saving my Permalink setting to generate the .htaccess file. Turns out that mod_rewrite was not enabled. I ran across this post on Digital Ocean.
FTA:
First, we need to activate mod_rewrite. It’s available but not enabled with a clean Apache 2 installation.
$ sudo a2enmod rewrite
This will activate the module or alert you that the module is already enabled. To put these changes into effect, restart Apache.
$ sudo systemctl restart apache2
Concatenate String in String Objective-c
simple one:
[[@"first" stringByAppendingString:@"second"] stringByAppendingString:@"third"];
if you have many STRINGS to Concatenate, you should use NSMutableString
for better performance
Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column
<asp:TemplateField HeaderText="ExEmp" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
FooterStyle-BackColor="BurlyWood" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:TextBox ID="txtNoOfExEmp" runat="server" CssClass="form-control input-sm m-bot15"
Font-Bold="true" onkeypress="return isNumberKey(event)" Text='<%#Bind("ExEmp") %>'></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" Width="50px" />
<FooterTemplate>
<asp:Label ID="lblTotNoOfExEmp" Font-Bold="true" runat="server" Text="0" CssClass="form-label"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
private void TotalExEmpOFMonth()
{
Label lbl_TotNoOfExEmp = (Label)GrdPFRecord.FooterRow.FindControl("lblTotNoOfExEmp");
/*Sum of the Total Amount Of month*/
foreach (GridViewRow gvr in GrdPFRecord.Rows)
{
TextBox txt_NoOfExEmp = (TextBox)gvr.FindControl("txtNoOfExEmp");
lbl_TotNoOfExEmp.Text = (Convert.ToDouble(txt_NoOfExEmp.Text) + Convert.ToDouble(lbl_TotNoOfExEmp.Text)).ToString();
lbl_TotNoOfExEmp.Text = string.Format("{0:F0}", Decimal.Parse(lbl_TotNoOfExEmp.Text));
}
}
WebAPI Multiple Put/Post parameters
If attribute routing is being used, you can use the [FromUri] and [FromBody] attributes.
Example:
[HttpPost()]
[Route("api/products/{id:int}")]
public HttpResponseMessage AddProduct([FromUri()] int id, [FromBody()] Product product)
{
// Add product
}
Arduino error: does not name a type?
More recently, I have found that other factors will also cause this error. I had an AES.h, AES.cpp containing a AES class and it gave this same unhelpful error. Only when I renamed to Encryption.h, Encryption.cpp and Encryption as the class name did it suddenly start working. There were no other code changes.
How to pass parameters to ThreadStart method in Thread?
The simplest is just
string filename = ...
Thread thread = new Thread(() => download(filename));
thread.Start();
The advantage(s) of this (over ParameterizedThreadStart
) is that you can pass multiple parameters, and you get compile-time checking without needing to cast from object
all the time.
VBScript to send email without running Outlook
You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:
Set MyEmail=CreateObject("CDO.Message")
MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"
'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
MyEmail.Configuration.Fields.Update
MyEmail.Send
set MyEmail=nothing
If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update
line:
'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username"
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"
More information on using CDO to send email with VBScript can be found on the link below:
http://www.paulsadowski.com/wsh/cdo.htm
MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?
for Xcode 8:
What I do is run sudo du -khd 1 in the Terminal to see my file system's storage amounts for each folder in simple text, then drill up/down into where the huge GB are hiding using the cd command.
Ultimately you'll find the Users//Library/Developer/CoreSimulator/Devices folder where you can have little concern about deleting all those "devices" using iOS versions you no longer need. It's also safe to just delete them all, but keep in mind you'll lose data that's written to the device like sqlite files you may want to use as a backup version.
I once saved over 50GB doing this since I did so much testing on older iOS versions.
How to identify which columns are not "NA" per row in a matrix?
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?
Try passing control to the next matching route. If Express is matching app.get route first, then it won't continue onto the options route unless you do this (note use of next):
app.get('somethingelse', function(req, res, next) {
//..set headers etc.
next();
});
In terms of organising the CORS stuff, I put it in a middleware which is working well for me:
//CORS middleware
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'example.com');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
//...
app.configure(function() {
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'cool beans' }));
app.use(express.methodOverride());
app.use(allowCrossDomain);
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
Java reflection: how to get field value from an object, not knowing its class
I strongly recommend using Java generics to specify what type of object is in that List, ie. List<Car>
. If you have Cars and Trucks you can use a common superclass/interface like this List<Vehicle>
.
However, you can use Spring's ReflectionUtils to make fields accessible, even if they are private like the below runnable example:
List<Object> list = new ArrayList<Object>();
list.add("some value");
list.add(3);
for(Object obj : list)
{
Class<?> clazz = obj.getClass();
Field field = org.springframework.util.ReflectionUtils.findField(clazz, "value");
org.springframework.util.ReflectionUtils.makeAccessible(field);
System.out.println("value=" + field.get(obj));
}
Running this has an output of:
value=[C@1b67f74
value=3
Bootstrap 3 dropdown select
The dropdown list appearing like that depends on what your browser is, as it is not possible to style this away for some. It looks like yours is IE9, but would look quite different in Chrome.
You could look to use something like this:
http://silviomoreto.github.io/bootstrap-select/
Which will make your selectboxes more consistent cross browser.
Capture iOS Simulator video for App Preview
You can combine QuickTime Player + iMovie(Free)
At first choose your desired simulator from xcode and record screen using QuickTime Player. After that use iMovie for making App Preview and finally upload the video with Safari browser.It's simple... :)
Error: Specified cast is not valid. (SqlManagerUI)
There are some funnies restoring old databases into SQL 2008 via the guy; have you tried doing it via TSQL ?
Use Master
Go
RESTORE DATABASE YourDB
FROM DISK = 'C:\YourBackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:\Data\YourMDFFile.mdf',--check and adjust path
MOVE 'YourLDFLogicalName' TO 'D:\Data\YourLDFFile.ldf'
How to retrieve the first word of the output of a command in bash?
If you are sure there are no leading spaces, you can use bash parameter substitution:
$ string="word1 word2"
$ echo ${string/%\ */}
word1
Watch out for escaping the single space. See here for more examples of substitution patterns. If you have bash > 3.0, you could also use regular expression matching to cope with leading spaces - see here:
$ string=" word1 word2"
$ [[ ${string} =~ \ *([^\ ]*) ]]
$ echo ${BASH_REMATCH[1]}
word1
iOS detect if user is on an iPad
Many Answers are good but I use like this in swift 4
Create Constant
struct App {
static let isRunningOnIpad = UIDevice.current.userInterfaceIdiom == .pad ? true : false
}
Use like this
if App.isRunningOnIpad {
return load(from: .main, identifier: identifier)
} else {
return load(from: .ipad, identifier: identifier)
}
Edit: As Suggested Cœur simply create an extension on UIDevice
extension UIDevice {
static let isRunningOnIpad = UIDevice.current.userInterfaceIdiom == .pad ? true : false
}
Could not reserve enough space for object heap to start JVM
It looks like the machine you're trying to run this on has only 256 MB memory.
Maybe the JVM tries to allocate a large, contiguous block of 64 MB memory. The 192 MB that you have free might be fragmented into smaller pieces, so that there is no contiguous block of 64 MB free to allocate.
Try starting your Java program with a smaller heap size, for example:
java -Xms16m ...
Removing multiple keys from a dictionary safely
I have no problem with any of the existing answers, but I was surprised to not find this solution:
keys_to_remove = ['a', 'b', 'c']
my_dict = {k: v for k, v in zip("a b c d e f g".split(' '), [0, 1, 2, 3, 4, 5, 6])}
for k in keys_to_remove:
try:
del my_dict[k]
except KeyError:
pass
assert my_dict == {'d': 3, 'e': 4, 'f': 5, 'g': 6}
Note: I stumbled across this question coming from here. And my answer is related to this answer.
How to remove components created with Angular-CLI
version control is your friend here, do a diff
or equivalent and you should see what's been added/modified.
In fact, removing the component folder might not be enough; with Angular-CLI v1.0, the command ng generate component my-new-component
also edits your app.module.ts
file by adding the respective import
line and the component to the providers
array.
jQuery .each() with input elements
To extract number :
var arrNumber = new Array();
$('input[type=number]').each(function(){
arrNumber.push($(this).val());
})
To extract text:
var arrText= new Array();
$('input[type=text]').each(function(){
arrText.push($(this).val());
})
Edit : .map
implementation
var arrText= $('input[type=text]').map(function(){
return this.value;
}).get();
What are "named tuples" in Python?
I think it's worth adding information about NamedTuples using type hinting:
# dependencies
from typing import NamedTuple, Optional
# definition
class MyNamedTuple(NamedTuple):
an_attribute: str
my_attribute: Optional[str] = None
next_attribute: int = 1
# instantiation
my_named_tuple = MyNamedTuple("abc", "def")
# or more explicitly:
other_tuple = MyNamedTuple(an_attribute="abc", my_attribute="def")
# access
assert "abc" == my_named_tuple.an_attribute
assert 1 == other_tuple.next_attribute
Difference between applicationContext.xml and spring-servlet.xml in Spring Framework
One more point I want to add. In spring-servlet.xml
we include component scan for Controller package.
In following example we include filter annotation for controller package.
<!-- Scans for annotated @Controllers in the classpath -->
<context:component-scan base-package="org.test.web" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
In applicationcontext.xml
we add filter for remaining package excluding controller.
<context:component-scan base-package="org.test">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
how to delete a specific row in codeigniter?
You are using an $id
variable in your model, but your are plucking it from nowhere. You need to pass the $id
variable from your controller to your model.
Controller
Lets pass the $id to the model via a parameter of the row_delete()
method.
function delete_row()
{
$this->load->model('mod1');
// Pass the $id to the row_delete() method
$this->mod1->row_delete($id);
redirect($_SERVER['HTTP_REFERER']);
}
Model
Add the $id to the Model methods parameters.
function row_delete($id)
{
$this->db->where('id', $id);
$this->db->delete('testimonials');
}
The problem now is that your passing the $id
variable from your controller, but it's not declared anywhere in your controller.
Writelines writes lines without newline, Just fills the file
As others have mentioned, and counter to what the method name would imply, writelines
does not add line separators. This is a textbook case for a generator. Here is a contrived example:
def item_generator(things):
for item in things:
yield item
yield '\n'
def write_things_to_file(things):
with open('path_to_file.txt', 'wb') as f:
f.writelines(item_generator(things))
Benefits: adds newlines explicitly without modifying the input or output values or doing any messy string concatenation. And, critically, does not create any new data structures in memory. IO (writing to a file) is when that kind of thing tends to actually matter. Hope this helps someone!
Dynamically Dimensioning A VBA Array?
You have to use the ReDim statement to dynamically size arrays.
Public Sub Test()
Dim NumberOfZombies As Integer
NumberOfZombies = 20000
Dim Zombies() As New Zombie
ReDim Zombies(NumberOfZombies)
End Sub
This can seem strange when you already know the size of your array, but there you go!
Add custom buttons on Slick Carousel
A variation on the answer by @tallgirltaadaa , draw your own button in the shape of a caret:
var a = $('.MyCarouselContainer').slick({
prevArrow: '<canvas class="prevArrowCanvas a-left control-c prev slick-prev" width="15" height="50"></canvas>',
nextArrow: '<canvas class="nextArrowCanvas a-right control-c next slick-next" width="15" height="50"></canvas>'
});
function drawNextPreviousArrows(strokeColor) {
var c = $(".prevArrowCanvas")[0];
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
ctx.moveTo(15, 0);
ctx.lineTo(0, 25);
ctx.lineTo(15, 50);
ctx.lineWidth = 2;
ctx.strokeStyle = strokeColor;
ctx.stroke();
var c = $(".nextArrowCanvas")[0];
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
ctx.moveTo(0, 0);
ctx.lineTo(15, 25);
ctx.lineTo(0, 50);
ctx.lineWidth = 2;
ctx.strokeStyle = strokeColor;
ctx.stroke();
}
drawNextPreviousArrows("#cccccc");
then add the css
.slick-prev, .slick-next
height: 50px;s
}
Insert text into textarea with jQuery
$.fn.extend({
insertAtCaret: function(myValue) {
var elemSelected = window.getSelection();
if(elemSelected) {
var startPos = elemSelected.getRangeAt(0).startOffset;
var endPos = elemSelected.getRangeAt(0).endOffset;
this.val(this.val().substring(0, startPos)+myValue+this.val().substring(endPos,this.val().length));
} else {
this.val(this.val()+ myValue) ;
}
}
});
How do I make an HTML text box show a hint when empty?
Another option, if you're happy to have this feature only for newer browsers, is to use the support offered by HTML 5's placeholder attribute:
<input name="email" placeholder="Email Address">
In the absence of any styles, in Chrome this looks like:
You can try demos out here and in HTML5 Placeholder Styling with CSS.
Be sure to check the browser compatibility of this feature. Support in Firefox was added in 3.7. Chrome is fine. Internet Explorer only added support in 10. If you target a browser that does not support input placeholders, you can use a jQuery plugin called jQuery HTML5 Placeholder, and then just add the following JavaScript code to enable it.
$('input[placeholder], textarea[placeholder]').placeholder();
Grouping switch statement cases together?
No, but you can with an if
-else if
-else
chain which achieves the same result:
if (answer >= 1 && answer <= 4)
cout << "You need more cars.";
else if (answer <= 8)
cout << "Now you need a house.";
else
cout << "What are you? A peace-loving hippie freak?";
You may also want to handle the case of 0 cars and then also the unexpected case of a negative number of cars probably by throwing an exception.
PS: I've renamed Answer
to answer
as it's considered bad style to start variables with an uppercase letter.
As a side note, scripting languages such as Python allow for the nice if answer in [1, 2, 3, 4]
syntax which is a flexible way of achieving what you want.
Swift - Integer conversion to Hours/Minutes/Seconds
Swift 4
func formatSecondsToString(_ seconds: TimeInterval) -> String {
if seconds.isNaN {
return "00:00"
}
let Min = Int(seconds / 60)
let Sec = Int(seconds.truncatingRemainder(dividingBy: 60))
return String(format: "%02d:%02d", Min, Sec)
}
Get root view from current activity
If you need root view of your activity (so you can add your contents there) use
findViewById(android.R.id.content).getRootView()
Also it was reported that on some devices you have to use
getWindow().getDecorView().findViewById(android.R.id.content)
instead.
Please note that as Booger reported, this may be behind navigation bar (with back button etc.) on some devices (but it seems on most devices it is not).
If you need to get view that you added to your activity using setContentView()
method then as pottedmeat wrote you can use
final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
But better just set id to this view in your xml layout and use this id instead.
urllib2 and json
Example - sending some data encoded as JSON as a POST data:
import json
import urllib2
data = json.dumps([1, 2, 3])
f = urllib2.urlopen(url, data)
response = f.read()
f.close()
SQL Server: use CASE with LIKE
Add an END
at last before alias name.
CASE WHEN countries LIKE '%'+@selCountry+'%'
THEN 'national' ELSE 'regional'
END AS validity
For example:
SELECT CASE WHEN countries LIKE '%'+@selCountry+'%'
THEN 'national' ELSE 'regional'
END AS validity
FROM TableName
Comparing two input values in a form validation with AngularJS
I recently wrote a custom directive which can be generic enough to do any validation. It take a validation function from the current scope
module.directive('customValidator', [function () {
return {
restrict: 'A',
require: 'ngModel',
scope: { validateFunction: '&' },
link: function (scope, elm, attr, ngModelCtrl) {
ngModelCtrl.$parsers.push(function (value) {
var result = scope.validateFunction({ 'value': value });
if (result || result === false) {
if (result.then) {
result.then(function (data) { //For promise type result object
ngModelCtrl.$setValidity(attr.customValidator, data);
}, function (error) {
ngModelCtrl.$setValidity(attr.customValidator, false);
});
}
else {
ngModelCtrl.$setValidity(attr.customValidator, result);
return result ? value : undefined; //For boolean result return based on boolean value
}
}
return value;
});
}
};
}]);
To use it you do
<input type="email" name="email2" ng-model="emailReg2" custom-validator='emailMatch' data-validate-function='checkEmailMatch(value)'>
<span ng-show="registerForm.email2.$error.emailMatch">Emails have to match!</span>
In you controller then you can implement the method, that should return true or false
$scope.checkEmailMatch=function(value) {
return value===$scope.emailReg;
}
The advantage is that you do not have to write custom directive for each custom validation.
Check file extension in upload form in PHP
Not sure if this would have a faster computational time, but another option...
$acceptedFormats = array('gif', 'png', 'jpg');
if(!in_array(pathinfo($filename, PATHINFO_EXTENSION), $acceptedFormats))) {
echo 'error';
}
Set iframe content height to auto resize dynamically
In the iframe:
So that means you have to add some code in the iframe page.
Simply add this script to your code IN THE IFRAME:
<body onload="parent.alertsize(document.body.scrollHeight);">
In the holding page:
In the page holding the iframe (in my case with ID="myiframe") add a small javascript:
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.
To that JavaScript function it sends how many pixels its (iframe) height is.
The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.
That's it, nothing else is needed.
But if you like to know some more small tricks keep on reading...
DYNAMIC HEIGHT IN THE IFRAME?
If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload).
I usually add a very simple toggle script I found online:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
}
</script>
to that script just add:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>
How you use the above script is easy:
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)
Complete holding page code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>
<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>
Complete iframe code: (this iframe named "theiframe.htm")
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight);
}
</script>
</head>
<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END
</body>
</html>
Demo
Excel Looping through rows and copy cell values to another worksheet
Private Sub CommandButton1_Click()
Dim Z As Long
Dim Cellidx As Range
Dim NextRow As Long
Dim Rng As Range
Dim SrcWks As Worksheet
Dim DataWks As Worksheet
Z = 1
Set SrcWks = Worksheets("Sheet1")
Set DataWks = Worksheets("Sheet2")
Set Rng = EntryWks.Range("B6:ad6")
NextRow = DataWks.UsedRange.Rows.Count
NextRow = IIf(NextRow = 1, 1, NextRow + 1)
For Each RA In Rng.Areas
For Each Cellidx In RA
Z = Z + 1
DataWks.Cells(NextRow, Z) = Cellidx
Next Cellidx
Next RA
End Sub
Alternatively
Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10")
This is a CopynPaste - Method
Sub CopyDataToPlan()
Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean
On Error GoTo Err_Execute
'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value
Sheets("Plan").Select
'Start at column B
LColumn = 2
LFound = False
While LFound = False
'Encountered blank cell in row 2, terminate search
If Len(Cells(2, LColumn)) = 0 Then
MsgBox "No matching date was found."
Exit Sub
'Found match in row 2
ElseIf Cells(2, LColumn) = LDate Then
'Select values to copy from "Rolling Plan" sheet
Sheets("Rolling Plan").Select
Range("B5:H6").Select
Selection.Copy
'Paste onto "Plan" sheet
Sheets("Plan").Select
Cells(3, LColumn).Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
LFound = True
MsgBox "The data has been successfully copied."
'Continue searching
Else
LColumn = LColumn + 1
End If
Wend
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
And there might be some methods doing that in Excel.
"Couldn't read dependencies" error with npm
1)Nodejs installs in C:\ProgramFiles in some cases. Try installing in C: drive or another directory if you don't have admin rights.
2)Make sure you are not installing behind a company's proxy setting. This can sometimes affect installation.
3) Finally, make sure you run the npm command from this directory:
Path\nodejs\node_modules\npm
where Path is your own directory.
Choosing a file in Python with simple Dialog
Another option to consider is Zenity: http://freecode.com/projects/zenity.
I had a situation where I was developing a Python server application (no GUI component) and hence didn't want to introduce a dependency on any python GUI toolkits, but I wanted some of my debug scripts to be parameterized by input files and wanted to visually prompt the user for a file if they didn't specify one on the command line. Zenity was a perfect fit. To achieve this, invoke "zenity --file-selection" using the subprocess module and capture the stdout. Of course this solution isn't Python-specific.
Zenity supports multiple platforms and happened to already be installed on our dev servers so it facilitated our debugging/development without introducing an unwanted dependency.
Temporary tables in stored procedures
The database uses the same lock for all #temp tables so if you are using a lot you will get deadlock problems. It is better to use @ table variables for concurrency.
How to change the display name for LabelFor in razor in mvc3?
You could decorate your view model property with the [DisplayName]
attribute and specify the text to be used:
[DisplayName("foo bar")]
public string SomekingStatus { get; set; }
Or use another overload of the LabelFor helper which allows you to specify the text:
@Html.LabelFor(model => model.SomekingStatus, "foo bar")
And, no, you cannot specify a class name in MVC3 as you tried to do, as the LabelFor
helper doesn't support that. However, this would work in MVC4 or 5.
How to find where gem files are installed
You can check it from your command prompt by running gem help commands
and then selecting the proper command:
kirti@kirti-Aspire-5733Z:~$ gem help commands
GEM commands are:
build Build a gem from a gemspec
cert Manage RubyGems certificates and signing settings
check Check a gem repository for added or missing files
cleanup Clean up old versions of installed gems in the local
repository
contents Display the contents of the installed gems
dependency Show the dependencies of an installed gem
environment Display information about the RubyGems environment
fetch Download a gem and place it in the current directory
generate_index Generates the index files for a gem server directory
help Provide help on the 'gem' command
install Install a gem into the local repository
list Display gems whose name starts with STRING
lock Generate a lockdown list of gems
mirror Mirror all gem files (requires rubygems-mirror)
outdated Display all gems that need updates
owner Manage gem owners on RubyGems.org.
pristine Restores installed gems to pristine condition from
files located in the gem cache
push Push a gem up to RubyGems.org
query Query gem information in local or remote repositories
rdoc Generates RDoc for pre-installed gems
regenerate_binstubs Re run generation of executable wrappers for gems.
search Display all gems whose name contains STRING
server Documentation and gem repository HTTP server
sources Manage the sources and cache file RubyGems uses to
search for gems
specification Display gem specification (in yaml)
stale List gems along with access times
uninstall Uninstall gems from the local repository
unpack Unpack an installed gem to the current directory
update Update installed gems to the latest version
which Find the location of a library file you can require
yank Remove a specific gem version release from
RubyGems.org
For help on a particular command, use 'gem help COMMAND'.
Commands may be abbreviated, so long as they are unambiguous.
e.g. 'gem i rake' is short for 'gem install rake'.
kirti@kirti-Aspire-5733Z:~$
Now from the above I can see the command environment
is helpful. So I would do:
kirti@kirti-Aspire-5733Z:~$ gem help environment
Usage: gem environment [arg] [options]
Common Options:
-h, --help Get help on this command
-V, --[no-]verbose Set the verbose level of output
-q, --quiet Silence commands
--config-file FILE Use this config file instead of default
--backtrace Show stack backtrace on errors
--debug Turn on Ruby debugging
Arguments:
packageversion display the package version
gemdir display the path where gems are installed
gempath display path used to search for gems
version display the gem format version
remotesources display the remote gem servers
platform display the supported gem platforms
<omitted> display everything
Summary:
Display information about the RubyGems environment
Description:
The RubyGems environment can be controlled through command line arguments,
gemrc files, environment variables and built-in defaults.
Command line argument defaults and some RubyGems defaults can be set in a
~/.gemrc file for individual users and a /etc/gemrc for all users. These
files are YAML files with the following YAML keys:
:sources: A YAML array of remote gem repositories to install gems from
:verbose: Verbosity of the gem command. false, true, and :really are the
levels
:update_sources: Enable/disable automatic updating of repository metadata
:backtrace: Print backtrace when RubyGems encounters an error
:gempath: The paths in which to look for gems
:disable_default_gem_server: Force specification of gem server host on
push
<gem_command>: A string containing arguments for the specified gem command
Example:
:verbose: false
install: --no-wrappers
update: --no-wrappers
:disable_default_gem_server: true
RubyGems' default local repository can be overridden with the GEM_PATH and
GEM_HOME environment variables. GEM_HOME sets the default repository to
install into. GEM_PATH allows multiple local repositories to be searched for
gems.
If you are behind a proxy server, RubyGems uses the HTTP_PROXY,
HTTP_PROXY_USER and HTTP_PROXY_PASS environment variables to discover the
proxy server.
If you would like to push gems to a private gem server the RUBYGEMS_HOST
environment variable can be set to the URI for that server.
If you are packaging RubyGems all of RubyGems' defaults are in
lib/rubygems/defaults.rb. You may override these in
lib/rubygems/defaults/operating_system.rb
kirti@kirti-Aspire-5733Z:~$
Finally to show you what you asked, I would do:
kirti@kirti-Aspire-5733Z:~$ gem environment gemdir
/home/kirti/.rvm/gems/ruby-2.0.0-p0
kirti@kirti-Aspire-5733Z:~$ gem environment gempath
/home/kirti/.rvm/gems/ruby-2.0.0-p0:/home/kirti/.rvm/gems/ruby-2.0.0-p0@global
kirti@kirti-Aspire-5733Z:~$
How to describe "object" arguments in jsdoc?
I see that there is already an answer about the @return tag, but I want to give more details about it.
First of all, the official JSDoc 3 documentation doesn't give us any examples about the @return for a custom object. Please see https://jsdoc.app/tags-returns.html. Now, let's see what we can do until some standard will appear.
Function returns object where keys are dynamically generated. Example: {1: 'Pete', 2: 'Mary', 3: 'John'}
. Usually, we iterate over this object with the help of for(var key in obj){...}
.
Possible JSDoc according to https://google.github.io/styleguide/javascriptguide.xml#JsTypes
/**
* @return {Object.<number, string>}
*/
function getTmpObject() {
var result = {}
for (var i = 10; i >= 0; i--) {
result[i * 3] = 'someValue' + i;
}
return result
}
Function returns object where keys are known constants. Example: {id: 1, title: 'Hello world', type: 'LEARN', children: {...}}
. We can easily access properties of this object: object.id
.
Possible JSDoc according to https://groups.google.com/forum/#!topic/jsdoc-users/TMvUedK9tC4
Fake It.
/**
* Generate a point.
*
* @returns {Object} point - The point generated by the factory.
* @returns {number} point.x - The x coordinate.
* @returns {number} point.y - The y coordinate.
*/
var pointFactory = function (x, y) {
return {
x:x,
y:y
}
}
The Full Monty.
/**
@class generatedPoint
@private
@type {Object}
@property {number} x The x coordinate.
@property {number} y The y coordinate.
*/
function generatedPoint(x, y) {
return {
x:x,
y:y
};
}
/**
* Generate a point.
*
* @returns {generatedPoint} The point generated by the factory.
*/
var pointFactory = function (x, y) {
return new generatedPoint(x, y);
}
Define a type.
/**
@typedef generatedPoint
@type {Object}
@property {number} x The x coordinate.
@property {number} y The y coordinate.
*/
/**
* Generate a point.
*
* @returns {generatedPoint} The point generated by the factory.
*/
var pointFactory = function (x, y) {
return {
x:x,
y:y
}
}
According to https://google.github.io/styleguide/javascriptguide.xml#JsTypes
package javax.servlet.http does not exist
The solution that work for is were add the next dependency to my pom.xml file.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
What are Unwind segues for and how do you use them?
For example if you navigate from viewControllerB to viewControllerA then in your viewControllerA below delegate will call and data will share.
@IBAction func unWindSeague (_ sender : UIStoryboardSegue) {
if sender.source is ViewControllerB {
if let _ = sender.source as? ViewControllerB {
self.textLabel.text = "Came from B = B->A , B exited"
}
}
}
- Unwind Seague Source View Controller ( You Need to connect Exit Button to VC’s exit icon and connect it to unwindseague:
- Unwind Seague Completed -> TextLabel of viewControllerA is Changed.
Removing a non empty directory programmatically in C or C++
The easiest way to do this is with remove_all function of the Boost.Filesystem library. Besides, the resulting code will be portable.
If you want to write something specific for Unix (rmdir) or for Windows (RemoveDirectory) then you'll have to write a function that deletes are subfiles and subfolders recursively.
EDIT
Looks like this question was already asked, in fact someone already recommended Boost's remove_all. So please don't upvote my answer.
How the single threaded non blocking IO model works in Node.js
Okay, most things should be clear so far... the tricky part is the SQL: if it is not in reality running in another thread or process in it’s entirety, the SQL-execution has to be broken down into individual steps (by an SQL processor made for asynchronous execution!), where the non-blocking ones are executed, and the blocking ones (e.g. the sleep) actually can be transferred to the kernel (as an alarm interrupt/event) and put on the event list for the main loop.
That means, e.g. the interpretation of the SQL, etc. is done immediately, but during the wait (stored as an event to come in the future by the kernel in some kqueue, epoll, ... structure; together with the other IO operations) the main loop can do other things and eventually check if something happened of those IOs and waits.
So, to rephrase it again: the program is never (allowed to get) stuck, sleeping calls are never executed. Their duty is done by the kernel (write something, wait for something to come over the network, waiting for time to elapse) or another thread or process. – The Node process checks if at least one of those duties is finished by the kernel in the only blocking call to the OS once in each event-loop-cycle. That point is reached, when everything non-blocking is done.
Clear? :-)
I don’t know Node. But where does the c.query come from?
What is the most efficient way to store tags in a database?
One item is going to have many tags. And one tag will belong to many items. This implies to me that you'll quite possibly need an intermediary table to overcome the many-to-many obstacle.
Something like:
Table: Items
Columns: Item_ID, Item_Title, Content
Table: Tags
Columns: Tag_ID, Tag_Title
Table: Items_Tags
Columns: Item_ID, Tag_ID
It might be that your web app is very very popular and need de-normalizing down the road, but it's pointless muddying the waters too early.
Iterate through Nested JavaScript Objects
Here is a concise breadth-first iterative solution, which I prefer to recursion:
const findCar = function(car) {
const carSearch = [cars];
while(carSearch.length) {
let item = carSearch.shift();
if (item.label === car) return true;
carSearch.push(...item.subs);
}
return false;
}
Add one year in current date PYTHON
Here's one more answer that I've found to be pretty concise and doesn't use external packages:
import datetime as dt
import calendar
# Today, in `dt.date` type
day = dt.datetime.now().date()
one_year_delta = dt.timedelta(days=366 if ((day.month >= 3 and calendar.isleap(day.year+1)) or
(day.month < 3 and calendar.isleap(day.year))) else 365)
# Add one year to the current date
print(day + one_year_delta)
Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine
Eureka ! Finally I found a solution on this.
This is caused by Windows update that stops any 32-bit processes from consuming more than 1200 MB on a 64-bit machine. The only way you can repair this is by using the System Restore option on Win 7.
Start >> All Programs >> Accessories >> System Tools >> System Restore.
And then restore to a date on which your Java worked fine. This worked for me. What is surprising here is Windows still pushes system updates under the name of "Critical Updates" even when you disable all windows updates. ^&%)#* Windows :-)
How to prevent Google Colab from disconnecting?
I would recommend using JQuery (It seems that Co-lab includes JQuery by default).
function ClickConnect(){
console.log("Working");
$("colab-toolbar-button").click();
}
setInterval(ClickConnect,60000);
Loop through an array php
Starting simple, with no HTML:
foreach($database as $file) {
echo $file['filename'] . ' at ' . $file['filepath'];
}
And you can otherwise manipulate the fields in the foreach.
C# Test if user has write access to a folder
Try this:
try
{
DirectoryInfo di = new DirectoryInfo(path);
DirectorySecurity acl = di.GetAccessControl();
AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount));
WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(currentUser);
foreach (AuthorizationRule rule in rules)
{
FileSystemAccessRule fsAccessRule = rule as FileSystemAccessRule;
if (fsAccessRule == null)
continue;
if ((fsAccessRule.FileSystemRights & FileSystemRights.WriteData) > 0)
{
NTAccount ntAccount = rule.IdentityReference as NTAccount;
if (ntAccount == null)
{
continue;
}
if (principal.IsInRole(ntAccount.Value))
{
Console.WriteLine("Current user is in role of {0}, has write access", ntAccount.Value);
continue;
}
Console.WriteLine("Current user is not in role of {0}, does not have write access", ntAccount.Value);
}
}
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("does not have write access");
}
How to determine SSL cert expiration date from a PEM encoded certificate?
One line checking on true/false if cert of domain will be expired in some time later(ex. 15 days):
openssl x509 -checkend $(( 24*3600*15 )) -noout -in <(openssl s_client -showcerts -connect my.domain.com:443 </dev/null 2>/dev/null | openssl x509 -outform PEM)
if [ $? -eq 0 ]; then
echo 'good'
else
echo 'bad'
fi
align images side by side in html
You mean something like this?
<div class="image123">
<div class="imgContainer">
<img src="/images/tv.gif" height="200" width="200"/>
<p>This is image 1</p>
</div>
<div class="imgContainer">
<img class="middle-img" src="/images/tv.gif"/ height="200" width="200"/>
<p>This is image 2</p>
</div>
<div class="imgContainer">
<img src="/images/tv.gif"/ height="200" width="200"/>
<p>This is image 3</p>
</div>
</div>
with the imgContainer style as
.imgContainer{
float:left;
}
Also see this jsfiddle.
Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink
For a one-page web application where I add scrollable sections dynamically, I trigger OSX's scrollbars by programmatically scrolling one pixel down and back up:
// Plain JS:
var el = document.getElementById('scrollable-section');
el.scrollTop = 1;
el.scrollTop = 0;
// jQuery:
$('#scrollable-section').scrollTop(1).scrollTop(0);
This triggers the visual cue fading in and out.
setState() inside of componentDidUpdate()
The componentDidUpdate
signature is void::componentDidUpdate(previousProps, previousState)
. With this you will be able to test which props/state are dirty and call setState
accordingly.
Example:
componentDidUpdate(previousProps, previousState) {
if (previousProps.data !== this.props.data) {
this.setState({/*....*/})
}
}
Pass a JavaScript function as parameter
You can also use eval()
to do the same thing.
//A function to call
function needToBeCalled(p1, p2)
{
alert(p1+"="+p2);
}
//A function where needToBeCalled passed as an argument with necessary params
//Here params is comma separated string
function callAnotherFunction(aFunction, params)
{
eval(aFunction + "("+params+")");
}
//A function Call
callAnotherFunction("needToBeCalled", "10,20");
That's it. I was also looking for this solution and tried solutions provided in other answers but finally got it work from above example.
Octave/Matlab: Adding new elements to a vector
Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:
big = 1e5;
tic;
x = rand(big,1);
toc
x = zeros(big,1);
tic;
for ii = 1:big
x(ii) = rand;
end
toc
x = [];
tic;
for ii = 1:big
x(end+1) = rand;
end;
toc
x = [];
tic;
for ii = 1:big
x = [x rand];
end;
toc
Elapsed time is 0.004611 seconds.
Elapsed time is 0.016448 seconds.
Elapsed time is 0.034107 seconds.
Elapsed time is 12.341434 seconds.
I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get
Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.
So I guess the speed advantage only applies to more recent versions of Matlab
git submodule tracking latest
Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming
Update March 2013
Git 1.8.2 added the possibility to track branches.
"git submodule
" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).
# add submodule to track master branch
git submodule add -b master [URL to Git repo];
# update your submodule
git submodule update --remote
If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".
Also see Vogella's tutorial on submodules for general information on submodules.
Note:
git submodule add -b . [URL to Git repo];
^^^
See git submodule
man page:
A special value of .
is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.
See commit b928922727d6691a3bdc28160f93f25712c565f6:
submodule add
: If --branch
is given, record it in .gitmodules
This allows you to easily record a submodule.<name>.branch
option in .gitmodules
when you add a new submodule. With this patch,
$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>
reduces to
$ git submodule add -b <branch> <repository> [<path>]
This means that future calls to
$ git submodule update --remote ...
will get updates from the same branch that you used to initialize the submodule, which is usually what you want.
Signed-off-by: W. Trevor King [email protected]
Original answer (February 2012):
A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log
within that submodule.
So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:
- cd in the submodule
- git fetch/pull to make sure it has the latest commits on the right branch
- cd back in the parent repo
- add and commit in order to record the new commit of the submodule.
gitslave (that you already looked at) seems to be the best fit, including for the commit operation.
It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).
Other alternatives are detailed here.
How to remove a row from JTable?
A JTable normally forms the View part of an MVC implementation. You'll want to remove rows from your model. The JTable, which should be listening for these changes, will update to reflect this removal. Hence you won't find removeRow() or similar as a method on JTable.
Test if a property is available on a dynamic variable
In my case, I needed to check for the existence of a method with a specific name, so I used an interface for that
var plugin = this.pluginFinder.GetPluginIfInstalled<IPlugin>(pluginName) as dynamic;
if (plugin != null && plugin is ICustomPluginAction)
{
plugin.CustomPluginAction(action);
}
Also, interfaces can contain more than just methods:
Interfaces can contain methods, properties, events, indexers, or any
combination of those four member types.
From: Interfaces (C# Programming Guide)
Elegant and no need to trap exceptions or play with reflexion...
Jenkins: Failed to connect to repository
Not mentionned here so far, but this can come also from stash.
We encountered the same issue, the root cause for our problem was that the stash instance we use for jenkins did crash.
Restarting stash solved it in our case.
Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails
If you want to keep the default config but want md5 authentication with socket connection for one specific user/db connection, add a "local" line BEFORE the "local all/all" line:
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local dbname username md5 # <-- this line
local all all peer
# IPv4 local connections:
host all all 127.0.0.1/32 ident
# IPv6 local connections:
host all all ::1/128 ident
How to dynamically create CSS class in JavaScript and apply?
https://jsfiddle.net/xk6Ut/256/
One option to dynamically create and update CSS class in JavaScript:
- Using Style Element to create a CSS section
- Using an ID for the style element so that we can update the CSS
class
.....
function writeStyles(styleName, cssText) {
var styleElement = document.getElementById(styleName);
if (styleElement)
document.getElementsByTagName('head')[0].removeChild(
styleElement);
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = styleName;
styleElement.innerHTML = cssText;
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
...
var cssText = '.testDIV{ height:' + height + 'px !important; }';
writeStyles('styles_js', cssText)
MySQL Event Scheduler on a specific time everyday
DROP EVENT IF EXISTS xxxEVENTxxx;
CREATE EVENT xxxEVENTxxx
ON SCHEDULE
EVERY 1 DAY
STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
DO
--process;
¡IMPORTANT!->
SET GLOBAL event_scheduler = ON;
How to remove an unpushed outgoing commit in Visual Studio?
Assuming you have pushed most recent changes to the server:
- Close Visual Studio and delete your local copy of the project
- Open Visual Studio, go to Team Explorer tab, click Manage Connections. (plug)
- Click the dropdown arrow next to Manage Connections, Connect to a Project
- Select the project, confirm the local path, and click the Connect button.
Once you reopen the project both commits and changes should be zero.
VBScript -- Using error handling
Note that On Error Resume Next
is not set globally. You can put your unsafe part of code eg into a function, which will interrupted immediately if error occurs, and call this function from sub containing precedent OERN
statement.
ErrCatch()
Sub ErrCatch()
Dim Res, CurrentStep
On Error Resume Next
Res = UnSafeCode(20, CurrentStep)
MsgBox "ErrStep " & CurrentStep & vbCrLf & Err.Description
End Sub
Function UnSafeCode(Arg, ErrStep)
ErrStep = 1
UnSafeCode = 1 / (Arg - 10)
ErrStep = 2
UnSafeCode = 1 / (Arg - 20)
ErrStep = 3
UnSafeCode = 1 / (Arg - 30)
ErrStep = 0
End Function
Why should I use IHttpActionResult instead of HttpResponseMessage?
I'd rather implement TaskExecuteAsync interface function for IHttpActionResult. Something like:
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
switch ((Int32)_respContent.Code)
{
case 1:
case 6:
case 7:
response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
break;
case 2:
case 3:
case 4:
response = _request.CreateResponse(HttpStatusCode.BadRequest, _respContent);
break;
}
return Task.FromResult(response);
}
, where _request is the HttpRequest and _respContent is the payload.
NoSql vs Relational database
Not all data is relational. For those situations, NoSQL can be helpful.
With that said, NoSQL stands for "Not Only SQL". It's not intended to knock SQL or supplant it.
SQL has several very big advantages:
- Strong mathematical basis.
- Declarative syntax.
- A well-known language in Structured Query Language (SQL).
Those haven't gone away.
It's a mistake to think about this as an either/or argument. NoSQL is an alternative that people need to consider when it fits, that's all.
Documents can be stored in non-relational databases, like CouchDB.
Maybe reading this will help.
add title attribute from css
Well, although it's not actually possible to change the title attribute, it is possible to show a tooltip completely from css.
You can check a working version out at http://jsfiddle.net/HzH3Z/5/.
What you can do is style the label:after selector and give it display:none, and set it's content from css. You can then change the display attribute to display:block on label:hover:after, and it will show.
Like this:
label:after{
content: "my tooltip";
padding: 2px;
display:none;
position: relative;
top: -20px;
right: -30px;
width: 150px;
text-align: center;
background-color: #fef4c5;
border: 1px solid #d4b943;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
-ms-border-radius: 2px;
border-radius: 2px;
}
label:hover:after{
display: block;
}
How to make sure that string is valid JSON using JSON.NET
Here is a TryParse extension method based on Habib's answer:
public static bool TryParse(this string strInput, out JToken output)
{
if (String.IsNullOrWhiteSpace(strInput))
{
output = null;
return false;
}
strInput = strInput.Trim();
if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
(strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
{
try
{
output = JToken.Parse(strInput);
return true;
}
catch (JsonReaderException jex)
{
//Exception in parsing json
//optional: LogError(jex);
output = null;
return false;
}
catch (Exception ex) //some other exception
{
//optional: LogError(ex);
output = null;
return false;
}
}
else
{
output = null;
return false;
}
}
Usage:
JToken jToken;
if (strJson.TryParse(out jToken))
{
// work with jToken
}
else
{
// not valid json
}
create array from mysql query php
You do need to iterate through...
$typeArray = array();
$query = "select * from whatever";
$result = mysql_query($query);
if ($result) {
while ($record = mysql_fetch_array($results)) $typeArray[] = $record['type'];
}
Responsive Bootstrap Jumbotron Background Image
The below code works for all the screens :
.jumbotron {
background: url('backgroundimage.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
}
The cover property will resize the background image to cover the entire container, even if it has to stretch the image or cut a little bit off one of the edges.
What does $ mean before a string?
$ syntax is nice, but with one downside.
If you need something like a string template, that is declared on the class level as field...well in one place as it should be.
Then you have to declare the variables on the same level...which is not really cool.
It is much nicer to use the string.Format syntax for this kind of things
class Example1_StringFormat {
string template = $"{0} - {1}";
public string FormatExample1() {
string some1 = "someone";
return string.Format(template, some1, "inplacesomethingelse");
}
public string FormatExample2() {
string some2 = "someoneelse";
string thing2 = "somethingelse";
return string.Format(template, some2, thing2);
}
}
The use of globals is not really ok and besides that - it does not work with globals either
static class Example2_Format {
//must have declaration in same scope
static string some = "";
static string thing = "";
static string template = $"{some} - {thing}";
//This returns " - " and not "someone - something" as you would maybe
//expect
public static string FormatExample1() {
some = "someone";
thing = "something";
return template;
}
//This returns " - " and not "someoneelse- somethingelse" as you would
//maybe expect
public static string FormatExample2() {
some = "someoneelse";
thing = "somethingelse";
return template;
}
}
How to access remote server with local phpMyAdmin client?
In Windows with Wamp Server Installed you may find the configuration file
C:\wamp64\apps\phpmyadmin4.8.4\config.inc.php
Change the bolow line as appropriate
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['port'] = 3306;//$wampConf['mysqlPortUsed'];
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = '';
$cfg['Servers'][$i]['password'] = '';
How to create an executable .exe file from a .m file
It used to be possible to compile Matlab to C with older versions of Matlab. Check out other tools that Matlab comes with.
Newest Matlab code can be exported as a Java's jar or a .Net Dll, etc. You can then write an executable against that library - it will be obfuscated by the way. The users will have to install a freely available Matlab Runtime.
Like others mentioned, mcc / mcc.exe is what you want to convert matlab code to C code.
Creating a new directory in C
Look at stat
for checking if the directory exists,
And mkdir
, to create a directory.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
struct stat st = {0};
if (stat("/some/directory", &st) == -1) {
mkdir("/some/directory", 0700);
}
You can see the manual of these functions with the man 2 stat
and man 2 mkdir
commands.
Excel: the Incredible Shrinking and Expanding Controls
What I started doing a while back was to have a single sub that sets the size of all my controls. I can then run this sub from any point in the code where the controls grow or shrink. It's sometimes a lot of extra finicky work, but it keeps my buttons from eating my spreadsheet.
Setting a JPA timestamp column to be generated by the database?
I have this working well using JPA2.0 and MySQL 5.5.10, for cases where I only care about the last time the row was modified. MySQL will create a timestamp on first insertion, and every time UPDATE is called on the row. (NOTE: this will be problematic if I cared whether or not the UPDATE actually made a change).
The "timestamp" column in this example is like a "last-touched" column.x`
The code below uses a separate column "version" for optimistic locking.
private long version;
private Date timeStamp
@Version
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
// columnDefinition could simply be = "TIMESTAMP", as the other settings are the MySQL default
@Column(name="timeStamp", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
@Temporal(TemporalType.TIMESTAMP)
public Date getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
(NOTE: @Version doesn't work on a MySQL "DATETIME" column, where the attribute type is "Date" in the Entity class. This was because Date was generating a value down to the millisecond, however MySQL was not storing the millisecond, so when it did a comparison between what was in the database, and the "attached" entity, it thought they had different version numbers)
From the MySQL manual regarding TIMESTAMP :
With neither DEFAULT nor ON UPDATE clauses, it is the same as DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP.
How can I write variables inside the tasks file in ansible
In Your example, apache.yml is tasklist, but not playbook
In depends on desired architecture, You can do one of:
Convert apache.yml to role. Then define tasks in roles/apache/tasks/mail.yml and variables in roles/apache/defaults/mail.yml (vars in defaults can be overriden when role applied)
Set vars in play.yml playbook
play.yml
---
- hosts: 127.0.0.1
connection: local
sudo: false
vars:
url: czxcxz
tasks:
- include: apache.yml
apache.yml
- name: Download apache
shell: wget {{url}}
Default settings Raspberry Pi /etc/network/interfaces
For my Raspberry Pi 3B model it was
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet manual
allow-hotplug wlan0
iface wlan0 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
allow-hotplug wlan1
iface wlan1 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
What does ENABLE_BITCODE do in xcode 7?
Bitcode (iOS, watchOS)
Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.
Basically this concept is somewhat similar to java where byte code is run on different JVM's and in this case the bitcode is placed on iTune store and instead of giving the intermediate code to different platforms(devices) it provides the compiled code which don't need any virtual machine to run.
Thus we need to create the bitcode once and it will be available for existing or coming devices. It's the Apple's headache to compile an make it compatible with each platform they have.
Devs don't have to make changes and submit the app again to support new platforms.
Let's take the example of iPhone 5s when apple introduced x64
chip in it. Although x86
apps were totally compatible with x64
architecture but to fully utilise the x64
platform the developer has to change the architecture or some code. Once s/he's done the app is submitted to the app store for the review.
If this bitcode concept was launched earlier then we the developers doesn't have to make any changes to support the x64
bit architecture.
Extract first item of each sublist
lst = [['a','b','c'], [1,2,3], ['x','y','z']]
outputlist = []
for values in lst:
outputlist.append(values[0])
print(outputlist)
Output: ['a', 1, 'x']
Build project into a JAR automatically in Eclipse
Create an Ant file and tell Eclipse to build it. There are only two steps and each is easy with the step-by-step instructions below.
Step 1
Create a build.xml file and add to package explorer:
<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file -->
<project name="TestMain" default="CreateJar">
<target name="CreateJar" description="Create Jar file">
<jar jarfile="Test.jar" basedir="." includes="*.class" />
</target>
</project>
Eclipse should looks something like the screenshot below. Note the Ant icon on build.xml.
Step 2
Right-click on the root node in the project.
- Select Properties
- Select Builders
- Select New
- Select Ant Build
- In the Main tab, complete the path to the build.xml file in the bin folder.
Check the Output
The Eclipse output window (named Console) should show the following after a build:
Buildfile: /home/<user>/src/Test/build.xml
CreateJar:
[jar] Building jar: /home/<user>/src/Test/Test.jar
BUILD SUCCESSFUL
Total time: 152 milliseconds
EDIT: Some helpful comments by @yeoman and @betlista
@yeoman I think the correct include would be /.class, not *.class, as most
people use packages and thus recursive search for class files makes
more sense than flat inclusion
@betlista I would recomment to not to have build.xml in src folder
Homebrew refusing to link OpenSSL
I had the same problem while trying to install newer version of ruby 2.6.5
https://github.com/kelaberetiv/TagUI/issues/86 helps me to solve the problem. This if for macOS catalina Version 10.15.1
Basically, I did update and upgrade
homebrew and install openssl and install ruby.
brew update && brew upgrade
brew install openssl
Then create these 2 symlinks
ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/
ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/
then installed ruby 2.6.5
Find the similarity metric between two strings
Note, difflib.SequenceMatcher
only finds the longest contiguous matching subsequence, this is often not what is desired, for example:
>>> a1 = "Apple"
>>> a2 = "Appel"
>>> a1 *= 50
>>> a2 *= 50
>>> SequenceMatcher(None, a1, a2).ratio()
0.012 # very low
>>> SequenceMatcher(None, a1, a2).get_matching_blocks()
[Match(a=0, b=0, size=3), Match(a=250, b=250, size=0)] # only the first block is recorded
Finding the similarity between two strings is closely related to the concept of pairwise sequence alignment in bioinformatics. There are many dedicated libraries for this including biopython. This example implements the Needleman Wunsch algorithm:
>>> from Bio.Align import PairwiseAligner
>>> aligner = PairwiseAligner()
>>> aligner.score(a1, a2)
200.0
>>> aligner.algorithm
'Needleman-Wunsch'
Using biopython or another bioinformatics package is more flexible than any part of the python standard library since many different scoring schemes and algorithms are available. Also, you can actually get the matching sequences to visualise what is happening:
>>> alignment = next(aligner.align(a1, a2))
>>> alignment.score
200.0
>>> print(alignment)
Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-
|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-
App-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-el
How do you keep parents of floated elements from collapsing?
The problem happens when a floated element is within a container box, that element does not automatically force the container’s height adjust to the floated element. When an element is floated, its parent no longer contains it because the float is removed from the flow. You can use 2 methods to fix it:
{ clear: both; }
clearfix
Once you understand what is happening, use the method below to “clearfix” it.
.clearfix:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
.clearfix {
display: inline-block;
}
html[xmlns] .clearfix {
display: block;
}
* html .clearfix {
height: 1%;
}
Demonstration :)
What is correct media query for IPad Pro?
I tried several of the proposed answers but the problem is that the media queries conflicted with other queries and instead of displaying the mobile CSS on the iPad Pro, it was displaying the desktop CSS. So instead of using max and min for dimensions, I used the EXACT VALUES and it works because on the iPad pro you can't resize the browser.
Note that I added a query for mobile CSS that I use for devices with less than 900px width; feel free to remove it if needed.
This is the query, it combines both landscape and portrait, it works for the 12.9" and if you need to target the 10.5" you can simply add the queries for these dimensions:
@media only screen and (max-width: 900px),
(height: 1024px) and (width: 1366px) and (-webkit-min-device-pixel-ratio: 1.5) and (orientation: landscape),
(width: 1024px) and (height: 1366px) and (-webkit-min-device-pixel-ratio: 1.5) and (orientation: portrait) {
// insert mobile and iPad Pro 12.9" CSS here
}
iPhone - Grand Central Dispatch main thread
Dispatching blocks to the main queue from the main thread can be useful. It gives the main queue a chance to handle other blocks that have been queued so that you're not simply blocking everything else from executing.
For example you could write an essentially single threaded server that nonetheless handles many concurrent connections. As long as no individual block in the queue takes too long the server stays responsive to new requests.
If your program does nothing but spend its whole life responding to events then this can be quite natural. You just set up your event handlers to run on the main queue and then call dispatch_main(), and you may not need to worry about thread safety at all.
Java getHours(), getMinutes() and getSeconds()
For a time difference, note that the calendar starts at 01.01.1970, 01:00, not at 00:00. If you're using java.util.Date and java.text.SimpleDateFormat, you will have to compensate for 1 hour:
long start = System.currentTimeMillis();
long end = start + (1*3600 + 23*60 + 45) * 1000 + 678; // 1 h 23 min 45.678 s
Date timeDiff = new Date(end - start - 3600000); // compensate for 1h in millis
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.SSS");
System.out.println("Duration: " + timeFormat.format(timeDiff));
This will print:
Duration: 1:23:45.678
Check if string is in a pandas dataframe
You should use any()
In [98]: a['Names'].str.contains('Mel').any()
Out[98]: True
In [99]: if a['Names'].str.contains('Mel').any():
....: print "Mel is there"
....:
Mel is there
a['Names'].str.contains('Mel')
gives you a series of bool values
In [100]: a['Names'].str.contains('Mel')
Out[100]:
0 False
1 False
2 False
3 False
4 True
Name: Names, dtype: bool
Generate random numbers uniformly over an entire range
Why rand
is a bad idea
Most of the answers you got here make use of the rand
function and the modulus operator. That method may not generate numbers uniformly (it depends on the range and the value of RAND_MAX
), and is therefore discouraged.
C++11 and generation over a range
With C++11 multiple other options have risen. One of which fits your requirements, for generating a random number in a range, pretty nicely: std::uniform_int_distribution
. Here's an example:
const int range_from = 0;
const int range_to = 10;
std::random_device rand_dev;
std::mt19937 generator(rand_dev());
std::uniform_int_distribution<int> distr(range_from, range_to);
std::cout << distr(generator) << '\n';
And here's the running example.
Template function may help some:
template<typename T>
T random(T range_from, T range_to) {
std::random_device rand_dev;
std::mt19937 generator(rand_dev());
std::uniform_int_distribution<T> distr(range_from, range_to);
return distr(generator);
}
Other random generators
The <random>
header offers innumerable other random number generators with different kind of distributions including Bernoulli, Poisson and normal.
How can I shuffle a container?
The standard provides std::shuffle
, which can be used as follows:
std::vector<int> vec = {4, 8, 15, 16, 23, 42};
std::random_device random_dev;
std::mt19937 generator(random_dev());
std::shuffle(vec.begin(), vec.end(), generator);
The algorithm will reorder the elements randomly, with a linear complexity.
Boost.Random
Another alternative, in case you don't have access to a C++11+ compiler, is to use Boost.Random. Its interface is very similar to the C++11 one.
How to place div side by side
If you're not tagetting IE6, then float the second <div>
and give it a margin equal to (or maybe a little bigger than) the first <div>
's fixed width.
HTML:
<div id="main-wrapper">
<div id="fixed-width"> lorem ipsum </div>
<div id="rest-of-space"> dolor sit amet </div>
</div>
CSS:
#main-wrapper {
100%;
background:red;
}
#fixed-width {
width:100px;
float:left
}
#rest-of-space {
margin-left:101px;
/* May have to increase depending on borders and margin of the fixd width div*/
background:blue;
}
The margin accounts for the possibility that the 'rest-of-space' <div>
may contain more content than the 'fixed-width' <div>
.
Don't give the fixed width one a background; if you need to visibly see these as different 'columns' then use the Faux Columns trick.
How to Get a Sublist in C#
Use the Where clause from LINQ:
List<object> x = new List<object>();
x.Add("A");
x.Add("B");
x.Add("C");
x.Add("D");
x.Add("B");
var z = x.Where(p => p == "A");
z = x.Where(p => p == "B");
In the statements above "p" is the object that is in the list. So if you used a data object, i.e.:
public class Client
{
public string Name { get; set; }
}
then your linq would look like this:
List<Client> x = new List<Client>();
x.Add(new Client() { Name = "A" });
x.Add(new Client() { Name = "B" });
x.Add(new Client() { Name = "C" });
x.Add(new Client() { Name = "D" });
x.Add(new Client() { Name = "B" });
var z = x.Where(p => p.Name == "A");
z = x.Where(p => p.Name == "B");
How to specify line breaks in a multi-line flexbox layout?
I tried several answers here, and none of them worked. Ironically, what did work was about the simplest alternative to a <br/>
one could attempt:
<div style="flex-basis: 100%;"></div>
or you could also do:
<div style="width: 100%;"></div>
Place that wherever you want a new line. It seems to work even with adjacent <span>
's, but I'm using it with adjacent <div>
's.
Comparing Dates in Oracle SQL
You can use trunc and to_date as follows:
select TO_CHAR (g.FECHA, 'DD-MM-YYYY HH24:MI:SS') fecha_salida, g.NUMERO_GUIA, g.BOD_ORIGEN, g.TIPO_GUIA, dg.DOC_NUMERO, dg.*
from ils_det_guia dg, ils_guia g
where dg.NUMERO_GUIA = g.NUMERO_GUIA and dg.TIPO_GUIA = g.TIPO_GUIA and dg.BOD_ORIGEN = g.BOD_ORIGEN
and dg.LAB_CODIGO = 56
and trunc(g.FECHA) > to_date('01/02/15','DD/MM/YY')
order by g.FECHA;
Adjusting the Xcode iPhone simulator scale and size
You can set any scale you wish. It`s became actual after 6+ simulator been presented
To obtain it follow next easy steps:
- quit simulator if open
- open terminal (from spotlight for example)
- paste next text to terminal and press enter
defaults write ~/Library/Preferences/com.apple.iphonesimulator SimulatorWindowLastScale "0.4"
You can try any scales changing 0.4 to desired value.
To reset this custom scale, just apply any standard scale from simulator menu in way described above.
Static linking vs dynamic linking
static linking gives you only a single exe, inorder to make a change you need to recompile your whole program. Whereas in dynamic linking you need to make change only to the dll and when you run your exe, the changes would be picked up at runtime.Its easier to provide updates and bug fixes by dynamic linking (eg: windows).
OnClick vs OnClientClick for an asp:CheckBox?
You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.
In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".
$(document).ready(function () {
$('input[type=checkbox]').click(function(){
var areYouSure = confirm('Are you sure you want make this change?');
if (areYouSure) {
$(this).prop('checked', this.checked);
} else {
$(this).prop('checked', !this.checked);
}
});
});
<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />
protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
using (myDataContext db = new myDataDataContext())
{
CheckBox chk = (CheckBox)sender;
RepeaterItem row = (RepeaterItem) chk.NamingContainer;
var studentID = ((Label) row.FindControl("lblID")).Text;
var z = (from b in db.StudentApplicants
where b.StudentID == studentID
select b).FirstOrDefault();
if(chk != null && chk.Checked != z.FinancialAid){
z.FinancialAid = chk.Checked;
z.ModifiedDate = DateTime.Now;
db.SubmitChanges();
BindGrid();
}
gvData.DataBind();
}
}
Capturing Groups From a Grep RegEx
If you're using Bash, you don't even have to use grep
:
files="*.jpg"
regex="[0-9]+_([a-z]+)_[0-9a-z]*"
for f in $files # unquoted in order to allow the glob to expand
do
if [[ $f =~ $regex ]]
then
name="${BASH_REMATCH[1]}"
echo "${name}.jpg" # concatenate strings
name="${name}.jpg" # same thing stored in a variable
else
echo "$f doesn't match" >&2 # this could get noisy if there are a lot of non-matching files
fi
done
It's better to put the regex in a variable. Some patterns won't work if included literally.
This uses =~
which is Bash's regex match operator. The results of the match are saved to an array called $BASH_REMATCH
. The first capture group is stored in index 1, the second (if any) in index 2, etc. Index zero is the full match.
You should be aware that without anchors, this regex (and the one using grep
) will match any of the following examples and more, which may not be what you're looking for:
123_abc_d4e5
xyz123_abc_d4e5
123_abc_d4e5.xyz
xyz123_abc_d4e5.xyz
To eliminate the second and fourth examples, make your regex like this:
^[0-9]+_([a-z]+)_[0-9a-z]*
which says the string must start with one or more digits. The carat represents the beginning of the string. If you add a dollar sign at the end of the regex, like this:
^[0-9]+_([a-z]+)_[0-9a-z]*$
then the third example will also be eliminated since the dot is not among the characters in the regex and the dollar sign represents the end of the string. Note that the fourth example fails this match as well.
If you have GNU grep
(around 2.5 or later, I think, when the \K
operator was added):
name=$(echo "$f" | grep -Po '(?i)[0-9]+_\K[a-z]+(?=_[0-9a-z]*)').jpg
The \K
operator (variable-length look-behind) causes the preceding pattern to match, but doesn't include the match in the result. The fixed-length equivalent is (?<=)
- the pattern would be included before the closing parenthesis. You must use \K
if quantifiers may match strings of different lengths (e.g. +
, *
, {2,4}
).
The (?=)
operator matches fixed or variable-length patterns and is called "look-ahead". It also does not include the matched string in the result.
In order to make the match case-insensitive, the (?i)
operator is used. It affects the patterns that follow it so its position is significant.
The regex might need to be adjusted depending on whether there are other characters in the filename. You'll note that in this case, I show an example of concatenating a string at the same time that the substring is captured.
How to install plugins to Sublime Text 2 editor?
According to John Day's answer
You should have a Data/Packages folder in your Sublime Text 2 install directory. All you need to do is download the plugin and put the plugin folder in the Packages folder.
In case if you are searching for Data/Packages folder you can find it here
Windows: %APPDATA%\Sublime Text 2
OS X: ~/Library/Application Support/Sublime Text 2
Linux: ~/.Sublime Text 2
Portable Installation: Sublime Text 2/Data
How To Raise Property Changed events on a Dependency Property?
I ran into a similar problem where I have a dependency property that I wanted the class to listen to change events to grab related data from a service.
public static readonly DependencyProperty CustomerProperty =
DependencyProperty.Register("Customer", typeof(Customer),
typeof(CustomerDetailView),
new PropertyMetadata(OnCustomerChangedCallBack));
public Customer Customer {
get { return (Customer)GetValue(CustomerProperty); }
set { SetValue(CustomerProperty, value); }
}
private static void OnCustomerChangedCallBack(
DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
CustomerDetailView c = sender as CustomerDetailView;
if (c != null) {
c.OnCustomerChanged();
}
}
protected virtual void OnCustomerChanged() {
// Grab related data.
// Raises INotifyPropertyChanged.PropertyChanged
OnPropertyChanged("Customer");
}
How to edit the size of the submit button on a form?
Using CSS.
Either inside your <head>
tag (the #search
means "the element with an ID of search
")
<style type="text/css">
input#search
{
width: 20px;
height: 20px;
}
</style>
Or inline, in your <input>
tag
<input type="submit" id="search" value="Search" style="width: 20px; height: 20px;" />
Angular 5 Service to read local .json file
Let’s create a JSON file, we name it navbar.json you can name it whatever you want!
navbar.json
[
{
"href": "#",
"text": "Home",
"icon": ""
},
{
"href": "#",
"text": "Bundles",
"icon": "",
"children": [
{
"href": "#national",
"text": "National",
"icon": "assets/images/national.svg"
}
]
}
]
Now we’ve created a JSON file with some menu data. We’ll go to app component file and paste the below code.
app.component.ts
import { Component } from '@angular/core';
import menudata from './navbar.json';
@Component({
selector: 'lm-navbar',
templateUrl: './navbar.component.html'
})
export class NavbarComponent {
mainmenu:any = menudata;
}
Now your Angular 7 app is ready to serve the data from the local JSON file.
Go to app.component.html and paste the following code in it.
app.component.html
<ul class="navbar-nav ml-auto">
<li class="nav-item" *ngFor="let menu of mainmenu">
<a class="nav-link" href="{{menu.href}}">{{menu.icon}} {{menu.text}}</a>
<ul class="sub_menu" *ngIf="menu.children && menu.children.length > 0">
<li *ngFor="let sub_menu of menu.children"><a class="nav-link" href="{{sub_menu.href}}"><img src="{{sub_menu.icon}}" class="nav-img" /> {{sub_menu.text}}</a></li>
</ul>
</li>
</ul>
css h1 - only as wide as the text
align-self-start, align-self-center... in flexbox
.centercol h1{
background: #F2EFE9;
border-left: 3px solid #C6C1B8;
color: #006BB6;
display: block;
align-self: center;
font-weight: normal;
font-size: 18px;
padding: 3px 3px 3px 6px;
}
Iterating through a List Object in JSP
<c:forEach items="${sessionScope.empL}" var="emp">
<tr>
<td>Employee ID: <c:out value="${emp.eid}"/></td>
<td>Employee Pass: <c:out value="${emp.ename}"/></td>
</tr>
</c:forEach>
jquery how to catch enter key and change event to tab
Includes all types of inputs
$(':input').keydown(function (e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if (key == 13) {
e.preventDefault();
var inputs = $(this).closest('form').find(':input:visible:enabled');
if ((inputs.length-1) == inputs.index(this))
$(':input:enabled:visible:first').focus();
else
inputs.eq(inputs.index(this) + 1).focus();
}
});
Stopping fixed position scrolling at a certain point?
Here's a quick jQuery plugin I just wrote that can do what you require:
$.fn.followTo = function (pos) {
var $this = this,
$window = $(window);
$window.scroll(function (e) {
if ($window.scrollTop() > pos) {
$this.css({
position: 'absolute',
top: pos
});
} else {
$this.css({
position: 'fixed',
top: 0
});
}
});
};
$('#yourDiv').followTo(250);
See working example →
How to set tint for an image view programmatically in android?
As the first answer didn't work for me:
//get ImageView
ImageView myImageView = (ImageView) findViewById(R.id.iv);
//colorid is the id of a color defined in values/colors.xml
myImageView.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(getApplicationContext(), R.color.colorid)));
This only seems to work in API 21+, but for me that wasn't an issue. You can use an ImageViewCompat to resolve that issue, tho.
I hope I helped anyone out :-)
What is the difference between NULL, '\0' and 0?
A byte with a value of 0x00
is, on the ASCII table, the special character called NUL
or NULL
. In C, since you shouldn't embed control characters in your source code, this is represented in C strings with an escaped 0, i.e., \0
.
But a true NULL is not a value. It is the absence of a value. For a pointer, it means the pointer has nothing to point to. In a database, it means there is no value in a field (which is not the same thing as saying the field is blank, 0, or filled with spaces).
The actual value a given system or database file format uses to represent a NULL
isn't necessarily 0x00
.
How to convert characters to HTML entities using plain JavaScript
Using escape() should work with the character code range 0x00 to 0xFF (UTF-8 range).
If you go beyond 0xFF (255), such as 0x100 (256) then escape() will not work:
escape("\u0100"); // %u0100
and:
text = "\u0100"; // A
html = escape(text).replace(/%(..)/g,"&#x$1;"); // &#xu0;100
So, if you want to cover all Unicode charachacters as defined on http://www.w3.org/TR/html4/sgml/entities.html , then you could use something like:
var html = text.replace(/[\u00A0-\u00FF]/g, function(c) {
return '&#'+c.charCodeAt(0)+';';
});
Note here the range is between: \u00A0-\u00FF.
Thats the first character code range defined in http://www.w3.org/TR/html4/sgml/entities.html which is the same as what escape() covers.
You'll need to add the other ranges you want to cover as well, or all of them.
Example: UTF-8 range with general punctuations (\u00A0-\u00FF and \u2022-\u2135)
var html = text.replace(/[\u00A0-\u00FF\u2022-\u2135]/g, function(c) {
return '&#'+c.charCodeAt(0)+';';
});
Edit:
BTW: \u00A0-\u2666 should convert every Unicode character code not within ASCII range to HTML entities blindly:
var html = text.replace(/[\u00A0-\u2666]/g, function(c) {
return '&#'+c.charCodeAt(0)+';';
});
Ruby array to string conversion
suppose your array :
arr=["1","2","3","4"]
Method to convert array to string:
Array_name.join(",")
Example:
arr.join(",")
Result:
"'1','2','3','4'"
Can .NET load and parse a properties file equivalent to Java Properties class?
Yeah there's no built in classes to do this that I'm aware of.
But that shouldn't really be an issue should it? It looks easy enough to parse just by storing the result of Stream.ReadToEnd()
in a string, splitting based on new lines and then splitting each record on the =
character. What you'd be left with is a bunch of key value pairs which you can easily toss into a dictionary.
Here's an example that might work for you:
public static Dictionary<string, string> GetProperties(string path)
{
string fileData = "";
using (StreamReader sr = new StreamReader(path))
{
fileData = sr.ReadToEnd().Replace("\r", "");
}
Dictionary<string, string> Properties = new Dictionary<string, string>();
string[] kvp;
string[] records = fileData.Split("\n".ToCharArray());
foreach (string record in records)
{
kvp = record.Split("=".ToCharArray());
Properties.Add(kvp[0], kvp[1]);
}
return Properties;
}
Here's an example of how to use it:
Dictionary<string,string> Properties = GetProperties("data.txt");
Console.WriteLine("Hello: " + Properties["Hello"]);
Console.ReadKey();
Flushing buffers in C
Flushing the output buffers:
printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is
or
fprintf(fd, "Buffered, will be flushed");
fflush(fd); //Prints to a file
Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf()
it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf
something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.
Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf()
, so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.
I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf()
is an expensive operation (which is why it doesn't by default flush the buffer).
As far as flushing the input buffer (stdin
), you should not do that. Flushing stdin
is undefined behavior according to the C11 standard §7.21.5.2 part 2:
If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.
On some systems, Linux being one as you can see in the man page for fflush()
, there's a defined behavior but it's system dependent so your code will not be portable.
Now if you're worried about garbage "stuck" in the input buffer you can use fpurge()
on that.
See here for more on fflush()
and fpurge()
Select a Dictionary<T1, T2> with LINQ
The extensions methods also provide a ToDictionary extension. It is fairly simple to use, the general usage is passing a lambda selector for the key and getting the object as the value, but you can pass a lambda selector for both key and value.
class SomeObject
{
public int ID { get; set; }
public string Name { get; set; }
}
SomeObject[] objects = new SomeObject[]
{
new SomeObject { ID = 1, Name = "Hello" },
new SomeObject { ID = 2, Name = "World" }
};
Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);
Then objectDictionary[1]
Would contain the value "Hello"
How to bind 'touchstart' and 'click' events but not respond to both?
This is the fix that I "create" and it take out the GhostClick and implements the FastClick. Try on your own and let us know if it worked for you.
$(document).on('touchstart click', '.myBtn', function(event){
if(event.handled === false) return
event.stopPropagation();
event.preventDefault();
event.handled = true;
// Do your magic here
});
How can I convert this foreach code to Parallel.ForEach?
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
// No need for the list
// List<string> list_lines = new List<string>(lines);
Parallel.ForEach(lines, line =>
{
//My Stuff
});
This will cause the lines to be parsed in parallel, within the loop. If you want a more detailed, less "reference oriented" introduction to the Parallel class, I wrote a series on the TPL which includes a section on Parallel.ForEach.
checked = "checked" vs checked = true
checked
attribute is a boolean value so "checked"
value of other "string"
except boolean false
converts to true
.
Any string value will be true. Also presence of attribute make it true:
<input type="checkbox" checked>
You can make it uncheked only making boolean change in DOM using JS.
So the answer is: they are equal.
w3c
Can you do a For Each Row loop using MySQL?
In the link you provided, thats not a loop in sql...
thats a loop in programming language
they are first getting list of all distinct districts, and then for each district executing query again.
how to set radio button checked in edit mode in MVC razor view
Here is the code for get value of checked radio button and set radio button checked according to it's value in edit form:
Controller:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
CommonServiceReference.tbl_user user = new CommonServiceReference.tbl_user();
user.user_gender = collection["rdbtnGender"];
return RedirectToAction("Index");
}
catch(Exception e)
{
throw e;
}
}
public ActionResult Edit(int id)
{
CommonServiceReference.ViewUserGroup user = clientObj.getUserById(id);
ViewBag.UserObj = user;
return View();
}
VIEW:
Create:
<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" required>
<label for="rdbtnGender2">FEMALE</label>
Edit:
<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" @(ViewBag.UserObj.user_gender == "Male" ? "checked='true'" : "") required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" @(ViewBag.UserObj.user_gender == "Female" ? "checked='true'" : "") required>
<label for="rdbtnGender2">FEMALE</label>
Copy output of a JavaScript variable to the clipboard
For general purposes of copying any text to the clipboard, I wrote the following function:
function textToClipboard (text) {
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
The value of the parameter is inserted into value of a newly created <textarea>
, which is then selected, its value is copied to the clipboard and then it gets removed from the document.
Splitting a C++ std::string using tokens, e.g. ";"
I find std::getline()
is often the simplest. The optional delimiter parameter means it's not just for reading "lines":
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> strings;
istringstream f("denmark;sweden;india;us");
string s;
while (getline(f, s, ';')) {
cout << s << endl;
strings.push_back(s);
}
}
iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"
It comes from +[UIWindow _synchronizeDrawingAcrossProcessesOverPort:withPreCommitHandler:]
via os_log API. It doesn't depend from another components/frameworks that you are using(only from UIKit) - it reproduces in clean single view application project on changing interface orientation.
This method consists from 2 parts:
- adding passed precommit handler to list of handlers;
- do some work, that depends on current finite state machine state.
When second part fails (looks like prohibited transition), it prints message above to error log.
However, I think that this problem is not fatal: there are 2 additional assert cases in this method, that will lead to crash in debug.
Seems that radar is the best we can do.
Android Studio Gradle Already disposed Module
In my case, same as in this question, it happened becayse I had my project in a symbolic link directory. After reopening the project in the real directory and reconfiguring gradle (File -> Sync with Gradle files
) the problem went away. Shame on you, Android Studio!
How to call code behind server method from a client side JavaScript function?
JS Code:
<script type="text/javascript">
function ShowCurrentTime(name) {
PageMethods.GetCurrentTime(name, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
</script>
HTML Code:
<asp:ImageButton ID="IMGBTN001" runat="server" ImageUrl="Images/ico/labaniat.png"
class="img-responsive em-img-lazy" OnClientClick="ShowCurrentTime('01')" />
Code Behind C#
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
How to remove youtube branding after embedding video in web page?
That watermark in the bottom right only appears on mouseover
. There's no parameter to remove that, however if you stack a transparent div
on top of the video and make it a higher z-index
and the same size of the video, your mouseover
will not trigger the watermark because your mouse will be hitting the div
.
Of course the tradeoff for this is that you lose the ability to actually click on the video to pause it. But if you want to leave the ability to pause it, you could display the controls and have the top layer div
cover up until the bottom 30 pixels or so, letting you click the controls.
Get the filePath from Filename using Java
I'm not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:
System.out.println("File path: " + new File("Your file name").getAbsolutePath());
The File class has several more methods you might find useful.
Get Context in a Service
Since Service
is a Context
, the variable context must be this
:
DataBaseManager dbm = Utils.getDataManager(this);
Get user's non-truncated Active Directory groups from command line
Or you could use dsquery and dsget:
dsquery user domainroot -name <userName> | dsget user -memberof
To retrieve group memberships something like this:
Tue 09/10/2013 13:17:41.65
C:\
>dsquery user domainroot -name jqpublic | dsget user -memberof
"CN=Technical Support Staff,OU=Acme,OU=Applications,DC=YourCompany,DC=com"
"CN=Technical Support Staff,OU=Contosa,OU=Applications,DC=YourCompany,DC=com"
"CN=Regional Administrators,OU=Workstation,DC=YourCompany,DC=com"
Although I can't find any evidence that I ever installed this package on my computer, you might need to install the Remote Server Administration Tools for Windows 7.
How do you query for "is not null" in Mongo?
Thanks for providing a solution, I noticed in MQL, sometimes $ne:null doesn't work instead we need to use syntax $ne:"" i.e. in the context of above example we would need to use db.mycollection.find({"IMAGE URL":{"$ne":""}}) - Not sure why this occurs, I have posted this question in the MongoDB forum.
following is the snapshot showing example:
enter image description here