I had a similar problem and for encrypt/decrypt i came up with this solution:
public static byte[] generateKey(String password) throws Exception
{
byte[] keyStart = password.getBytes("UTF-8");
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
sr.setSeed(keyStart);
kgen.init(128, sr);
SecretKey skey = kgen.generateKey();
return skey.getEncoded();
}
public static byte[] encodeFile(byte[] key, byte[] fileData) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(fileData);
return encrypted;
}
public static byte[] decodeFile(byte[] key, byte[] fileData) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(fileData);
return decrypted;
}
To save a encrypted file to sd do:
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "your_folder_on_sd", "file_name");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] yourKey = generateKey("password");
byte[] filesBytes = encodeFile(yourKey, yourByteArrayContainigDataToEncrypt);
bos.write(fileBytes);
bos.flush();
bos.close();
To decode a file use:
byte[] yourKey = generateKey("password");
byte[] decodedData = decodeFile(yourKey, bytesOfYourFile);
For reading in a file to a byte Array there a different way out there. A Example: http://examples.javacodegeeks.com/core-java/io/fileinputstream/read-file-in-byte-array-with-fileinputstream/
DavidLn's answer has worked well for me in the past. But it doesn't capture all of setPristine's functionality, which tripped me up this time. Here is a fuller shim:
var form_set_pristine = function(form){
// 2013-12-20 DF TODO: remove this function on Angular 1.1.x+ upgrade
// function is included natively
if(form.$setPristine){
form.$setPristine();
} else {
form.$pristine = true;
form.$dirty = false;
angular.forEach(form, function (input, key) {
if (input.$pristine)
input.$pristine = true;
if (input.$dirty) {
input.$dirty = false;
}
});
}
};
Unfortunately MySQL does not support SQL check constraints. You can define them in your DDL query for compatibility reasons but they are just ignored.
There is a simple alternative
You can create BEFORE INSERT
and BEFORE UPDATE
triggers which either cause an error or set the field to its default value when the requirements of the data are not met.
Example for BEFORE INSERT
working after MySQL 5.5
DELIMITER $$
CREATE TRIGGER `test_before_insert` BEFORE INSERT ON `Test`
FOR EACH ROW
BEGIN
IF CHAR_LENGTH( NEW.ID ) < 4 THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT := 'check constraint on Test.ID failed';
END IF;
END$$
DELIMITER ;
Prior to MySQL 5.5 you had to cause an error, e.g. call a undefined procedure.
In both cases this causes an implicit transaction rollback. MySQL does not allow the ROLLBACK statement itself within procedures and triggers.
If you don't want to rollback the transaction ( INSERT / UPDATE should pass even with a failed "check constraint" you can overwrite the value using SET NEW.ID = NULL
which will set the id to the fields default value, doesn't really make sense for an id tho
Edit: Removed the stray quote.
Concerning the :=
operator:
Unlike
=
, the:=
operator is never interpreted as a comparison operator. This means you can use:=
in any valid SQL statement (not just in SET statements) to assign a value to a variable.
https://dev.mysql.com/doc/refman/5.6/en/assignment-operators.html
Concerning backtick identifier quotes:
The identifier quote character is the backtick (“`”)
If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks
Follow the below steps
From feature/branch (enter the below command)
git checkout master
git pull
git checkout feature/branchname
git merge master
Just an example: I want to run runio.py from within helper1.py
Project tree example:
myproject_root
- modules_dir/helpers_dir/helper1.py
- tools_dir/runio.py
Get project root:
import os
rootdir = os.path.dirname(os.path.realpath(__file__)).rsplit(os.sep, 2)[0]
Build path to script:
runme = os.path.join(rootdir, "tools_dir", "runio.py")
execfile(runme)
unset
is not actually a function, but a language construct. It is no more a function call than a return
or an include
.
Aside from performance issues, using unset
makes your code's intent much clearer.
Expanding on Xin's answer and assuming the comparison value type is INT, this approach works too:
SELECT IIF(ISNULL(@A, -2147483648) > ISNULL(@B, -2147483648), @A, @B)
This is a full test with example values:
DECLARE @A AS INT
DECLARE @B AS INT
SELECT @A = 2, @B = 1
SELECT IIF(ISNULL(@A, -2147483648) > ISNULL(@B, -2147483648), @A, @B)
-- 2
SELECT @A = 2, @B = 3
SELECT IIF(ISNULL(@A, -2147483648) > ISNULL(@B, -2147483648), @A, @B)
-- 3
SELECT @A = 2, @B = NULL
SELECT IIF(ISNULL(@A, -2147483648) > ISNULL(@B, -2147483648), @A, @B)
-- 2
SELECT @A = NULL, @B = 1
SELECT IIF(ISNULL(@A, -2147483648) > ISNULL(@B, -2147483648), @A, @B)
-- 1
SyntaxError: missing ) after argument list.
the issue also may occur if you pass string directly without a single or double quote.
$('#contentData').append("<div class='media'><div class='media-body'><a class='btn' href='" + type + "' onclick=\"(canLaunch(' + v.LibraryItemName + '))\">View »</a></div></div>").
so always keep the habit to pass in a quote like
onclick=\"(canLaunch(\'' + v.LibraryItemName + '\'))"\
For Visual Studio Users, On Package Manager console:
git branch | %{ git fetch upstream; git merge upstream/master}
Try to use the func below to add colorbar:
def add_colorbar(mappable):
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt
last_axes = plt.gca()
ax = mappable.axes
fig = ax.figure
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cbar = fig.colorbar(mappable, cax=cax)
plt.sca(last_axes)
return cbar
Then you codes need to be modified as:
fig , ( (ax1,ax2) , (ax3,ax4)) = plt.subplots(2, 2,sharex = True,sharey=True)
z1_plot = ax1.scatter(x,y,c = z1,vmin=0.0,vmax=0.4)
add_colorbar(z1_plot)
I run into the same problem and none of the suggestions worked (Firefox on Windows XP).
So I found a possible workaround using image data to display a little checkmark:
span:before {
content:url("data:image/gif;base64,R0lGODlhCgAKAJEAAAAAAP///////wAAACH5BAEAAAIALAAAAAAKAAoAAAISlG8AeMq5nnsiSlsjzmpzmj0FADs=");
}
Of course you can create your own checkmark image and use a converter to add it as data:image/gif. Hope this helps.
I tried several variations of the answers here. No matter what I try, I can always find a use case where the user is prompted to close Terminal.
Since my script is a simple (drutil -drive 2 tray open
-- to open a specific DVD drive), the user does not need to see the Terminal window while the script runs.
My solution was to turn the script into an app, which runs the script without displaying a Terminal window. The added benefit is that any terminal windows that are already open stay open, and if none are open, then Terminal doesn't stay resident after the script ends. It doesn't seem to launch Terminal at all to run the bash script.
I followed these instructions to turn my script into an app: https://superuser.com/a/1354541/162011
I've looked at the source code for WebView
and I concluded that there is no elegant way to accomplish what you are asking.
What I ended up doing was subclassing WebView
and overriding OnTouchEvent
.
In OnTouchEvent
for ACTION_DOWN
, I check how many pointers there are using MotionEvent.getPointerCount()
.
If there is more than one pointer, I call setSupportZoom(true)
, otherwise I call setSupportZoom(false)
. I then call the super.OnTouchEvent().
This will effectively disable zooming when scrolling (thus disabling the zoom controls) and enable zooming when the user is about to pinch zoom. Not a nice way of doing it, but it has worked well for me so far.
Note that getPointerCount()
was introduced in 2.1 so you'll have to do some extra stuff if you support 1.6.
When parsing its configuration file, the expression ${MY_HOME}
will be expanded to the value of the system property named MY_HOME
, not the system environment variable. There's a difference between the two.
To achieve this in a clean way, you'll have to add something like this to the JVM invocation line:
-DMY_HOME=$MY_HOME
That would define the Java system property MY_HOME
to contain the value of the environment variable MY_HOME
.
I had the same Issue. my solution was built up from two projects. A Class library
and a website referencing to the class library project. the problem was that i was trying to access the App.config
in my Class library
project but the system was searching in Web.config
of the website. I put the connection string inside Web.config
and ... problem solved!
The main reason was that despite ConfigurationManager
was used in another assembly it was searching inside the runnig project .
the aim of balanced tree is to reach the leaf in a minimum of traversal (min height). The degree of the tree is the number of branches minus 1. A Balanced tree may be not Binary.
Inspired by VB.Net Generics List(Of Integer), I created my own module for that. Maybe you find it useful, too or you'd like to extend for additional methods e.g. to remove items again:
'Save module with name: ListOfInteger
Public Function ListLength(list() As Integer) As Integer
On Error Resume Next
ListLength = UBound(list) + 1
On Error GoTo 0
End Function
Public Sub ListAdd(list() As Integer, newValue As Integer)
ReDim Preserve list(ListLength(list))
list(UBound(list)) = newValue
End Sub
Public Function ListContains(list() As Integer, value As Integer) As Boolean
ListContains = False
Dim MyCounter As Integer
For MyCounter = 0 To ListLength(list) - 1
If list(MyCounter) = value Then
ListContains = True
Exit For
End If
Next
End Function
Public Sub DebugOutputList(list() As Integer)
Dim MyCounter As Integer
For MyCounter = 0 To ListLength(list) - 1
Debug.Print list(MyCounter)
Next
End Sub
You might use it as follows in your code:
Public Sub IntegerListDemo_RowsOfAllSelectedCells()
Dim rows() As Integer
Set SelectedCellRange = Excel.Selection
For Each MyCell In SelectedCellRange
If IsEmpty(MyCell.value) = False Then
If ListOfInteger.ListContains(rows, MyCell.Row) = False Then
ListAdd rows, MyCell.Row
End If
End If
Next
ListOfInteger.DebugOutputList rows
End Sub
If you need another list type, just copy the module, save it at e.g. ListOfLong and replace all types Integer by Long. That's it :-)
While it can be annoying when used as an anti-piracy measure, I can see there might be some instances where it'd be legitimate, so:
function disableCopyPaste(elm) {
// Disable cut/copy/paste key events
elm.onkeydown = interceptKeys
// Disable right click events
elm.oncontextmenu = function() {
return false
}
}
function interceptKeys(evt) {
evt = evt||window.event // IE support
var c = evt.keyCode
var ctrlDown = evt.ctrlKey||evt.metaKey // Mac support
// Check for Alt+Gr (http://en.wikipedia.org/wiki/AltGr_key)
if (ctrlDown && evt.altKey) return true
// Check for ctrl+c, v and x
else if (ctrlDown && c==67) return false // c
else if (ctrlDown && c==86) return false // v
else if (ctrlDown && c==88) return false // x
// Otherwise allow
return true
}
I've used event.ctrlKey
rather than checking for the key code as on most browsers on Mac OS X Ctrl/Alt "down" and "up" events are never triggered, so the only way to detect is to use event.ctrlKey
in the e.g. c event after the Ctrl key is held down. I've also substituted ctrlKey
with metaKey
for macs.
Limitations of this method:
edit
->copy
menu item in e.g. Firefox can still allow copy/pasting.for me @"^[\w ]+$" is working, allow number, alphabet and space, but need to type at least one letter or number.
URL url = Test.class.getResource(args[0]); // reading demo file path from
// same location where class
File input=null;
try {
input = new File(url.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I tried with the correct answer by @Lahiru, but did not work with MySQL server version 8.0.16 (Community) on macOS Mojave.
Followed the instructions by Sameer Choudhary above and with some adjustments, I was able to change root password and enable root access from localhost.
Update: All of these are not required, if you are installing on Mac OS using homebrew: "brew install mysql"
I prefer use a function this way.
DELIMITER $$ DROP FUNCTION IF EXISTS `db`.`F_AGE` $$
CREATE FUNCTION `F_AGE`(in_dob datetime) RETURNS int(11)
NO SQL
BEGIN
DECLARE l_age INT;
IF DATE_FORMAT(NOW( ),'00-%m-%d') >= DATE_FORMAT(in_dob,'00-%m-%d') THEN
-- This person has had a birthday this year
SET l_age=DATE_FORMAT(NOW( ),'%Y')-DATE_FORMAT(in_dob,'%Y');
ELSE
-- Yet to have a birthday this year
SET l_age=DATE_FORMAT(NOW( ),'%Y')-DATE_FORMAT(in_dob,'%Y')-1;
END IF;
RETURN(l_age);
END $$
DELIMITER ;
now to use
SELECT F_AGE('1979-02-11') AS AGE;
OR
SELECT F_AGE(date) AS age FROM table;
No, it is better practice to leave them out.
Without strip(), you can have empty keys and values:
apples<tab>round, fruity things
oranges<tab>round, fruity things
bananas<tab>
Without strip(), bananas is present in the dictionary but with an empty string as value. With strip(), this code will throw an exception because it strips the tab of the banana line.
Here is a more generic solution for any given weekday. Working demo on jsfiddle
var myIsoWeekDay = 2; // say our weeks start on tuesday, for monday you would type 1, etc.
var startOfPeriod = moment("2013-06-23T00:00:00"),
// how many days do we have to substract?
var daysToSubtract = moment(startOfPeriod).isoWeekday() >= myIsoWeekDay ?
moment(startOfPeriod).isoWeekday() - myIsoWeekDay :
7 + moment(startOfPeriod).isoWeekday() - myIsoWeekDay;
// subtract days from start of period
var begin = moment(startOfPeriod).subtract('d', daysToSubtract);
As I know, there is no direct support, but you can use plain-ol' javascript for that:
// Cookies
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
The following is a sample code to pass values from one page to another using html. Here the data from page1 is passed to page2 and it's retrieved by using javascript.
1) page1.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 1 - Codemaker</title>
</head>
<body>
<form method="get" action="page2.html">
<table>
<tr>
<td>First Name:</td>
<td><input type=text name=firstname size=10></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type=text name=lastname size=10></td>
</tr>
<tr>
<td>Age:</td>
<td><input type=text name=age size=10></td>
</tr>
<tr>
<td colspan=2><input type=submit value="Submit">
</td>
</tr>
</table>
</form>
</body>
</html>
2) page2.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 2 - Codemaker</title>
</head>
<body>
<script>
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
document.write("firstname = " + firstname + "<br>");
document.write("lastname = " + lastname + "<br>");
document.write("age = " + age + "<br>");
</script>
</body>
</html>
@NathanClement was a bit faster. Yet, here is the complete code (slightly more elaborate):
Option Explicit
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Set shtToExport = ThisWorkbook.Worksheets("Sheet1") 'Sheet to export as CSV
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False 'Possibly overwrite without asking
wbkExport.SaveAs Filename:="C:\tmp\test.csv", FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
End Sub
I'd suggest 3 things in the beginning of your script:
First, as already being said use environment:
#!/usr/bin/env python
Second, set your encoding:
# -*- coding: utf-8 -*-
Third, set some doc string:
"""This is a awesome
python script!"""
And for sure I would use " "
(4 spaces) for ident.
Final header will look like:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a awesome
python script!"""
Best wishes and happy coding.
An example using jQuery is below. Hope this helps
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
JSONTest = function() {
var resultDiv = $("#resultDivContainer");
$.ajax({
url: "https://example.com/api/",
type: "POST",
data: { apiKey: "23462", method: "example", ip: "208.74.35.5" },
dataType: "json",
success: function (result) {
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
};
</script>
</head>
<body>
<h1>My jQuery JSON Web Page</h1>
<div id="resultDivContainer"></div>
<button type="button" onclick="JSONTest()">JSON</button>
</body>
</html>
Firebug debug process
Another reason projects use simplejson is that the builtin json did not originally include its C speedups, so the performance difference was noticeable.
The only real difference between a soft reference and a weak reference is that
the garbage collector uses algorithms to decide whether or not to reclaim a softly reachable object, but always reclaims a weakly reachable object.
I know this is an "older" post. This question and the provided answers helped me get ideas for my own problem. I think this solution addresses the OP question (intersecting borders with 4 and 2 columns depending on display)
Fiddle: https://jsfiddle.net/tqmfpwhv/1/
css based on OP information, media query at end is for med & lg view.
.vr-all {
padding:0px;
border-right:1px solid #CC0000;
}
.vr-xs {
padding:0px;
}
.vr-md {
padding:0px;
}
.hrspacing { padding:0px; }
.hrcolor {
border-color: #CC0000;
border-style: solid;
border-bottom: 1px;
margin:0px;
padding:0px;
}
/* for medium and up */
@media(min-width:992px){
.vr-xs {
border-right:1px solid #CC0000;
}
}
html adjustments to OP provided code. Red border and Img links for example.
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="one">
<h5>Rich Media Ad Production</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" />
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="two">
<h5>Web Design & Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for only x-small/small viewports -->
<div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="three">
<h5>Mobile Apps Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="four">
<h5>Creative Design</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for for all viewports -->
<div class="col-xs-12 hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="five">
<h5>Web Analytics</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="six">
<h5>Search Engine Marketing</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for only x-small/small viewports -->
<div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="seven">
<h5>Mobile Apps Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="eight">
<h5>Quality Assurance</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
</div>
</div>
IBAction and IBOutlets are used to hook up your interface made in Interface Builder with your controller. If you wouldn't use Interface Builder and build your interface completely in code, you could make a program without using them. But in reality most of us use Interface Builder, once you want to get some interactivity going in your interface, you will have to use IBActions and IBoutlets.
If you already have a Desktop environment then I'm sure Gnumeric / LibreOffice would work well, but on a headless server (such as Amazon Web Services), they require dozens of dependencies that you also need to install.
I found this Python alternative:
https://github.com/dilshod/xlsx2csv
$ easy_install xlsx2csv
$ xlsx2csv file.xlsx > newfile.csv
Took 2 seconds to install and works like a charm.
If you have multiple sheets you can export all at once, or one at a time:
$ xlsx2csv file.xlsx --all > all.csv
$ xlsx2csv file.xlsx --all -p '' > all-no-delimiter.csv
$ xlsx2csv file.xlsx -s 1 > sheet1.csv
He also links to several alternatives built in Bash, Python, Ruby, and Java.
Go to Windows Credential Manager (press Windows Key and type 'credential') to edit the git entry under Windows Credentials. Replace old password with the new one.
I solved this problem by using,
element.scrollIntoView({ behavior: 'smooth', block: 'center' });
This makes the element appear in the center
after scrolling, so I don't have to calculate yOffset
.
Hope it helps...
There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.
For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.
There are actually multiple solutions, depending on the scenario:
public static void runJustBeforeBeingDrawn(final View view, final Runnable runnable) { final OnPreDrawListener preDrawListener = new OnPreDrawListener() { @Override public boolean onPreDraw() { view.getViewTreeObserver().removeOnPreDrawListener(this); runnable.run(); return true; } }; view.getViewTreeObserver().addOnPreDrawListener(preDrawListener); }
Sample usage:
ViewUtil.runJustBeforeBeingDrawn(yourView, new Runnable() {
@Override
public void run() {
//Here you can safely get the view size (use "getWidth" and "getHeight"), and do whatever you wish with it
}
});
view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); int width=view.getMeasuredWidth(); int height=view.getMeasuredHeight();
If you know the size of the container:
val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(maxWidth, View.MeasureSpec.AT_MOST)
val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(maxHeight, View.MeasureSpec.AT_MOST)
view.measure(widthMeasureSpec, heightMeasureSpec)
val width=view.measuredWidth
val height=view.measuredHeight
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { final int newHeight= MeasureSpec.getSize(heightMeasureSpec); final int newWidth= MeasureSpec.getSize(widthMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec); }
If you write in Kotlin, you can use the next function, which behind the scenes works exactly like runJustBeforeBeingDrawn
that I've written:
view.doOnPreDraw { actionToBeTriggered() }
Note that you need to add this to gradle (found via here) :
android {
kotlinOptions {
jvmTarget = "1.8"
}
}
implementation 'androidx.core:core-ktx:#.#'
The -I
directive does the job:
gcc -Icore -Ianimator -Iimages -Ianother_dir -Iyet_another_dir my_file.c
Run list
to show all the jobs, then use the jobID/applicationID in the appropriate command.
Kill mapred jobs:
mapred job -list
mapred job -kill <jobId>
Kill yarn jobs:
yarn application -list
yarn application -kill <ApplicationId>
>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'
As of pandas 0.20.3, use .to_pydatetime()
to convert any pandas.DateTimeIndex
instances to Python datetime.datetime
.
Theres a few ways you can do this. You can either add a background to the canvas you are currently working on, which if the canvas isn't going to be redrawn every loop is fine. Otherwise you can make a second canvas underneath your main canvas and draw the background to it. The final way is to just use a standard <img>
element placed under the canvas. To draw a background onto the canvas element you can do something like the following:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = 903;
canvas.height = 657;
var background = new Image();
background.src = "http://www.samskirrow.com/background.png";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
// Draw whatever else over top of it on the canvas.
The rating bar is used automatically at run time for change color on touch star.
First add style in app\src\main\res\values\styles.xml file:
<style name="RatingBar" parent="Theme.AppCompat">
<item name="colorControlNormal">@android:color/darker_gray</item>
<item name="colorControlActivated">@color/com_facebook_blue</item>
</style>
Then your rating bar add theme like this:
<RatingBar
android:id="@+id/rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:stepSize="1"
android:theme="@style/RatingBar"/>
For the current Spring-Boot Version 1.5.3 the parameter is
spring.resources.static-locations
Update I configured
`spring.resources.static-locations=file:/opt/x/y/z/static``
and expected to get my index.html living in this folder when calling
http://<host>/index.html
This did not work. I had to include the folder name in the URL:
http://<host>/static/index.html
Use:
docker start $(docker ps -a -q --filter "status=exited")
This will start all containers which are in the exited state.
docker exec -it <container-id> /bin/bash
This will connect to the particular container.
For the current date activity and complete activity for previous 30 days use this, since the SYSDATE is variable in a day the previous 30th day will not have the whole data for that day.
SELECT DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND SYSDATE()
You can use relative imports only from in a module that was in turn imported as part of a package -- your script or interactive interpreter wasn't, so of course from . import
(which means "import from the same package I got imported from") doesn't work. import mypackage
will be fine once you ensure the parent directory of mypackage
is in sys.path
(how you managed to get your current directory away from sys.path
I don't know -- do you have something strange in site.py, or...?)
To get your current directory back into sys.path
there is in fact no better way than putting it there.
Here's something that worked for me.
@ViewChild('mapSearch', { read: ElementRef }) mapInput: ElementRef;
ngAfterViewInit() {
interval(1000).pipe(
switchMap(() => of(this.mapInput)),
filter(response => response instanceof ElementRef),
take(1))
.subscribe((input: ElementRef) => {
//do stuff
});
}
So I basically set a check every second until the *ngIf
becomes true and then I do my stuff related to the ElementRef
.
Here is a version of @adabyron's answer that prevents the leaky EventArgs
abstraction.
First, the modified EventToCommandBehavior
class (now a generic abstract class and formatted with ReSharper code cleanup). Note the new GetCommandParameter
virtual method and its default implementation:
public abstract class EventToCommandBehavior<TEventArgs> : Behavior<FrameworkElement>
where TEventArgs : EventArgs
{
public static readonly DependencyProperty EventProperty = DependencyProperty.Register("Event", typeof(string), typeof(EventToCommandBehavior<TEventArgs>), new PropertyMetadata(null, OnEventChanged));
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(EventToCommandBehavior<TEventArgs>), new PropertyMetadata(null));
public static readonly DependencyProperty PassArgumentsProperty = DependencyProperty.Register("PassArguments", typeof(bool), typeof(EventToCommandBehavior<TEventArgs>), new PropertyMetadata(false));
private Delegate _handler;
private EventInfo _oldEvent;
public string Event
{
get { return (string)GetValue(EventProperty); }
set { SetValue(EventProperty, value); }
}
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public bool PassArguments
{
get { return (bool)GetValue(PassArgumentsProperty); }
set { SetValue(PassArgumentsProperty, value); }
}
protected override void OnAttached()
{
AttachHandler(Event);
}
protected virtual object GetCommandParameter(TEventArgs e)
{
return e;
}
private void AttachHandler(string eventName)
{
_oldEvent?.RemoveEventHandler(AssociatedObject, _handler);
if (string.IsNullOrEmpty(eventName))
{
return;
}
EventInfo eventInfo = AssociatedObject.GetType().GetEvent(eventName);
if (eventInfo != null)
{
MethodInfo methodInfo = typeof(EventToCommandBehavior<TEventArgs>).GetMethod("ExecuteCommand", BindingFlags.Instance | BindingFlags.NonPublic);
_handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, methodInfo);
eventInfo.AddEventHandler(AssociatedObject, _handler);
_oldEvent = eventInfo;
}
else
{
throw new ArgumentException($"The event '{eventName}' was not found on type '{AssociatedObject.GetType().FullName}'.");
}
}
private static void OnEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = (EventToCommandBehavior<TEventArgs>)d;
if (behavior.AssociatedObject != null)
{
behavior.AttachHandler((string)e.NewValue);
}
}
// ReSharper disable once UnusedMember.Local
// ReSharper disable once UnusedParameter.Local
private void ExecuteCommand(object sender, TEventArgs e)
{
object parameter = PassArguments ? GetCommandParameter(e) : null;
if (Command?.CanExecute(parameter) == true)
{
Command.Execute(parameter);
}
}
}
Next, an example derived class that hides DragCompletedEventArgs
. Some people expressed concern about leaking the EventArgs
abstraction into their view model assembly. To prevent this, I created an interface that represents the values we care about. The interface can live in the view model assembly with the private implementation in the UI assembly:
// UI assembly
public class DragCompletedBehavior : EventToCommandBehavior<DragCompletedEventArgs>
{
protected override object GetCommandParameter(DragCompletedEventArgs e)
{
return new DragCompletedArgs(e);
}
private class DragCompletedArgs : IDragCompletedArgs
{
public DragCompletedArgs(DragCompletedEventArgs e)
{
Canceled = e.Canceled;
HorizontalChange = e.HorizontalChange;
VerticalChange = e.VerticalChange;
}
public bool Canceled { get; }
public double HorizontalChange { get; }
public double VerticalChange { get; }
}
}
// View model assembly
public interface IDragCompletedArgs
{
bool Canceled { get; }
double HorizontalChange { get; }
double VerticalChange { get; }
}
Cast the command parameter to IDragCompletedArgs
, similar to @adabyron's answer.
Just add the line below to the <TextInput>
secureTextEntry={true}
Here is (low and dirty) workaround in case you need to use ajax or some feature which you cannot use when making link manually (using tag):
<%= Html.ActionLink("LinkTextToken", "ActionName", "ControllerName").ToHtmlString().Replace("LinkTextToken", "Refresh <span class='large sprite refresh'></span>")%>
You can use any text instead of 'LinkTextToken', it is there only to be replaced, it is only important that it does not occur anywhere else inside actionlink.
Just use regex to get rid of any non number characters whenever a key is pressed or the textbox loses focus.
var numInput;
window.onload = function () {
numInput = document.getElementById('numonly');
numInput.onkeydown = numInput.onblur = numInput.onkeyup = function()
{
numInput.value = numInput.value.replace(/[^0-9]+/,"");
}
}
More one example:
Follow:
qryAux = (from q in qryAux where
q.OrdSeq == (from pp in Sessao.Query<NameTable>() where pp.FieldPk
== q.FieldPk select pp.OrdSeq).Max() select q);
Equals:
select t.* from nametable t where t.OrdSeq =
(select max(t2.OrdSeq) from nametable t2 where t2.FieldPk= t.FieldPk)
You're looking for basename
.
The example from the PHP manual:
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>
As mentioned earlier, you can use the grid system to layout your inputs and labels anyway that you want. The trick is to remember that you can use rows within your columns to break them into twelfths as well.
The example below is one possible way to accomplish your goal and will put the two text boxes near Label3 on the same line when the screen is small or larger.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->_x000D_
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
<!--[if lt IE 9]>_x000D_
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>_x000D_
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>_x000D_
<![endif]-->_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label1</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label2</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-6">_x000D_
<div class="row">_x000D_
<label class="col-xs-12">Label3</label>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-xs-12 col-sm-6">_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-12 col-sm-6">_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label4</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
</body>_x000D_
</html>
_x000D_
I had the similar issue and the above examples doesn't help me to read properties. I have posted the complete class which will help you to read properties values from application.properties file in SpringBoot application in the below link.
Spring Boot - Environment @Autowired throws NullPointerException
Below query will provide exactly the same result as given in the desired response:
db.books.aggregate([
{
$group: {
_id: { addresses: "$addr", books: "$book" },
num: { $sum :1 }
}
},
{
$group: {
_id: "$_id.addresses",
bookCounts: { $push: { bookName: "$_id.books",count: "$num" } }
}
},
{
$project: {
_id: 1,
bookCounts:1,
"totalBookAtAddress": {
"$sum": "$bookCounts.count"
}
}
}
])
The response will be looking like below:
/* 1 */
{
"_id" : "address4",
"bookCounts" : [
{
"bookName" : "book3",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 2 */
{
"_id" : "address90",
"bookCounts" : [
{
"bookName" : "book33",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 3 */
{
"_id" : "address15",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 4 */
{
"_id" : "address3",
"bookCounts" : [
{
"bookName" : "book9",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 5 */
{
"_id" : "address5",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 6 */
{
"_id" : "address1",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 3
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 4
},
/* 7 */
{
"_id" : "address2",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 2
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 3
},
/* 8 */
{
"_id" : "address77",
"bookCounts" : [
{
"bookName" : "book11",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 9 */
{
"_id" : "address9",
"bookCounts" : [
{
"bookName" : "book99",
"count" : 1
}
],
"totalBookAtAddress" : 1
}
Put the line
$this->db->order_by("course_name","desc");
at top of your query. Like
$this->db->order_by("course_name","desc");$this->db->select('*');
$this->db->where('tennant_id',$tennant_id);
$this->db->from('courses');
$query=$this->db->get();
return $query->result();
The headers and footers for printing from browsers is, sadly, a browser preference, not a document-level element that you can style. Refer to my very similar question for further workarounds and disappointment.
foreach (DataRow dr in ds.Tables[0].Rows)
{
//your code here
}
I know this is old but here's a one liner list comprehension:
data = ['word1, 23, 12','word2, 10, 19','word3, 11, 15']
[[int(item) if item.isdigit() else item for item in items.split(', ')] for items in data]
or
[int(item) if item.isdigit() else item for items in data for item in items.split(', ')]
You can also consult readlink -f "which java
". However it might not work for all binary wrappers. It is most likely better to actually start a Java class.
Use Control.BringToFront
:
myForm.BringToFront();
Why don't you try using only this code:
dismiss();
If you want to dismiss the Dialog Fragment by its own. You can simply put this code inside the dialog fragment where you want to dismiss the Dialog.
For example:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
This will close the recent Dialog Fragment that is shown on the screen.
Hope it helps for you.
Just check the dictionary:
d = {'hello':'world'}
if d:
print 'not empty'
else:
print 'empty'
d = {}
if d:
print 'not empty'
else:
print 'empty'
A simple function to understand how to retrieve og:tags, title and description, adapt this for yourself
function read_og_tags_as_json($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$HTML_DOCUMENT = curl_exec($ch);
curl_close($ch);
$doc = new DOMDocument();
$doc->loadHTML($HTML_DOCUMENT);
// fecth <title>
$res['title'] = $doc->getElementsByTagName('title')->item(0)->nodeValue;
// fetch og:tags
foreach( $doc->getElementsByTagName('meta') as $m ){
// if had property
if( $m->getAttribute('property') ){
$prop = $m->getAttribute('property');
// here search only og:tags
if( preg_match("/og:/i", $prop) ){
// get results on an array -> nice for templating
$res['og_tags'][] =
array( 'property' => $m->getAttribute('property'),
'content' => $m->getAttribute('content') );
}
}
// end if had property
// fetch <meta name="description" ... >
if( $m->getAttribute('name') == 'description' ){
$res['description'] = $m->getAttribute('content');
}
}
// end foreach
// render JSON
echo json_encode($res, JSON_PRETTY_PRINT |
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
Return for this page (may have more infos) :
{
"title": "php - Getting title and meta tags from external website - Stack Overflow",
"og_tags": [
{
"property": "og:type",
"content": "website"
},
{
"property": "og:url",
"content": "https://stackoverflow.com/questions/3711357/getting-title-and-meta-tags-from-external-website"
},
{
"property": "og:site_name",
"content": "Stack Overflow"
},
{
"property": "og:image",
"content": "https://cdn.sstatic.net/Sites/stackoverflow/Img/[email protected]?v=73d79a89bded"
},
{
"property": "og:title",
"content": "Getting title and meta tags from external website"
},
{
"property": "og:description",
"content": "I want to try figure out how to get the\n\n<title>A common title</title>\n<meta name=\"keywords\" content=\"Keywords blabla\" />\n<meta name=\"description\" content=\"This is the descript..."
}
]
}
As of surefire plugin version 2.22.1 (possibly earlier) you can run single test using testnames property when using testng.xml
Given a following testng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="all-tests">
<classes>
<class name="server.Atest"/>
<class name="server.Btest"/>
<class name="server.Ctest"/>
</classes>
</test>
<test name="run-A-test">
<classes>
<class name="server.Atest"/>
</classes>
</test>
<test name="run-B-test">
<classes>
<class name="server.Btest"/>
</classes>
</test>
<test name="run-C-test">
<classes>
<class name="server.Ctest"/>
</classes>
</test>
</suite>
with the pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
[...]
<properties>
<selectedTests>all-tests</selectedTests>
</properties>
[...]
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
<configuration>
<suiteXmlFiles>
<file>src/test/resources/testng.xml</file>
</suiteXmlFiles>
<properties>
<property>
<name>testnames</name>
<value>${selectedTests}</value>
</property>
</properties>
</configuration>
</plugin>
</plugins>
[...]
</project>
From command line
mvn clean test -DselectedTests=run-B-test
Further reading - Maven surefire plugin using testng
I like this one: it - vec.begin()
, because to me it clearly says "distance from beginning". With iterators we're used to thinking in terms of arithmetic, so the -
sign is the clearest indicator here.
Use utcOffset function.
var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).utcOffset(10 * 60); //set timezone offset in minutes
console.log(localDate.format()); //2015-01-30T20:00:00+10:00
The difference between static const
and #define
is that the former uses the memory and the later does not use the memory for storage. Secondly, you cannot pass the address of an #define
whereas you can pass the address of a static const
. Actually it is depending on what circumstance we are under, we need to select one among these two. Both are at their best under different circumstances. Please don't assume that one is better than the other... :-)
If that would have been the case, Dennis Ritchie would have kept the best one alone... hahaha... :-)
you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image
if not installed ARM EABI v7a System Image, you should install all.
In the controller action append to the header the following lines
public ActionResult Create(string PositionID)
{
Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.
You can create GitHub repositories via the command line using their Repositories API (http://develop.github.com/p/repo.html)
Check Creating github repositories with command line | Do it yourself Android for example usage.
Try this, create drawable in your resource...
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="@color/white"/>
<size android:height="20dp"
android:width="20dp"/>
</shape>
then use...
Drawable mDrawable = getActivity().getResources().getDrawable(R.drawable.bg_rectangle_multicolor);
mDrawable.setColorFilter(Color.parseColor(color), PorterDuff.Mode.SRC_IN);
mView1.setBackground(mDrawable);
with color... "#FFFFFF"
if the color is transparent use... setAlpha
mView1.setAlpha(x);
with x float 0-1 Ej (0.9f)
Good Luck
for more advanced python editing consider installing the simplefold vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.
The $http service can be used for general purpose AJAX. If you have a proper RESTful API, you should take a look at ngResource.
You might also take a look at Restangular, which is a third party library to handle REST APIs easy.
For the record, jQuery has an is()
function for this:
a.is(b)
Note that a
is already a jQuery instance.
If there's something about what infix and prefix mean that you don't quite understand, I'd highly suggest you reread that section of your textbook. You aren't doing yourself any favors if you come out of this with the right answer for this one problem, but still don't understand the concept.
Algorithm-wise, its pretty darn simple. You just act like a computer yourself a bit. Start by puting parens around every calculation in the order it would be calculated. Then (again in order from first calculation to last) just move the operator in front of the expression on its left hand side. After that, you can simplify by removing parens.
If your string (In your case the variable text
) could be null this would make a big Difference:
1-string.IsNullOrEmpty(text.Trim())
--> EXCEPTION since your calling a mthode of a null object
2-string.IsNullOrWhiteSpace(text)
This would work fine since the null issue is beeing checked internally
To provide the same behaviour using the 1st Option you would have to check somehow if its not null first then use the trim() method
if ((text != null) && string.IsNullOrEmpty(text.Trim())) { ... }
Try this:
With xlApp.ActiveSheet.Pictures.Insert(PicPath)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = 75
.Height = 100
End With
.Left = xlApp.ActiveSheet.Cells(i, 20).Left
.Top = xlApp.ActiveSheet.Cells(i, 20).Top
.Placement = 1
.PrintObject = True
End With
It's better not to .select anything in Excel, it is usually never necessary and slows down your code.
You can copy those two functions (listed below), and use them to escape/unescape all quotes and special characters. You don't have to use jQuery or any other library for this.
function escape(s) {
return ('' + s)
.replace(/\\/g, '\\\\')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\u00A0/g, '\\u00A0')
.replace(/&/g, '\\x26')
.replace(/'/g, '\\x27')
.replace(/"/g, '\\x22')
.replace(/</g, '\\x3C')
.replace(/>/g, '\\x3E');
}
function unescape(s) {
s = ('' + s)
.replace(/\\x3E/g, '>')
.replace(/\\x3C/g, '<')
.replace(/\\x22/g, '"')
.replace(/\\x27/g, "'")
.replace(/\\x26/g, '&')
.replace(/\\u00A0/g, '\u00A0')
.replace(/\\n/g, '\n')
.replace(/\\t/g, '\t');
return s.replace(/\\\\/g, '\\');
}
This works:
<select name="foo" id="foo">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<input type="button" id="button" value="Button" />
$('#button').click(function() {
alert($('#foo option:selected').text());
alert($('#foo option:selected').val());
});
There is no built in thread based pool. However, it can be very quick to implement a producer/consumer queue with the Queue
class.
From: https://docs.python.org/2/library/queue.html
from threading import Thread
from Queue import Queue
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
q = Queue()
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()
for item in source():
q.put(item)
q.join() # block until all tasks are done
Totally possible with the python-varname package (python3):
from varname import nameof
s = 'Hey!'
print (nameof(s))
Output:
s
Get the package here:
IOError: [Errno 13] Permission denied: 'juliodantas2015.json'
tells you everything you need to know: though you successfully made your python program executable with your chmod
, python can't open that juliodantas2015.json'
file for writing. You probably don't have the rights to create new files in the folder you're currently in.
If you are using cocos2d, you may see an issue with [parentView bringSubviewToFront:view], at least it was not working for me. Instead of bringing the view I wanted to the front, I send the other views back and that did the trick.
[[[CCDirector sharedDirector] view] sendSubviewToBack:((UIButton *) button)];
:not()
pseudo class:For selecting everything but a certain element (or elements). We can use the :not()
CSS pseudo class. The :not()
pseudo class requires a CSS
selector as its argument. The selector will apply the styles to all the elements except for the elements which are specified as an argument.
/* This query selects All div elements except for */_x000D_
div:not(.foo) {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Selects all hovered nav elements inside section element except_x000D_
for the nav elements which have the ID foo*/_x000D_
section nav:hover:not(#foo) {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* selects all li elements inside an ul which are not odd */_x000D_
ul li:not(:nth-child(odd)) { _x000D_
color: red;_x000D_
}
_x000D_
<div>test</div>_x000D_
<div class="foo">test</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<section>_x000D_
<nav id="foo">test</nav>_x000D_
<nav>Hover me!!!</nav>_x000D_
</section>_x000D_
<nav></nav>_x000D_
_x000D_
<br>_x000D_
_x000D_
<ul>_x000D_
<li>1</li>_x000D_
<li>2</li>_x000D_
<li>3</li>_x000D_
<li>4</li>_x000D_
<li>5</li>_x000D_
</ul>
_x000D_
We can already see the power of this pseudo class, it allows us to conveniently fine tune our selectors by excluding certain elements. Furthermore, this pseudo class increases the specificity of the selector. For example:
/* This selector has a higher specificity than the #foo below */_x000D_
#foo:not(#bar) {_x000D_
color: red;_x000D_
}_x000D_
_x000D_
/* This selector is lower in the cascade but is overruled by the style above */_x000D_
#foo {_x000D_
color: green;_x000D_
}
_x000D_
<div id="foo">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor_x000D_
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</div>
_x000D_
A.replaceWith(span)
- No parent neededGeneric form:
target.replaceWith(element)
Way better/cleaner than the previous method.
For your use case:
A.replaceWith(span)
...
).Examples:
// Initially [child1, target, child3]
target.replaceWith(span, "foo") // [child1, span, "foo", child3]
const list = ["bar", span]
target.replaceWith(...list, "fizz") // [child1, "bar", span, "fizz", child3]
null
targetIf your target has a chance to be null, you can consider using the newish ?.
optional chaining operator. Nothing will happen if target doesn't exist. Read more here.
target?.replaceWith(element)
Supported Browsers - 94% Apr 2020
I think you can achieve this the quickest by using the where
function:
For example looking for items greater than 0.2 in a numpy array and replacing those with 0:
import numpy as np
nums = np.random.rand(4,3)
print np.where(nums > 0.2, 0, nums)
I had a similar proxy related problem. In my case it was enough to add:
webRequest.Proxy.Credentials = new NetworkCredential("user", "password", "domain");
Apache commons collections library provides a utility method for inversing the map. You can use this if you are sure that the values of myHashMap are unique
org.apache.commons.collections.MapUtils.invertMap(java.util.Map map)
Sample code
HashMap<String, Character> reversedHashMap = MapUtils.invertMap(myHashMap)
Remove the spaces before the autoplay=1:
src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&;enablejsapi=1"
rm -rf .git
should suffice. That will blow away all Git-related information.
Use Google Maps JavaScript API with places library to implement Google Maps Autocomplete search box in the webpage.
HTML
<input id="searchInput" class="controls" type="text" placeholder="Enter a location">
JavaScript
<script>
function initMap() {
var input = document.getElementById('searchInput');
var autocomplete = new google.maps.places.Autocomplete(input);
}
</script>
Complete guide, source code, and live demo can be found from here - Google Maps Autocomplete Search Box with Map and Info Window
This will give you a very compact list of all messages for any specified time.
git log --since=1/11/2011 --until=28/11/2011 --no-merges --format=%B > CHANGELOG.TXT
Razor is a view engine for ASP.NET MVC, and also a template engine. Razor code and ASP.NET inline code (code mixed with markup) both get compiled first and get turned into a temporary assembly before being executed. Thus, just like C# and VB.NET both compile to IL which makes them interchangable, Razor and Inline code are both interchangable.
Therefore, it's more a matter of style and interest. I'm more comfortable with razor, rather than ASP.NET inline code, that is, I prefer Razor (cshtml) pages to .aspx pages.
Imagine that you want to get a Human
class, and render it. In cshtml files you write:
<div>Name is @Model.Name</div>
While in aspx files you write:
<div>Name is <%= Human.Name %></div>
As you can see, @
sign of razor makes mixing code and markup much easier.
A note for others who may be using Owl Carousel v 1.3.2:
You can replace the navigation text in the settings where you're enabling the navigation.
navigation:true,
navigationText: [
"<i class='fa fa-chevron-left'></i>",
"<i class='fa fa-chevron-right'></i>"
]
This is to help fill in the gaps in Adrien Plisson's answer (which should be upvoted as soon as he edits it ;-):
you can also get the fully qualified path of your first argument by using %~f1, but this gives a path according to the current path, which is obviously not what you want.
unfortunately, i don't know how to mix the 2 together...
One can handle %0
and %1
likewise:
%~dpnx0
for fully qualified drive+path+name+extension of the batchfile itself,%~f0
also suffices;%~dpnx1
for fully qualified drive+path+name+extension of its first argument [if that's a filename at all],%~f1
also suffices;%~f1
will work independent of how you did specify your first argument: with relative paths or with absolute paths (if you don't specify the file's extension when naming %1
, it will not be added, even if you use %~dpnx1
-- however.
But how on earth would you name a file on a different drive anyway if you wouldn't give that full path info on the commandline in the first place?
However, %~p0
, %~n0
, %~nx0
and %~x0
may come in handy, should you be interested in path (without driveletter), filename (without extension), full filename with extension or filename's extension only. But note, while %~p1
and %~n1
will work to find out the path or name of the first argument, %~nx1
and %~x1
will not add+show the extension, unless you used it on the commandline already.
Fixed position elements are positioned relative to the browser window, so the parent element is basically irrelevant.
To get the effect you want, where the overflow
on the parent clips the child, use position: absolute
instead: http://jsfiddle.net/DBHUv/1/
what worked for me is to remove the runconfiguration of the test. Then right click the testclass and click run as junit test.
now it recreates a correct run config for me.
$('[data-item-id="stand-out"]')
I wanted "key" & "value" pair of a first dictionary item. I used the following code.
key, val = next(iter(my_dict.items()))
For MacPython installations, I found an effective solution to fixing the problem with setuptools (easy_install) in this blog post:
http://droidism.com/getting-running-with-django-and-macpython-26-on-leopard
One handy tip includes finding out which version of python is active in the terminal:
which python
A shot in the dark, but From the looks of your error message, it seems that either the sqlserver instance is not running on port 1433 or something is blocking the requests to that port
My answer below doesn't solve the question but it relates to.
If someone is using enum
instead of a class model, like this example:
public enum Counter
{
[Display(Name = "Number 1")]
No1 = 1,
[Display(Name = "Number 2")]
No2 = 2,
[Display(Name = "Number 3")]
No3 = 3
}
And a property to get the value when submiting:
public int No { get; set; }
In the razor page, you can use Html.GetEnumSelectList<Counter>()
to get the enum properties.
<select asp-for="No" asp-items="@Html.GetEnumSelectList<Counter>()"></select>
It generates the following HTML:
<select id="No" name="No">
<option value="1">Number 1</option>
<option value="2">Number 2</option>
<option value="3">Number 3</option>
</select>
Try this
$('body').on('change', '#multiid', function() {
// your stuff
})
please check .on()
selector
__func__
is documented in the C++0x standard at section 8.4.1. In this case it's a predefined function local variable of the form:
static const char __func__[] = "function-name ";
where "function name" is implementation specfic. This means that whenever you declare a function, the compiler will add this variable implicitly to your function. The same is true of __FUNCTION__
and __PRETTY_FUNCTION__
. Despite their uppercasing, they aren't macros. Although __func__
is an addition to C++0x
g++ -std=c++98 ....
will still compile code using __func__
.
__PRETTY_FUNCTION__
and __FUNCTION__
are documented here http://gcc.gnu.org/onlinedocs/gcc-4.5.1/gcc/Function-Names.html#Function-Names. __FUNCTION__
is just another name for __func__
. __PRETTY_FUNCTION__
is the same as __func__
in C but in C++ it contains the type signature as well.
You can simple make use of lapply
or sapply
builtin functions.
lapply
will return you a list
-
lapply(dataframe,class)
while sapply
will take the best possible return type ex. Vector etc -
sapply(dataframe,class)
Both the commands will return you all the column names with their respective class.
If the problem is with the index as the staging area for commits (i.e. .git/index
), you can simply remove the index (make a backup copy if you want), and then restore index to version in the last commit:
On OSX/Linux:
rm -f .git/index
git reset
On Windows:
del .git\index
git reset
(The reset
command above is the same as git reset --mixed HEAD
)
You can alternatively use lower level plumbing git read-tree
instead of git reset
.
If the problem is with index for packfile, you can recover it using git index-pack
.
If you have at least 2 wifi networks to connect is a very simple way is to use a bug in iOS simulator:
The bug is that simulator tries to use a network (IP?) which is not connected already.
Until you relaunched simulator- it will have no internet (even if that first wifi network you connected had internet connection), so you can run (cmd-R) and stop (cmd-.) project(s) to use simulator without connection, but your Mac will be connected.
Then, if you'll need to run simulator connected- just quit and launch it.
The easiest way to use this is
put this in the header:
<script>
$(function ($) {
$("a").tooltip()
});
</script>
and then
<a href="#" rel="tooltip" data-placement="bottom" title="My Tooltip Text">
My link text
</a>
so with that js code if you have tag any where in your page with rel="tooltip"
get the bootstrap tooltip.
good luck.
run configuration -> arguments -> vm arguments
(can also be placed in the debug configuration under Debug Configuration->Arguments->VM Arguments)
VanillaJS === JavaScript i.e.VanillaJS is native JavaScript
Why, Vanilla says it all!!!
Computer software, and sometimes also other computing-related systems like computer hardware or algorithms, are called vanilla when not customized from their original form, meaning that they are used without any customization or updates applied to them (Refer this article). So Vanilla often refers to pure or plain.
In the English language Vanilla has a similar meaning, In information technology, vanilla (pronounced vah-NIHL-uh ) is an adjective meaning plain or basic. Or having no special or extra features, ordinary or standard.
So why name it VanillaJS? As the accepted answer says some bosses want to work with a framework (because it's more organized and flexible and do all the things we want??) but simply JavaScript will do the job. Yet you need to add a framework somewhere. Use VanillaJS...
Is it a Joke? YES
Want some fun?
Where can you find it, http://vanilla-js.com/ Download and see for yourself!!! It's 0 bytes uncompressed, 25 bytes gzipped
:D
Found this pun on internet regarding JS frameworks (Not to condemn the existing JS frameworks though, they'll make life really easy :)),
Also refer,
x=[]
for i in range(0,5):
x.append(i)
print(x[i])
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
If you want to display an image file on the phone, you can do this:
private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageBitmap(BitmapFactory.decodeFile("pathToImageFile"));
If you want to display an image from your drawable resources, do this:
private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageResource(R.drawable.imageFileId);
You'll find the drawable
folder(s) in the project res
folder. You can put your image files there.
You can comput hashes using MessageDigest
, but this is wrong in terms of security. Hashes are not to be used for storing passwords, as they are easily breakable.
You should use another algorithm like bcrypt, PBKDF2 and scrypt to store you passwords. See here.
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").parse("2012-07-10 14:58:00.000000");
The mm
is minutes you want MM
CODE
public class Test {
public static void main(String[] args) throws ParseException {
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
.parse("2012-07-10 14:58:00.000000");
System.out.println(temp);
}
}
Prints:
Tue Jul 10 14:58:00 EDT 2012
You could try using the <col>
tag manage table styling for all rows but you will need to set the table-layout:fixed
style on the <table>
or the tables css class and set the overflow
style for the cells
http://www.w3schools.com/TAGS/tag_col.asp
<table class="fixed">
<col width="20px" />
<col width="30px" />
<col width="40px" />
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
</table>
and this be your CSS
table.fixed { table-layout:fixed; }
table.fixed td { overflow: hidden; }
You could do this if it's short:
int[] array = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
but that gets bad for more than just a few.
Easier would be a for
loop:
int[] myArray = new int[10];
for (int i = 0; i < array.length; i++)
myArray[i] = -1;
Edit: I also like the Arrays.fill()
option other people have mentioned.
Frequently use this:
grep
can be used in conjunction with -r
(recursive), i
(ignore case) and -o
(prints only matching part of lines). To exclude files
use --exclude
and to exclude directories use --exclude-dir
.
Putting it together you end up with something like:
grep -rio --exclude={filenames comma separated} \
--exclude-dir={directory names comma separated} <search term> <location>
Describing it makes it sound far more complicated than it actually is. Easier to illustrate with a simple example.
Example:
Suppose I am searching for current project for all places where I explicitly set the string value debugger
during a debugging session, and now wish to review / remove.
I write a script called findDebugger.sh
and use grep
to find all occurrences. However:
For file exclusions - I wish to ensure that .eslintrc
is ignored (this actually has a linting rule about debugger
so should be excluded). Likewise, I don't want my own script to be referenced in any results.
For directory exclusions - I wish to exclude node_modules
as it contains lots of libraries that do reference debugger
and I am not interested in those results. Also I just wish to omit .idea
and .git
hidden directories because I don't care about those search locations either, and wish to keep the search performant.
So here is the result - I create a script called findDebugger.sh
with:
#!/usr/bin/env bash
grep -rio --exclude={.eslintrc,findDebugger.sh} \
--exclude-dir={node_modules,.idea,.git} debugger .
// styles.css
html {
scroll-behavior: smooth
}
Source: https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2
You can simply add show.legend=FALSE
to geom to suppress the corresponding legend
I just hit this error after trying to "git submodule init" on a new checkout of my repo. Turns out I had specified the module sub-folder with the wrong case initially. Since I'm on a Mac with a case-sensitive filesystem (hurr) it was failing. For example:
git submodule add [email protected]:user/project.git MyApp/Resources/Project
Cloning into 'MyApp/Resources/Project'
succeeds but the trouble is that on disk the path is
Myapp/Resources/Project
What I don't understand is why git is init'ing the module to wrong folder (ignoring the incorrect case in my command) but then operating correctly (by failing) with subsequent commands.
The difference is pretty subtle and if you dont pay much attention then you will keep it using in a wrong way.
Best way to understand the difference between orElse()
and orElseGet()
is that orElse()
will always be executed if the Optional<T>
is null or not, But orElseGet()
will only be executed when Optional<T>
is null.
The dictionary meaning of orElse is :- execute the part when something is not present, but here it contradicts, see the below example:
Optional<String> nonEmptyOptional = Optional.of("Vishwa Ratna");
String value = nonEmptyOptional.orElse(iAmStillExecuted());
public static String iAmStillExecuted(){
System.out.println("nonEmptyOptional is not NULL,still I am being executed");
return "I got executed";
}
Output: nonEmptyOptional is not NULL,still I am being executed
Optional<String> emptyOptional = Optional.ofNullable(null);
String value = emptyOptional.orElse(iAmStillExecuted());
public static String iAmStillExecuted(){
System.out.println("emptyOptional is NULL, I am being executed, it is normal as
per dictionary");
return "I got executed";
}
Output: emptyOptional is NULL, I am being executed, it is normal as per dictionary
For
orElseGet()
, The method goes as per dictionary meaning, TheorElseGet()
part will be executed only when the Optional is null.
Benchmarks:
+--------------------+------+-----+------------+-------------+-------+
| Benchmark | Mode | Cnt | Score | Error | Units |
+--------------------+------+-----+------------+-------------+-------+
| orElseBenchmark | avgt | 20 | 60934.425 | ± 15115.599 | ns/op |
+--------------------+------+-----+------------+-------------+-------+
| orElseGetBenchmark | avgt | 20 | 3.798 | ± 0.030 | ns/op |
+--------------------+------+-----+------------+-------------+-------+
Remarks:
orElseGet()
has clearly outperformedorElse()
for our particular example.
Hope it clears the doubts of people like me who wants the very basic ground example :)
A function can only have too many parameters if some of the parameters are redundant. If all the parameters are used, the function must have the correct number of parameters. Take this often used function:
HWND CreateWindowEx
(
DWORD dwExStyle,
LPCTSTR lpClassName,
LPCTSTR lpWindowName,
DWORD dwStyle,
int x,
int y,
int nWidth,
int nHeight,
HWND hWndParent,
HMENU hMenu,
HINSTANCE hInstance,
LPVOID lpParam
);
That's 12 parameters (9 if you bundle the x,y,w and h as a rectangle) and there's also the parameters derived from the class name as well. How would you reduce this? Would you want to reduce the number more to the point?
Don't let the number of parameters bother you, just make sure it's logical and well documented and let intellisense* help you.
* Other coding assistants are available!
CAST is standard SQL, but CONVERT is only for the dialect T-SQL. We have a small advantage for convert in the case of datetime.
With CAST, you indicate the expression and the target type; with CONVERT, there’s a third argument representing the style for the conversion, which is supported for some conversions, like between character strings and date and time values. For example, CONVERT(DATE, '1/2/2012', 101) converts the literal character string to DATE using style 101 representing the United States standard.
if you'd rather cut the image to display in circular, here you go
public static Bitmap getCircularBitmap(Bitmap bitmap) {
Bitmap output;
if (bitmap.getWidth() > bitmap.getHeight()) {
output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
} else {
output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
float r = 0;
if (bitmap.getWidth() > bitmap.getHeight()) {
r = bitmap.getHeight() / 2;
} else {
r = bitmap.getWidth() / 2;
}
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(r, r, r, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
import java.io.*;
public class Code {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder("ls", "-ltr");
Process process = builder.start();
StringBuilder out = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line = null;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append("\n");
}
System.out.println(out);
}
}
}
No, but you could open a web server at, for example, 127.0.0.77 and use it to check if the Request URI is "/welcome.aspx"... If yes redirect to google, if not load the original site.
127.0.0.77 mysite.com
try this
= f.input :title, :as => :hidden, :input_html => { :value => "some value" }
If you need a Win 10 UWP compatible variant:
using DomXmlDocument = Windows.Data.Xml.Dom.XmlDocument;
public static class DocumentExtensions
{
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using (var xmlReader = xDocument.CreateReader())
{
xmlDocument.Load(xmlReader);
}
return xmlDocument;
}
public static DomXmlDocument ToDomXmlDocument(this XDocument xDocument)
{
var xmlDocument = new DomXmlDocument();
using (var xmlReader = xDocument.CreateReader())
{
xmlDocument.LoadXml(xmlReader.ReadOuterXml());
}
return xmlDocument;
}
public static XDocument ToXDocument(this XmlDocument xmlDocument)
{
using (var memStream = new MemoryStream())
{
using (var w = XmlWriter.Create(memStream))
{
xmlDocument.WriteContentTo(w);
}
memStream.Seek(0, SeekOrigin.Begin);
using (var r = XmlReader.Create(memStream))
{
return XDocument.Load(r);
}
}
}
public static XDocument ToXDocument(this DomXmlDocument xmlDocument)
{
using (var memStream = new MemoryStream())
{
using (var w = XmlWriter.Create(memStream))
{
w.WriteRaw(xmlDocument.GetXml());
}
memStream.Seek(0, SeekOrigin.Begin);
using (var r = XmlReader.Create(memStream))
{
return XDocument.Load(r);
}
}
}
}
Improved version of Komang answer (add referer and user agent, check if you can write the file), return true if it's ok, false if there is an error :
public function downloadImage($url,$filename){
if(file_exists($filename)){
@unlink($filename);
}
$fp = fopen($filename,'w');
if($fp){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$result = parse_url($url);
curl_setopt($ch, CURLOPT_REFERER, $result['scheme'].'://'.$result['host']);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0');
$raw=curl_exec($ch);
curl_close ($ch);
if($raw){
fwrite($fp, $raw);
}
fclose($fp);
if(!$raw){
@unlink($filename);
return false;
}
return true;
}
return false;
}
If you're using Intellij on Mac, this setup finally worked for me.
Installations: Intellij
Settings:
Enable Annotation processor
Check if Lombok plugin is enabled
Add Lombok jar in Global Libraries and project dependencies.
File --> Project Structure --> Project Settings --> Modules --> Dependencies Tab = check lombok
Restart Intellij
With custom colours (for example, dark red, dark green and dark blue):
import random
COLORS = [(139, 0, 0),
(0, 100, 0),
(0, 0, 139)]
def random_color():
return random.choice(COLORS)
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++)
{
if (attributes[i] is DomainNameAttribute)
{
System.Console.WriteLine(((DomainNameAttribute) attributes[i]).Name);
}
}
I was also searching same answer, because at some point of time I needed total_count with distinct values along with limit/offset.
Because it's little tricky to do- To get total count with distinct values along with limit/offset. Usually it's hard to get total count with limit/offset. Finally I got the way to do -
SELECT DISTINCT COUNT(*) OVER() as total_count, * FROM table_name limit 2 offset 0;
Query performance is also high.
For checking the version of scikit-learn in shell script, if you have pip installed, you can try this command
pip freeze | grep scikit-learn
scikit-learn==0.17.1
Hope it helps!
Follow the steps below:
1- git stash
2- git add .
3- git commit -m "your commit message"
I had these icons for a different reason. We have one big solution for all our projects (nearly 100). I made a subselection of the projects I was interested in and made a new solution. However the references where project references instead of references to the compiled dll's....
After some research I found this link on GitHub which explains this is new behaviour in VS2015.
On the GitHub page they explain a workaround for converting project references to binary references.
To embed a signature on an email, I would use the long version:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
The reason is that not many email readers use html5, so it's always better use old html styles. Actually, it's better to use tables than divs + css as well.
In my case the error happened because the new line after the return
statement.
Error : Expected an assignment or function call and instead saw an expression
return
(
<ul>
{
props.numbers.map(number => <li key={number.toString()}>number</li>)
}
</ul>
);
Working OK. No Error
return (
<ul>
{
props.numbers.map(number => <li key={number.toString()}>number</li>)
}
</ul>
);
If you don't have an array but you are trying to use your observable like an array even though it's a stream of objects, this won't work natively. I show how to fix this below assuming you only care about adding objects to the observable, not deleting them.
If you are trying to use an observable whose source is of type BehaviorSubject, change it to ReplaySubject then in your component subscribe to it like this:
this.messages$ = this.chatService.messages$.pipe(scan((acc, val) => [...acc, val], []));
<div class="message-list" *ngFor="let item of messages$ | async">
If you receive "MMMM" as a response, probably you are getting the month and then converting it to a string of defined format.
DateTime.Now.Month.ToString("MMMM")
will output "MMMM"
DateTime.Now.ToString("MMMM")
will output the month name
It is not a direct answer, but you can (if your server permit):
1) Create a model for your Organization; extra: It will be easier to populate your HTML.
2) Create a factory (FactoryGirl) for your model;
3) Create a list (create_list) with the factory;
4) 'pick' (sample) a Organization from the list with:
# Random select
option = Organization.all.sample
# Select the FIRST(0) by id
option = Organization.all[0]
# Select the SECOND(1) after some restriction
option = Organization.where(some_attr: some_value)[2]
option = Organization.where("some_attr OP some_value")[2] #OP is "=", "<", ">", so on...
You can use nested routes
Django <1.8
urlpatterns = patterns(''
url(r'^project_config/', include(patterns('',
url(r'^$', ProjectConfigView.as_view(), name="project_config")
url(r'^(?P<product>\w+)$', include(patterns('',
url(r'^$', ProductView.as_view(), name="product"),
url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
))),
))),
)
Django >=1.8
urlpatterns = [
url(r'^project_config/', include([
url(r'^$', ProjectConfigView.as_view(), name="project_config")
url(r'^(?P<product>\w+)$', include([
url(r'^$', ProductView.as_view(), name="product"),
url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
])),
])),
]
This is a lot more DRY (Say you wanted to rename the product
kwarg to product_id
, you only have to change line 4, and it will affect the below URLs.
Edited for Django 1.8 and above
LPCWSTR
is equivalent to wchar_t const *
. It's a pointer to a wide character string that won't be modified by the function call.
You can assign to LPCWSTR
s by prepending a L to a string literal: LPCWSTR *myStr = L"Hello World";
LPCTSTR and any other T types, take a string type depending on the Unicode settings for your project. If _UNICODE
is defined for your project, the use of T types is the same as the wide character forms, otherwise the Ansi forms. The appropriate function will also be called this way: FindWindowEx
is defined as FindWindowExA
or FindWindowExW
depending on this definition.
Give the div a class or id and do something like this:
$("#example").get().innerHTML;
That works at the DOM level.
Use the attribute selector
[id^=product]{property:value}
SupressFinalize
tells the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:
Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.
In general, most any Dispose()
method should be able to call GC.SupressFinalize()
, because it should clean up everything that would be cleaned up in the finalizer.
SupressFinalize
is just something that provides an optimization that allows the system to not bother queuing the object to the finalizer thread. A properly written Dispose()
/finalizer should work properly with or without a call to GC.SupressFinalize()
.
I like to use np.vectorize
for such tasks. Consider the following:
>>> # Arrays
>>> x = np.array([5, 2, 3, 1, 4, 5])
>>> y = np.array(['f','o','o','b','a','r'])
>>> # Function containing the constraints
>>> func = np.vectorize(lambda t: t>1 and t<5)
>>> # Call function on x
>>> y[func(x)]
>>> array(['o', 'o', 'a'], dtype='<U1')
The advantage is you can add many more types of constraints in the vectorized function.
Hope it helps.
NSDoc save the text file in a string to an html file then simultaneously load it into a webview that is in the same place as your UITextView..
The accepted answer (setting an explicit width in pixels) makes it hard to make changes, and breaks when your users use a different font size. Using CSS tables, on the other hand, works great:
form { display: table; }_x000D_
p { display: table-row; }_x000D_
label { display: table-cell; }_x000D_
input { display: table-cell; }
_x000D_
<form>_x000D_
<p>_x000D_
<label for="a">Short label:</label>_x000D_
<input id="a" type="text">_x000D_
</p>_x000D_
<p>_x000D_
<label for="b">Very very very long label:</label>_x000D_
<input id="b" type="text">_x000D_
</p>_x000D_
</form>
_x000D_
Here's a JSFiddle: http://jsfiddle.net/DaS39/1/
And if you need the labels right-aligned, just add text-align: right
to the labels: http://jsfiddle.net/DaS39/
EDIT: One more quick note: CSS tables also let you play with columns: for example, if you want to make the input fields take as much space as possible, you can add the following in your form
<div style="display: table-column;"></div>
<div style="display: table-column; width:100%;"></div>
you may want to add white-space: nowrap
to the labels
in that case.
You can get this error if you use wrong mode when opening the file. For example:
with open(output, 'wb') as output_file:
print output_file.read()
In that code, I want to read the file, but I use mode wb
instead of r
or r+
I use this as a daily scheduled task to hide users disabled in AD from the Global Address List
$mailboxes = get-user | where {$_.UserAccountControl -like '*AccountDisabled*' -and $_.RecipientType -eq 'UserMailbox' } | get-mailbox | where {$_.HiddenFromAddressListsEnabled -eq $false}
foreach ($mailbox in $mailboxes) { Set-Mailbox -HiddenFromAddressListsEnabled $true -Identity $mailbox }
I know this is quite out of date, but this might still be useful for those coming late to the party. (EDIT: updated since this still gets traffic and @Goozak has pointed out in the comments that my original analysis of the sample was incorrect as well.)
I pulled this from the example code in your link:
IF !%1==! GOTO VIEWDATA
REM IF NO COMMAND-LINE ARG...
FIND "%1" C:\BOZO\BOOKLIST.TXT
GOTO EXIT0
REM PRINT LINE WITH STRING MATCH, THEN EXIT.
:VIEWDATA
TYPE C:\BOZO\BOOKLIST.TXT | MORE
REM SHOW ENTIRE FILE, 1 PAGE AT A TIME.
:EXIT0
!%1==!
is simply an idiomatic use of ==
intended to verify that the thing on the left, that contains your variable, is different from the thing on the right, that does not. The !
in this case is just a character placeholder. It could be anything. If %1
has content, then the equality will be false, if it does not you'll just be comparing !
to !
and it will be true.
!==!
is not an operator, so writing "asdf" !==! "fdas"
is pretty nonsensical.
The suggestion to use if not "asdf" == "fdas"
is definitely the way to go.
string DemoLimit = "02/28/2018";
string pattern = "MM/dd/yyyy";
CultureInfo enUS = new CultureInfo("en-US");
DateTime.TryParseExact(DemoLimit, pattern, enUS,
DateTimeStyles.AdjustToUniversal, out datelimit);
For more https://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx
Current for 2016 link is https://msdn.microsoft.com/en-us/library/mt204009.aspx
SQL Server Data Tools in Visual Studio 2015 is a modern development tool that you can download for free to build SQL Server relational databases, Azure SQL databases, Integration Services packages, Analysis Services data models, and Reporting Services reports. With SSDT, you can design and deploy any SQL Server content type with the same ease as you would develop an application in Visual Studio. This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016.
Note that you don't need to have Visual Studio pre-installed. SSDT will install required components of VS, if it is not installed on your machine.
This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016
Previously included in SQL Server standalone Business Intelligence Studio is not available any more and in last years replaced by SQL Server Data Tools (SSDT) for Visual Studio. See answer http://sqlmag.com/sql-server-2014/q-where-business-intelligence-development-studio-bids-sql-server-2014
You must use a .ts
file - e.g. test.ts
to get Typescript validation, intellisense typing
of vars, return types, as well as "typed" error checking (e.g. passing a string
to a method that expects an number
param will error out).
It will be transpiled into (standard) .js
via tsc
.
Clarification needed based on down-votes, very helpful comments and other answers.
types
Yes, you can do type
checking in VS Code in .js
files with @ts-check
- as shown in the animation
What I originally was referring to for Typescript types
is something like this in .ts
which isn't quite the same thing:
hello-world.ts
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
This will not compile. Error: Type "1" is not assignable to String
if you tried this syntax in a Javascript hello-world.js
file:
//@ts-check
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file
If there's something I missed that covers this as well as the OP's context, please add. Let's all learn.
You can simply use raw html tags like
foo <font color='red'>bar</font> foo
Be aware that this will not survive a conversion of the notebook to latex.
As there are some complaints about the deprecation of the proposed solution. They are totally valid and Scott has already answered the question with a more recent, i.e. CSS based approach. Nevertheless, this answer shows some general approach to use html tags within IPython to style markdown cell content beyond the available pure markdown capabilities.
I see Federico you've found solution by yourself. The problem was in two places. Assignations need proper quoting, in your case
SOME_PATH="/$COMPANY/someProject/some path"
is one of possible solutions.
But in shell those quotes are not stored in a memory, so when you want to use this variable, you need to quote it again, for example:
NEW_VAR="$SOME_PATH"
because if not, space will be expanded to command level, like this:
NEW_VAR=/YourCompany/someProject/some path
which is not what you want.
For more info you can check out my article about it http://www.cofoh.com/white-shell
Technically, you can too put image data in an img tag, using data URIs.
<img src="data:image/jpeg;base64,<?php echo base64_encode( $image_data ); ?>" />
There are some special circumstances where this could even be useful, although in most cases you're better off serving the image through a separate script like daiscog suggests.
Set the default console colors and fonts:
http://poshcode.org/2220
From Windows PowerShell Cookbook (O'Reilly)
by Lee Holmes (http://www.leeholmes.com/guide)
Set-StrictMode -Version Latest
Push-Location
Set-Location HKCU:\Console
New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee
New-ItemProperty . FaceName -type STRING -value "Lucida Console"
New-ItemProperty . FontFamily -type DWORD -value 0x00000036
New-ItemProperty . FontSize -type DWORD -value 0x000c0000
New-ItemProperty . FontWeight -type DWORD -value 0x00000190
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078
New-ItemProperty . WindowSize -type DWORD -value 0x00320078
Pop-Location
I've just had some of the similar problems with scrollTop
described here.
In the end I got around this on Firefox and IE by using the selector $('*').scrollTop(0);
Not perfect if you have elements you don't want to effect but it gets around the Document, Body, HTML and Window disparity. If it helps...
Old question, but the autolayout-solution with runtime border adjustments still missing.
borders(for: [.left, .bottom], width: 2, color: .red)
The following UIView extension will add the border only on the given edges. If you change the edges at runtime, the borders will adjust accordingly.
extension UIView {
func borders(for edges:[UIRectEdge], width:CGFloat = 1, color: UIColor = .black) {
if edges.contains(.all) {
layer.borderWidth = width
layer.borderColor = color.cgColor
} else {
let allSpecificBorders:[UIRectEdge] = [.top, .bottom, .left, .right]
for edge in allSpecificBorders {
if let v = viewWithTag(Int(edge.rawValue)) {
v.removeFromSuperview()
}
if edges.contains(edge) {
let v = UIView()
v.tag = Int(edge.rawValue)
v.backgroundColor = color
v.translatesAutoresizingMaskIntoConstraints = false
addSubview(v)
var horizontalVisualFormat = "H:"
var verticalVisualFormat = "V:"
switch edge {
case UIRectEdge.bottom:
horizontalVisualFormat += "|-(0)-[v]-(0)-|"
verticalVisualFormat += "[v(\(width))]-(0)-|"
case UIRectEdge.top:
horizontalVisualFormat += "|-(0)-[v]-(0)-|"
verticalVisualFormat += "|-(0)-[v(\(width))]"
case UIRectEdge.left:
horizontalVisualFormat += "|-(0)-[v(\(width))]"
verticalVisualFormat += "|-(0)-[v]-(0)-|"
case UIRectEdge.right:
horizontalVisualFormat += "[v(\(width))]-(0)-|"
verticalVisualFormat += "|-(0)-[v]-(0)-|"
default:
break
}
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: horizontalVisualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["v": v]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: verticalVisualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["v": v]))
}
}
}
}
}
Or Use range
(python 3):
l=[i for i in range(len(lst)) if lst[i]=='something...']
For (python 2):
l=[i for i in xrange(len(lst)) if lst[i]=='something...']
And then (both cases):
print(l)
Is as expected.
When you use Theme.AppCompat in your application you can use FullScreenTheme by adding the code below to styles.
<style name="Theme.AppCompat.Light.NoActionBar.FullScreen" parent="@style/Theme.AppCompat.Light.NoActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>
and also mention in your manifest file.
<activity
android:name=".activities.FullViewActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen"
/>
You can use is_null() function.
http://php.net/manual/en/function.is-null.php : in the comments :
mdufour at gmail dot com 20-Aug-2008 04:31 Testing for a NULL field/column returned by a mySQL query.
Say you want to check if field/column “foo” from a given row of the table “bar” when > returned by a mySQL query is null. You just use the “is_null()” function:
[connect…]
$qResult=mysql_query("Select foo from bar;");
while ($qValues=mysql_fetch_assoc($qResult))
if (is_null($qValues["foo"]))
echo "No foo data!";
else
echo "Foo data=".$qValues["foo"];
[…]
I add the following configuration to web.xml and it got resolved.
<context-param>
<param-name>com.sun.faces.numberOfViewsInSession</param-name>
<param-value>500</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.numberOfLogicalViews</param-name>
<param-value>500</param-value>
</context-param>
Found a solution:
mysql> UPDATE table SET last_update=now(), last_monitor=last_update WHERE id=1;
I found this in MySQL Docs and after a few tests it works:
the following statement sets col2 to the current (updated) col1 value, not the original col1 value. The result is that col1 and col2 have the same value. This behavior differs from standard SQL.
UPDATE t1 SET col1 = col1 + 1, col2 = col1;
You could throw the enum value and string into an STL map. Then you could use it like so.
return myStringMap[Enum::Apple];
I generally use array split because it's easier simple syntax and scales better with more than 2 partitions.
import numpy as np
partitions = 2
dfs = np.array_split(df, partitions)
np.split(df, [100,200,300], axis=0]
wants explicit index numbers which may or may not be desirable.
there is a little problem here because the
if (typeof item !== 'string') {
return false
}
will not stop the foreach. So the function will return true even if the array does contain none string values.
This seems to wok for me:
function isStringArray(value: any): value is number[] {
if (Object.prototype.toString.call(value) === '[object Array]') {
if (value.length < 1) {
return false;
} else {
return value.every((d: any) => typeof d === 'string');
}
}
return false;
}
Greetings, Hans
A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b
the value you get is 2^16 - 56 or 65536 - 56.
Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8
using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8
when casting to a char
, which translates to the positive number 65480
.
From the language specification:
5.1.4. Widening and Narrowing Primitive Conversion
First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).
To get the right point use char c = (char) (b & 0xFF)
which first converts the byte value of b
to the positive integer 200
by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8
becomes 0x000000C8
or the positive number 200
in decimals.
Above is a direct explanation of what happens during conversion between the byte
, int
and char
primitive types.
If you want to encode/decode characters from bytes, use Charset
, CharsetEncoder
, CharsetDecoder
or one of the convenience methods such as new String(byte[] bytes, Charset charset)
or String#toBytes(Charset charset)
. You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets
.
you can use len(arr)
as suggested in previous answers to get the length of the array. In case you want the dimensions of a 2D array you could use arr.shape
returns height and width
With design (based on problem). This is an alternate of divide-and-conquer. We'll first define an enum (considering it's only for an unsigned int).
public enum IntegerLength {
One((byte)1,10),
Two((byte)2,100),
Three((byte)3,1000),
Four((byte)4,10000),
Five((byte)5,100000),
Six((byte)6,1000000),
Seven((byte)7,10000000),
Eight((byte)8,100000000),
Nine((byte)9,1000000000);
byte length;
int value;
IntegerLength(byte len,int value) {
this.length = len;
this.value = value;
}
public byte getLenght() {
return length;
}
public int getValue() {
return value;
}
}
Now we'll define a class that goes through the values of the enum and compare and return the appropriate length.
public class IntegerLenght {
public static byte calculateIntLenght(int num) {
for(IntegerLength v : IntegerLength.values()) {
if(num < v.getValue()){
return v.getLenght();
}
}
return 0;
}
}
The run time of this solution is the same as the divide-and-conquer approach.
So it would become:
List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
while(true)
Iterator<Integer> myListIterator = myCoords.iterator();
while (myListIterator.hasNext()) {
Integer coord = myListIterator.next();
System.out.print("\r" + coord);
try{
Thread.sleep(2000);
}catch(Exception e){
// handle the exception...
}
}
}
result = soup.find('strong', text='text I am looking for').text
It seems you need DataFrame.var
:
Normalized by N-1 by default. This can be changed using the ddof argument
var1 = credit_card.var()
Sample:
#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
var1 = credit_card.var()
print (var1)
A 8.8
B 10.0
C 10.0
D 7.7
E 7.8
dtype: float64
var2 = credit_card.var(axis=1)
print (var2)
0 4.3
1 3.8
2 9.8
3 12.2
4 2.3
dtype: float64
If need numpy solutions with numpy.var
:
print (np.var(credit_card.values, axis=0))
[ 7.04 8. 8. 6.16 6.24]
print (np.var(credit_card.values, axis=1))
[ 3.44 3.04 7.84 9.76 1.84]
Differences are because by default ddof=1
in pandas
, but you can change it to 0
:
var1 = credit_card.var(ddof=0)
print (var1)
A 7.04
B 8.00
C 8.00
D 6.16
E 6.24
dtype: float64
var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0 3.44
1 3.04
2 7.84
3 9.76
4 1.84
dtype: float64
Since Ant 1.8.0 there's apparently also resourceexists
From http://ant.apache.org/manual/Tasks/conditions.html
Tests a resource for existance. since Ant 1.8.0
The actual resource to test is specified as a nested element.
An example:
<resourceexists> <file file="${file}"/> </resourceexists>
I was about rework the example from the above good answer to this question, and then I found this
As of Ant 1.8.0, you may instead use property expansion; a value of true (or on or yes) will enable the item, while false (or off or no) will disable it. Other values are still assumed to be property names and so the item is enabled only if the named property is defined.
Compared to the older style, this gives you additional flexibility, because you can override the condition from the command line or parent scripts:
<target name="-check-use-file" unless="file.exists"> <available property="file.exists" file="some-file"/> </target> <target name="use-file" depends="-check-use-file" if="${file.exists}"> <!-- do something requiring that file... --> </target> <target name="lots-of-stuff" depends="use-file,other-unconditional-stuff"/>
from the ant manual at http://ant.apache.org/manual/properties.html#if+unless
Hopefully this example is of use to some. They're not using resourceexists, but presumably you could?.....
You cant set links to "disabled" just system elements like input, textfield etc.
But you can disable links with jQuery/JavaScript
$('.disabled').click(function(e){
e.preventDefault();
});
Just wrap the above code in whatever event you want to disable the links.
I have seen in some places the abstract method is defined as below. **
"An Abstract Method must have to implement in the child class"
** I felt it is like .
It is not necessary that an abstract method has to be implemented in a child class, if the child class is also abstract ..
1)An abstract method cant be a private method. 2)An Abstract method cant be implemented in the same abstract class.
I would say ..if we are implementing an abstract class, you must have to override the abstract methods from the base abstract class. Because.. Implementing the abstract method is with override key word .Similar to Virtual method.
It is not necessary for a virtual method to be implemented in an inherited class.
----------CODE--------------
public abstract class BaseClass
{
public int MyProperty { get; set; }
protected abstract void MyAbstractMethod();
public virtual void MyVirtualMethod()
{
var x = 3 + 4;
}
}
public abstract class myClassA : BaseClass
{
public int MyProperty { get; set; }
//not necessary to implement an abstract method if the child class is also abstract.
protected override void MyAbstractMethod()
{
throw new NotImplementedException();
}
}
public class myClassB : BaseClass
{
public int MyProperty { get; set; }
//You must have to implement the abstract method since this class is not an abstract class.
protected override void MyAbstractMethod()
{
throw new NotImplementedException();
}
}
Not sure if this is the most elegant solution (this is what I used), but you could scale your data to the range between 0 to 1 and then modify the colorbar:
import matplotlib as mpl
...
ax, _ = mpl.colorbar.make_axes(plt.gca(), shrink=0.5)
cbar = mpl.colorbar.ColorbarBase(ax, cmap=cm,
norm=mpl.colors.Normalize(vmin=-0.5, vmax=1.5))
cbar.set_clim(-2.0, 2.0)
With the two different limits you can control the range and legend of the colorbar. In this example only the range between -0.5 to 1.5 is show in the bar, while the colormap covers -2 to 2 (so this could be your data range, which you record before the scaling).
So instead of scaling the colormap you scale your data and fit the colorbar to that.
this worked for me. documentation from github Squashing Git Commits git reset origin/master
git checkout master && git pull;
git merge feature_branch;
git add . --all;
git commit -m "your commit message"
find documentation here
As a workaround to this limitation, I use two rules to cover all the cases.
For example, if I want to allow or deny these 18 ports:
465,110,995,587,143,11025,20,21,22,26,80,443,3000,10000,7080,8080,3000,5666
I use the below rules:
iptables -A INPUT -p tcp -i eth0 -m multiport --dports 465,110,995,587,143,11025,20,21,22,26,80,443 -j ACCEPT
iptables -A INPUT -p tcp -i eth0 -m multiport --dports 3000,10000,7080,8080,3000,5666 -j ACCEPT
The above rules should work for your scenario also. You can create another rule if you hit 15 ports limit on both first and second rule.
For me I need to specific schema to "information_schema.TABLES"
for example.
SELECT concat('CREATE TABLE new_db.', TABLE_NAME, ' LIKE old_db.', TABLE_NAME, ';') FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'old_db';
I think the most pythonic way to do this for me, will be
elif var in [80,443] + range(1024,65535):
although it could take a little time and memory (it's generating numbers from 1024 to 65535). If there's a problem with that, I'll do:
elif 1024 <= var <= 65535 or var in [80,443]:
If you are using Visual Studio, you can also left-click on the project in Solution Explorer and change the Windows Authentication property to Enabled in the Properties window.
You need to declare @font-face
like this in your stylesheet
@font-face {
font-family: 'Awesome-Font';
font-style: normal;
font-weight: 400;
src: local('Awesome-Font'), local('Awesome-Font-Regular'), url(path/Awesome-Font.woff) format('woff');
}
Now if you want to apply this font to a paragraph simply use it like this..
p {
font-family: 'Awesome-Font', Arial;
}
If you define the action git push
it should take it if no refspec is given on the command line, no refspec is configured in the remote, and no refspec is implied by any of the options given on the command line.
Just do it:
git config --global push.default current
then
git push
- It is a very easy to use method in C++11.
- We can use std::chrono::high_resolution_clock from header
- We can write a method to print the method execution time in a much readable form.
For example, to find the all the prime numbers between 1 and 100 million, it takes approximately 1 minute and 40 seconds. So the execution time get printed as:
Execution Time: 1 Minutes, 40 Seconds, 715 MicroSeconds, 715000 NanoSeconds
The code is here:
#include <iostream>
#include <chrono>
using namespace std;
using namespace std::chrono;
typedef high_resolution_clock Clock;
typedef Clock::time_point ClockTime;
void findPrime(long n, string file);
void printExecutionTime(ClockTime start_time, ClockTime end_time);
int main()
{
long n = long(1E+8); // N = 100 million
ClockTime start_time = Clock::now();
// Write all the prime numbers from 1 to N to the file "prime.txt"
findPrime(n, "C:\\prime.txt");
ClockTime end_time = Clock::now();
printExecutionTime(start_time, end_time);
}
void printExecutionTime(ClockTime start_time, ClockTime end_time)
{
auto execution_time_ns = duration_cast<nanoseconds>(end_time - start_time).count();
auto execution_time_ms = duration_cast<microseconds>(end_time - start_time).count();
auto execution_time_sec = duration_cast<seconds>(end_time - start_time).count();
auto execution_time_min = duration_cast<minutes>(end_time - start_time).count();
auto execution_time_hour = duration_cast<hours>(end_time - start_time).count();
cout << "\nExecution Time: ";
if(execution_time_hour > 0)
cout << "" << execution_time_hour << " Hours, ";
if(execution_time_min > 0)
cout << "" << execution_time_min % 60 << " Minutes, ";
if(execution_time_sec > 0)
cout << "" << execution_time_sec % 60 << " Seconds, ";
if(execution_time_ms > 0)
cout << "" << execution_time_ms % long(1E+3) << " MicroSeconds, ";
if(execution_time_ns > 0)
cout << "" << execution_time_ns % long(1E+6) << " NanoSeconds, ";
}
Edit: Watch out for attr() Its related to calc() in css. You may be able to achieve it in future.
Unfortunately for now there isn't a css only solution. This is what I suggest you do. To your element give a title attribute. And use text-overflow ellipsis to prevent breakage of the design and let user know more text is there.
<div style="width: 200px; height: 1em; text-overflow: ellipsis;" title="Some sample dynamic amount of text here">
Some sample dynamic amount of text here
</div>
.
.
.
Alternatively, If you just want to reduce size based on the viewport. CSS3 supports new dimensions that are relative to view port.
body {
font-size: 3.2vw;
}
It's not a Python example but in the D programing language the term mixin
is used to refer to a construct used much the same way; adding a pile of stuff to a class.
In D (which by the way doesn't do MI) this is done by inserting a template (think syntactically aware and safe macros and you will be close) into a scope. This allows for a single line of code in a class, struct, function, module or whatever to expand to any number of declarations.
You might give this a try:
@echo off
for /f %%a in (sample.txt) do (
echo %%a
exit /b
)
edit Or, say you have four columns of data and want from the 5th row down to the bottom, try this:
@echo off
for /f "skip=4 tokens=1-4" %%a in (junkl.txt) do (
echo %%a %%b %%c %%d
)
One option would be to roll your own. It would be fairly simple to do:
Document doc = getDocument();
Element root = doc.createElement(rootName);
doc.appendChild(root);
for (Map.Entry<String,String> element : map.entrySet() ) {
Element e = doc.createElement(element.getKey());
e.setTextContent(element.getValue());
root.appendChild(e);
}
save(doc, file);
and the load is an equally simply getChildNodes
and a loop. Sure it has a bit of boiler plate that the XML Gods demand but it is at most 1 hours work.
Or you could look at Properties if you are not too fused about the format of the XML.
Hope this easy one liner helps:
cols_as_np = df[df.columns[1:]].to_numpy()
Either of the following SQL will return all schema in Oracle DB.
select owner FROM all_tables group by owner;
select distinct owner FROM all_tables;
I had a similar situation, but the client config was using a basicHttpBinding. The issue turned out to be that the service was using SOAP 1.2 and you can't specify SOAP 1.2 in a basicHttpBinding. I modified the client config to use a customBinding instead and everything worked. Here are the details of my customBinding for reference. The service I was trying to consume was over HTTPS using UserNameOverTransport.
<customBinding>
<binding name="myBindingNameHere" sendTimeout="00:03:00">
<security authenticationMode="UserNameOverTransport" includeTimestamp="false">
<secureConversationBootstrap />
</security>
<textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
messageVersion="Soap12" writeEncoding="utf-8">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</textMessageEncoding>
<httpsTransport manualAddressing="false" maxBufferPoolSize="4194304"
maxReceivedMessageSize="4194304" allowCookies="false" authenticationScheme="Basic"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
keepAliveEnabled="true" maxBufferSize="4194304" proxyAuthenticationScheme="Anonymous"
realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
useDefaultWebProxy="true" requireClientCertificate="false" />
</binding>
</customBinding>