Use this single line.
self.automaticallyAdjustsScrollViewInsets = NO;
These methods are in ObjectNode
: the division is such that most read operations are included in JsonNode
, but mutations in ObjectNode
and ArrayNode
.
Note that you can just change first line to be:
ObjectNode jNode = mapper.createObjectNode();
// version ObjectMapper has should return ObjectNode type
or
ObjectNode jNode = (ObjectNode) objectCodec.createObjectNode();
// ObjectCodec is in core part, must be of type JsonNode so need cast
I was being able to ping my connection but was STILL getting the 'connection refused' error. Turns out I was pinging myself! That's what the problem was.
var clickEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
var element = document.getElementById('element-id');
var cancelled = !element.dispatchEvent(clickEvent);
if (cancelled) {
// A handler called preventDefault.
alert("cancelled");
} else {
// None of the handlers called preventDefault.
alert("not cancelled");
}
element.dispatchEvent
is supported in all major browsers. The example above is based on an sample simulateClick()
function on MDN.
it allows you to kill a task based on the image name like taskkill /im iexplore.exe or taskkill /im notepad.exe
To sort a dictionary and keep it functioning as a dictionary afterwards, you could use OrderedDict from the standard library.
If that's not what you need, then I encourage you to reconsider the sort functions that leave you with a list of tuples. What output did you want, if not an ordered list of key-value pairs (tuples)?
Take a look at the PDOStatement.fetchAll
method. You could also use fetch
in an iterator pattern.
Code sample for fetchAll
, from the PHP documentation:
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);
Results:
Array
(
[0] => Array
(
[NAME] => pear
[COLOUR] => green
)
[1] => Array
(
[NAME] => watermelon
[COLOUR] => pink
)
)
Your "localhost" cannot resolve the name www.google.com, which means your machine doesn't/can't reach a valid dns server.
Try ping google.com on the console of that machine to verify this.
Just as zero is a number - just a number that represents none - an empty list is still a list, just a list with nothing in it. null
is no list at all; it's therefore different from an empty list.
Similarly, a list that contains null items is a list, and is not an empty list. Because it has items in it; it doesn't matter that those items are themselves null. As an example, a list with three null values in it, and nothing else: what is its length? Its length is 3. The empty list's length is zero. And, of course, null doesn't have a length.
Parameter Options FollowSymLinks
enables you to have a symlink in your webroot pointing to some other file/dir. With this disabled, Apache will refuse to follow such symlink. More secure Options SymLinksIfOwnerMatch
can be used instead - this will allow you to link only to other files which you do own.
If you use Options
directive in .htaccess
with parameter which has been forbidden in main Apache config, server will return HTTP 500 error code.
Allowed .htaccess
options are defined by directive AllowOverride
in the main Apache config file. To allow symlinks, this directive need to be set to All
or Options
.
Besides allowing use of symlinks, this directive is also needed to enable mod_rewrite in .htaccess
context. But for this, also the more secure SymLinksIfOwnerMatch
option can be used.
I would suggest a different approach, using my own library you could do this in a few lines:
var groupMe = sequence(
groupBy(pluck('color')),
forOwn(function(acc, k, v) {
acc.push({colors: k, users: v});
return acc;
},[])
);
var result = groupMe(collection);
This would a be a bit difficult with lodash or Underscore because the arguments are in the opposite order order, so you'd have to use _.partial
a lot.
If you want to see how to do a proper definition go into Sublime Text->Preferences->Key Bindings - Default and search for the command you want to override.
{ "keys": ["f12"], "command": "goto_definition" },
{ "keys": ["super+alt+down"], "command": "goto_definition" }
Those are two that show in my Default.
On Mac I copied the second to override.
in Sublime Text -> Preferences -> Key Bindings - User I added this
/* Beginning of File */
[
{
"keys": ["super+shift+i"], "command": "goto_definition"
}
]
/* End of File */
This binds it to the Command + Shift + 1 combination on mac.
below code might help you
var objControl=document.getElementById("divid");
objControl.scrollTop = objControl.offsetTop;
If you want to perform any event on any specific keyboard button press, in that case, you can use @HostListener. For this, you have to import HostListener in your component ts file.
import { HostListener } from '@angular/core';
then use below function anywhere in your component ts file.
@HostListener('document:keyup', ['$event'])
handleDeleteKeyboardEvent(event: KeyboardEvent) {
if(event.key === 'Delete')
{
// remove something...
}
}
Pass bitmap to the saveImage Method, It will save your bitmap in the name of a saveBitmap, inside created test folder.
private void saveImage(Bitmap data) {
File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test");
if(!createFolder.exists())
createFolder.mkdir();
File saveImage = new File(createFolder,"saveBitmap.jpg");
try {
OutputStream outputStream = new FileOutputStream(saveImage);
data.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and use this:
saveImage(bitmap);
If you have the product collection object like:
$collection = Mage::getModel('catalog/product')->getCollection();
Now you can get product sku using $_product->getSku()
if you can't get image path with
echo $this->helper('catalog/image')->init($_product,'small_image')->resize(135);
Or
$_product->getImageUrl();
Then you can add a little code
$productModel = Mage::getModel('catalog/product');
$_prod = $productModel->loadByAttribute('sku', $_product->getSku());
$_prod->getImageUrl();
The way to use the ellipsis or varargs inside the method is as if it were an array:
public void PrintWithEllipsis(String...setOfStrings) {
for (String s : setOfStrings)
System.out.println(s);
}
This method can be called as following:
obj.PrintWithEllipsis(); // prints nothing
obj.PrintWithEllipsis("first"); // prints "first"
obj.PrintWithEllipsis("first", "second"); // prints "first\nsecond"
Inside PrintWithEllipsis
, the type of setOfStrings
is an array of String.
So you could save the compiler some work and pass an array:
String[] argsVar = {"first", "second"};
obj.PrintWithEllipsis(argsVar);
For varargs methods, a sequence parameter is treated as being an array of the same type. So if two signatures differ only in that one declares a sequence and the other an array, as in this example:
void process(String[] s){}
void process(String...s){}
then a compile-time error occurs.
Source: The Java Programming Language specification, where the technical term is variable arity parameter
rather than the common term varargs
.
There is no default value to control deleting old log files created by DailyRollingFileAppender. But you can write your own custom Appender that deletes old log files in much the same way as setting maxBackupIndex does for RollingFileAppender.
Simple instructions found here
From 1:
If you are trying to use the Apache Log4J DailyRollingFileAppender for a daily log file, you may need to want to specify the maximum number of files which should be kept. Just like rolling RollingFileAppender supports maxBackupIndex. But the current version of Log4j (Apache log4j 1.2.16) does not provide any mechanism to delete old log files if you are using DailyRollingFileAppender. I tried to make small modifications in the original version of DailyRollingFileAppender to add maxBackupIndex property. So, it would be possible to clean up old log files which may not be required for future usage.
In case if someone interests to pass data to dialog:
app.controller('ModalCtrl', function($scope, $modal) {
$scope.name = 'theNameHasBeenPassed';
$scope.showModal = function() {
$scope.opts = {
backdrop: true,
backdropClick: true,
dialogFade: false,
keyboard: true,
templateUrl : 'modalContent.html',
controller : ModalInstanceCtrl,
resolve: {} // empty storage
};
$scope.opts.resolve.item = function() {
return angular.copy(
{name: $scope.name}
); // pass name to resolve storage
}
var modalInstance = $modal.open($scope.opts);
modalInstance.result.then(function(){
//on ok button press
},function(){
//on cancel button press
console.log("Modal Closed");
});
};
})
var ModalInstanceCtrl = function($scope, $modalInstance, $modal, item) {
$scope.item = item;
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
Demo Plunker
The blog article is mostly right, but not complete. To have a full understanding of what an odex file does, you have to understand a little about how application files (APK) work.
Applications are basically glorified ZIP archives. The java code is stored in a file called classes.dex and this file is parsed by the Dalvik JVM and a cache of the processed classes.dex file is stored in the phone's Dalvik cache.
An odex is basically a pre-processed version of an application's classes.dex that is execution-ready for Dalvik. When an application is odexed, the classes.dex is removed from the APK archive and it does not write anything to the Dalvik cache. An application that is not odexed ends up with 2 copies of the classes.dex file--the packaged one in the APK, and the processed one in the Dalvik cache. It also takes a little longer to launch the first time since Dalvik has to extract and process the classes.dex file.
If you are building a custom ROM, it's a really good idea to odex both your framework JAR files and the stock apps in order to maximize the internal storage space for user-installed apps. If you want to theme, then simply deodex -> apply your theme -> reodex -> release.
To actually deodex, use small and baksmali:
To add controls dynamically to the form, do the following code. Here we are creating textbox controls to add dynamically.
Public Class Form1
Private m_TextBoxes() As TextBox = {}
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
' Get the index for the new control.
Dim i As Integer = m_TextBoxes.Length
' Make room.
ReDim Preserve m_TextBoxes(i)
' Create and initialize the control.
m_TextBoxes(i) = New TextBox
With m_TextBoxes(i)
.Name = "TextBox" & i.ToString()
If m_TextBoxes.Length < 2 Then
' Position the first one.
.SetBounds(8, 8, 100, 20)
Else
' Position subsequent controls.
.Left = m_TextBoxes(i - 1).Left
.Top = m_TextBoxes(i - 1).Top + m_TextBoxes(i - _
1).Height + 4
.Size = m_TextBoxes(i - 1).Size
End If
' Save the control's index in the Tag property.
' (Or you can get this from the Name.)
.Tag = i
End With
' Give the control an event handler.
AddHandler m_TextBoxes(i).TextChanged, AddressOf TextBox_TextChanged
' Add the control to the form.
Me.Controls.Add(m_TextBoxes(i))
End Sub
'When you enter text in one of the TextBoxes, the TextBox_TextChanged event
'handler displays the control's name and its current text.
Private Sub TextBox_TextChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs)
' Display the current text.
Dim txt As TextBox = DirectCast(sender, TextBox)
Debug.WriteLine(txt.Name & ": [" & txt.Text & "]")
End Sub
End Class
I second Dipaks' answer, but often just the text-indent is enough as you may/maynot be positioning the ul for better layout control.
ul li{
text-indent: -1em;
}
I want to point out one behavior of BackgroundWorker class that wasn't mentioned yet. You can make a normal Thread to run in background by setting the Thread.IsBackground property.
Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. [1]
You can test this behavoir by calling the following method in the constructor of your form window.
void TestBackgroundThread()
{
var thread = new Thread((ThreadStart)delegate()
{
long count = 0;
while (true)
{
count++;
Debug.WriteLine("Thread loop count: " + count);
}
});
// Choose one option:
thread.IsBackground = true; // <--- This will make the thread run in background
thread.IsBackground = false; // <--- This will delay program termination
thread.Start();
}
When the IsBackground property is set to true and you close the window, then your application will terminate normaly.
But when the IsBackground property is set to false (by default) and you close the window, then just the window will disapear but the process will still keep running.
The BackgroundWorker class utilize a Thread that runs in the background.
For PHP 7 in Ubuntu you can also do:
sudo apt-get install php7.0-pgsql
So, now you can do not uncomment lines in php.ini
UPD:
I have a same error, so problem was not in driver.
I changed my database.ini
, but every time I saw an error.
And I change database config in .env
and errors gone.
I spent quite a lot of time figuring out how to do this in Intellij 13x. I apparently never added the properties files to the artifacts that required them, which is a separate step in Intellij. The setup below also works when you have a properties file that is shared by multiple modules.
Great answers. Adding one that loads the color from an Android resources xml but still sets it programmatically:
textView.setTextColor(getResources().getColor(R.color.some_color));
Please note that from API 23, getResources().getColor()
is deprecated. Use instead:
textView.setTextColor(ContextCompat.getColor(context, R.color.some_color));
where the required color is defined in an xml as:
<resources>
<color name="some_color">#bdbdbd</color>
</resources>
Update:
This method was deprecated in API level 23. Use getColor(int, Theme) instead.
Check this.
String s = "having Community Portal|Help Desk|Local Embassy|Reference Desk|Site News";
StringTokenizer st = new StringTokenizer(s, "|");
String community = st.nextToken();
String helpDesk = st.nextToken();
String localEmbassy = st.nextToken();
String referenceDesk = st.nextToken();
String siteNews = st.nextToken();
Used this to convert any String number to double when u need int just convert the data type from num and num2 to int ; took all the cases for any string double with Eng:"Bader Qandeel"
public static double str2doubel(String str) {
double num = 0;
double num2 = 0;
int idForDot = str.indexOf('.');
boolean isNeg = false;
String st;
int start = 0;
int end = str.length();
if (idForDot != -1) {
st = str.substring(0, idForDot);
for (int i = str.length() - 1; i >= idForDot + 1; i--) {
num2 = (num2 + str.charAt(i) - '0') / 10;
}
} else {
st = str;
}
if (st.charAt(0) == '-') {
isNeg = true;
start++;
} else if (st.charAt(0) == '+') {
start++;
}
for (int i = start; i < st.length(); i++) {
if (st.charAt(i) == ',') {
continue;
}
num *= 10;
num += st.charAt(i) - '0';
}
num = num + num2;
if (isNeg) {
num = -1 * num;
}
return num;
}
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
According to Windows Dev Center:
TextBlock.IsTextSelectionEnabled property
[ Updated for UWP apps on Windows 10. For Windows 8.x articles, see the archive ]
Gets or sets a value that indicates whether text selection is enabled in the TextBlock, either through user action or calling selection-related API.
Subset is your safest and easiest answer.
subset(dataframe, A==B & E!=0)
Real data example with mtcars
subset(mtcars, cyl==6 & am!=0)
Another dplyr
possibility could be:
df %>%
group_by(cat) %>%
mutate(num = 1:n())
cat val num
<fct> <dbl> <int>
1 aaa 0.0564 1
2 aaa 0.258 2
3 aaa 0.308 3
4 aaa 0.469 4
5 aaa 0.552 5
6 bbb 0.170 1
7 bbb 0.370 2
8 bbb 0.484 3
9 bbb 0.547 4
10 bbb 0.812 5
11 ccc 0.280 1
12 ccc 0.398 2
13 ccc 0.625 3
14 ccc 0.763 4
15 ccc 0.882 5
A frequent issue when using git:
Laravel's .gitignore ignores the .env file which when missing generates this error
Solved this by manually adding an .env file on the server or uploading it through FTP
Edit/Create an .htaccess
file inside /galerias
with this:
Options -Indexes
Directory browsing is provided by the mod_autoindex module.
Here are implementations from phpjs.org:
This is not my code, I'm just pointing you to a useful resource.
For a Node.js app, in the server.js file before registering all of my own routes, I put the code below. It sets the headers for all responses. It also ends the response gracefully if it is a pre-flight "OPTIONS" call and immediately sends the pre-flight response back to the client without "nexting" (is that a word?) down through the actual business logic routes. Here is my server.js file. Relevant sections highlighted for Stackoverflow use.
// server.js
// ==================
// BASE SETUP
// import the packages we need
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
// ====================================================
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Logger
app.use(morgan('dev'));
// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------
//Set CORS header and intercept "OPTIONS" preflight call from AngularJS
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === "OPTIONS")
res.send(200);
else
next();
}
// -------------------------------------------------------------
// STACKOVERFLOW -- END OF THIS SECTION, ONE MORE SECTION BELOW
// -------------------------------------------------------------
// =================================================
// ROUTES FOR OUR API
var route1 = require("./routes/route1");
var route2 = require("./routes/route2");
var error404 = require("./routes/error404");
// ======================================================
// REGISTER OUR ROUTES with app
// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------
app.use(allowCrossDomain);
// -------------------------------------------------------------
// STACKOVERFLOW -- OK THAT IS THE LAST THING.
// -------------------------------------------------------------
app.use("/api/v1/route1/", route1);
app.use("/api/v1/route2/", route2);
app.use('/', error404);
// =================
// START THE SERVER
var port = process.env.PORT || 8080; // set our port
app.listen(port);
console.log('API Active on port ' + port);
You only need to prefix an if
statement with @
if you're not already inside a razor code block.
Edit: You have a couple of things wrong with your code right now.
You're declaring nmb
, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:
@if (ViewBag.Articles != null)
{
int nmb = 0;
foreach (var item in ViewBag.Articles)
{
if (nmb % 3 == 0)
{
@:<div class="row">
}
<a href="@Url.Action("Article", "Programming", new { id = item.id })">
<div class="tasks">
<div class="col-md-4">
<div class="task important">
<h4>@item.Title</h4>
<div class="tmeta">
<i class="icon-calendar"></i>
@item.DateAdded - Pregleda:@item.Click
<i class="icon-pushpin"></i> Authorrr
</div>
</div>
</div>
</div>
</a>
if (nmb % 3 == 0)
{
@:</div>
}
}
}
The important part here is the @:
. It's a short-hand of <text></text>
, which is used to force the razor engine to render text.
One other thing, the HTML standard specifies that a
tags can only contain inline elements, and right now, you're putting a div
, which is a block-level element, inside an a
.
Thanks for all help at this issue. I'll post here my solution:
Package Header
CREATE OR REPLACE PACKAGE X IS
TYPE exch_row IS RECORD(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);
TYPE exch_tbl IS TABLE OF X.exch_row;
FUNCTION GetExchangeRate RETURN X.exch_tbl PIPELINED;
END X;
Package Body
CREATE OR REPLACE PACKAGE BODY X IS
FUNCTION GetExchangeRate RETURN X.exch_tbl
PIPELINED AS
exch_rt_usd NUMBER := 1.0; --todo
rw exch_row;
BEGIN
FOR rw IN (SELECT c.currency_cd AS currency_cd, e.exch_rt AS exch_rt_eur, (e.exch_rt / exch_rt_usd) AS exch_rt_usd
FROM exch e, currency c
WHERE c.currency_key = e.currency_key
) LOOP
PIPE ROW(rw);
END LOOP;
END;
PROCEDURE DoIt IS
BEGIN
DECLARE
CURSOR c0 IS
SELECT i.DOC,
i.doc_currency,
i.net_value,
i.net_value / rt.exch_rt_usd AS net_value_in_usd,
i.net_value / rt.exch_rt_eur AS net_value_in_euro,
FROM item i, (SELECT * FROM TABLE(X.GetExchangeRate())) rt
WHERE i.doc_currency = rt.currency_cd;
TYPE c0_type IS TABLE OF c0%ROWTYPE;
items c0_type;
BEGIN
OPEN c0;
LOOP
FETCH c0 BULK COLLECT
INTO items LIMIT batchsize;
EXIT WHEN items.COUNT = 0;
FORALL i IN items.FIRST .. items.LAST SAVE EXCEPTIONS
INSERT INTO detail_items VALUES items (i);
END LOOP;
CLOSE c0;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
RAISE;
END;
END;
END X;
Please review.
Is this what you are looking for?
https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant
types is optional
If the file exists and contains data, then it is possible to generate the fieldname
parameter for csv.DictWriter
automatically:
# read header automatically
with open(myFile, "r") as f:
reader = csv.reader(f)
for header in reader:
break
# add row to CSV file
with open(myFile, "a", newline='') as f:
writer = csv.DictWriter(f, fieldnames=header)
writer.writerow(myDict)
Well the code you've shown doesn't actually include adding any Integers to the ArrayList
- but if you do know that you've got integers, you can use:
sum = (double) ((Integer) marks.get(i)).intValue();
That will convert it to an int
, which can then be converted to double
. You can't just cast directly between the boxed classes.
Note that if you can possibly use generics for your ArrayList
, your code will be clearer.
You usually don't want to do this. With Docker Compose you define services that compose your app. npm
and manage.py
are just management commands. You don't need a container for them. If you need to, say create your database tables with manage.py
, all you have to do is:
docker-compose run client python manage.py create_db
Think of it as the one-off dynos Heroku uses.
If you really need to treat these management commands as separate containers (and also use Docker Compose for these), you could create a separate .yml
file and start Docker Compose with the following command:
docker-compose up -f my_custom_docker_compose.yml
You can use the stacking index of the div to make it appear on top of anything else. Make it a larger value that other elements and it well be on top of others.
use z-index
property. See Specifying the stack level: the 'z-index' property and
Elaborate description of Stacking Contexts
Something like
#divOnTop { z-index: 1000; }
<div id="divOnTop">I am on top</div>
What you have to look out for will be IE6. In IE 6 some elements like <select>
will be placed on top of an element with z-index value higher than the <select>
. You can have a workaround for this by placing an <iframe>
behind the div.
See this Internet Explorer z-index bug?
For those using Yarn as their package manager instead of npm:
yarn global add babel-cli
There is no semicolon at the end of that instruction causing the error.
EDIT
Like RiverC pointed out, there is no semicolon at the end of the previous line!
require ("scripts/connect.php")
EDIT
It seems you have no-semicolons whatsoever.
http://php.net/manual/en/language.basic-syntax.instruction-separation.php
As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.
Your statement matches any string that contains a letter or digit anywhere, even if it contains other non-alphanumeric characters. Try this:
SELECT * FROM table WHERE column REGEXP '^[A-Za-z0-9]+$';
^
and $
require the entire string to match rather than just any portion of it, and +
looks for 1 or more alphanumberic characters.
You could also use a named character class if you prefer:
SELECT * FROM table WHERE column REGEXP '^[[:alnum:]]+$';
If json object key/name contains dot......! like
var myJson = {"my.name":"vikas","my.age":27}
Than you can access like
myJson["my.name"]
myJson["my.age"]
Since the answer by @axtavt focuses on JPA
not spring-data-jpa
To update an entity by querying then saving is not efficient because it requires two queries and possibly the query can be quite expensive since it may join other tables and load any collections that have fetchType=FetchType.EAGER
Spring-data-jpa
supports update operation.
You have to define the method in Repository interface.and annotated it with @Query
and @Modifying
.
@Modifying
@Query("update User u set u.firstname = ?1, u.lastname = ?2 where u.id = ?3")
void setUserInfoById(String firstname, String lastname, Integer userId);
@Query
is for defining custom query and @Modifying
is for telling spring-data-jpa
that this query is an update operation and it requires executeUpdate()
not executeQuery()
.
You can specify other return types:
int
- the number of records being updated.
boolean
- true if there is a record being updated. Otherwise, false.
Note: Run this code in a Transaction.
Since event.keyCode is deprecated, I found the event.key useful in javascript. Below is an example for getting the names of the keyboard keys pressed (using an input element). They are given as a KeyboardEvent key text property:
function setMyKeyDownListener() {_x000D_
window.addEventListener(_x000D_
"keydown",_x000D_
function(event) {MyFunction(event.key)}_x000D_
)_x000D_
}_x000D_
_x000D_
function MyFunction (the_Key) {_x000D_
alert("Key pressed is: "+the_Key);_x000D_
}
_x000D_
html { font-size: 4vw; background-color: green; color: white; padding: 1em; }
_x000D_
<body onload="setMyKeyDownListener()">_x000D_
<div>_x000D_
<input id="MyInputId">_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
If you treat the content as text, not HTML, then DOM operations should cause the data to be properly encoded. Here's how you'd do it in jQuery:
$('#container').text(xmlString);
Here's how you'd do it with standard DOM methods:
document.getElementById('container')
.appendChild(document.createTextNode(xmlString));
If you're placing the XML inside of HTML through server-side scripting, there are bound to be encoding functions to allow you to do that (if you add what your server-side technology is, we can give you specific examples of how you'd do it).
If you want to make a server request you should use AJAX, so you can send your desired parameters to the server and it can run whatever php you want with these parameters.
Example with pure javascript:
<input type="text" id="name" value="..."/>
<input type="text" id="location" value="..."/>
<input type="button" onclick="ajaxFunction();" value="Submit" />
<div id="ajaxDiv"></div>
<script type="text/javascript">
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var name = document.getElementById('name').value;
var location = document.getElementById('location').value;
var queryString = "?name=" + name + "&location=" + location;
ajaxRequest.open("POST", "some.php" + queryString, true);
ajaxRequest.send(null);
}
</script>
Example with jQuery Ajax: http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
You can have one file with functions called for example functions.php
functions.php
<?php
myFunction($Name, $Location) {
// etc...
}
myFunction2() {
}
// ... many functions
?>
some.php
<?php include("functions.php");
$Name = $_POST['name'];
$Location = $_POST['location'];
myFunction($Name, $Location);
// make what you want with these variables...?>
Solution for negative values. Adjust the padding-right to move the image.
<div style='overflow:hidden;'>
<div style='width:100% background:url(images.jpg) top right; padding-right:50px;'>
</div>
</div>
You could add to a set
until you reach n
:
setOfNumbers = set()
while len(setOfNumbers) < n:
setOfNumbers.add(random.randint(numLow, numHigh))
Be careful of having a smaller range than will fit in n
. It will loop forever, unable to find new numbers to insert up to n
According to Python Official Documentation, you can force the Garbage Collector to release unreferenced memory with gc.collect()
. Example:
import gc
gc.collect()
I had this problem with Blend for Visual Studio 2015. The Toolbox would just not appear anymore. This turns out to be because Blend is not Visual Studio!
(You can edit your code in Blend and build and run it... It certainly seems like Visual Studio, but it isn't. I'm not sure what the purpose of Blend is...)
You can tell you are in Blend if the task bar icon has big "B" in it. To switch from Blend to Visual Studio, go to View
-> Edit in Visual Studio...
. It will open up another application that looks just like Blend, except the Solution Explorer is on the right instead of the left, and now you have a toolbox...
The postgresql server might be down and the solution might be as simple as running:
sudo service postgresql start
which fixed the issue for me.
To get the value you would do this:
document.getElementById("genderf").value;
But to check, whether the radio button is checked or selected:
document.getElementById("genderf").checked;
I had this issue on a newly created solution that used existing projects. For some reason, one project could not "see" one other project, even though it had the same reference as every other project, and the referenced project was also building. I suspect that it was failing to detect something having to do with multiple target frameworks, because it was building in one framework but not the other.
Cleaning and rebuilding didn't work, and restarting VS didn't work.
What ended up working was opening a "Developer Command Prompt for VS 2019" and then issuing a msbuild MySolution.sln
command. This completed successfully, and afterwards VS started building successfully also.
in your class model (Object) implement Serializable, for Example:
public class MensajesProveedor implements Serializable {
private int idProveedor;
public MensajesProveedor() {
}
public int getIdProveedor() {
return idProveedor;
}
public void setIdProveedor(int idProveedor) {
this.idProveedor = idProveedor;
}
}
and your first Activity
MensajeProveedor mp = new MensajeProveedor();
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("mensajes",mp);
startActivity(i);
and your second Activity (NewActivity)
MensajesProveedor mensajes = (MensajesProveedor)getIntent().getExtras().getSerializable("mensajes");
good luck!!
run this query before creating or altering table.
SET @@global.innodb_large_prefix = 1;
this will set max key length to 3072 bytes
I think I have a shortcut for that:
# Importing datetime.
from datetime import datetime
# Creating a datetime object so we can test.
a = datetime.now()
# Converting a to string in the desired format (YYYYMMDD) using strftime
# and then to int.
a = int(a.strftime('%Y%m%d'))
Please note that you will most likely need an index on that column too.
class AddUserReferenceToTester < ActiveRecord::Migration
def change
add_column :testers, :user_id, :integer
add_index :testers, :user_id
end
end
You need to check your project settings, under C++, check include directories and make sure it points to where GameEngine.h
resides, the other issue could be that GameEngine.h
is not in your source file folder or in any include directory and resides in a different folder relative to your project folder. For instance you have 2 projects ProjectA
and ProjectB
, if you are including GameEngine.h
in some source/header file in ProjectA
then to include it properly, assuming that ProjectB
is in the same parent folder do this:
include "../ProjectB/GameEngine.h"
This is if you have a structure like this:
Root\ProjectA
Root\ProjectB <- GameEngine.h actually lives here
In order to use base_url()
, you must first have the URL Helper loaded. This can be done either in application/config/autoload.php
(on or around line 67):
$autoload['helper'] = array('url');
Or, manually:
$this->load->helper('url');
Once it's loaded, be sure to keep in mind that base_url()
doesn't implicitly print or echo out anything, rather it returns the value to be printed:
echo base_url();
Remember also that the value returned is the site's base url as provided in the config file. CodeIgniter will accomodate an empty value in the config file as well:
If this (base_url) is not set then CodeIgniter will guess the protocol, domain and path to your installation.
application/config/config.php, line 13
static __attribute__ ((noinline)) void foo()
{
}
This is what worked for me.
Expanding Nick Stinemates's answer
class Node(object):
def __init__(self):
self.data = None
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def prepend_node(self, data):
new_node = Node()
new_node.data = data
new_node.next = self.head
self.head = new_node
def append_node(self, data):
new_node = Node()
new_node.data = data
current = self.head
while current.next:
current = current.next
current.next = new_node
def reverse(self):
""" In-place reversal, modifies exiting list"""
previous = None
current_node = self.head
while current_node:
temp = current_node.next
current_node.next = previous
previous = current_node
current_node = temp
self.head = previous
def search(self, data):
current_node = self.head
try:
while current_node.data != data:
current_node = current_node.next
return True
except:
return False
def display(self):
if self.head is None:
print("Linked list is empty")
else:
current_node = self.head
while current_node:
print(current_node.data)
current_node = current_node.next
def list_length(self):
list_length = 0
current_node = self.head
while current_node:
list_length += 1
current_node = current_node.next
return list_length
def main():
linked_list = LinkedList()
linked_list.prepend_node(1)
linked_list.prepend_node(2)
linked_list.prepend_node(3)
linked_list.append_node(24)
linked_list.append_node(25)
linked_list.display()
linked_list.reverse()
linked_list.display()
print(linked_list.search(1))
linked_list.reverse()
linked_list.display()
print("Lenght of singly linked list is: " + str(linked_list.list_length()))
if __name__ == "__main__":
main()
From docs and example it is not clear that classpath manipulation is not allowed.
<configuration>
<compilerArgs>
<arg>classpath=${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
But see Java docs (also https://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/tooldocs/solaris/javac.html)
-classpath path Specifies the path javac uses to look up classes needed to run javac or being referenced by other classes you are compiling. Overrides the default or the CLASSPATH environment variable if it is set.
Maybe it is possible to get current classpath and extend it,
see in maven, how output the classpath being used?
<properties>
<cpfile>cp.txt</cpfile>
</properties>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>build-classpath</id>
<phase>generate-sources</phase>
<goals>
<goal>build-classpath</goal>
</goals>
<configuration>
<outputFile>${cpfile}</outputFile>
</configuration>
</execution>
</executions>
</plugin>
Read file (Read a file into a Maven property)
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>gmaven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<source>
def file = new File(project.properties.cpfile)
project.properties.cp = file.getText()
</source>
</configuration>
</execution>
</executions>
</plugin>
and finally
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<compilerArgs>
<arg>classpath=${cp}:${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
</plugin>
I had a same issue.
from PIL import Image
instead of
import Image
fixed the issue
You could do it like this.
JS
var select = document.getElementById('mySelect');
select.onchange = function () {
select.className = this.options[this.selectedIndex].className;
}
CSS
.redText {
background-color:#F00;
}
.greenText {
background-color:#0F0;
}
.blueText {
background-color:#00F;
}
You could use option { background-color: #FFF; }
if you want the list to be white.
HTML
<select id="mySelect" class="greenText">
<option class="greenText" value="apple" >Apple</option>
<option class="redText" value="banana" >Banana</option>
<option class="blueText" value="grape" >Grape</option>
</select>
Since this is a select
it doesn't really make sense to use .yellowText
as none selected if that's what you were getting at as something must be selected.
These helped me a lot: I wanted to save values from my gridview, and it was reloading my gridview /overriding my new values, as i have IsPostBack inside my PageLoad.
if (HttpContext.Current.Request["MYCLICKEDBUTTONID"] == null)
{
//Do not reload the gridview.
}
else
{
reload my gridview.
}
SOURCE: http://bytes.com/topic/asp-net/answers/312809-please-help-how-identify-button-clicked
This should work, since your state will change after the Ajax call, and the parent component will re-render.
render : function () {
var item;
if (this.state.isRequired) {
item = <MyOwnInput attribute={'whatever'} />
} else {
item = <MyOwnInput />
}
return (
<div>
{item}
</div>
);
}
The cleanest approach is to use the Array#concat method; it will not create a new array (unlike Array#+ which will do the same thing but create a new array).
Straight from the docs (http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-concat):
concat(other_ary)
Appends the elements of other_ary to self.
So
[1,2].concat([3,4]) #=> [1,2,3,4]
Array#concat will not flatten a multidimensional array if it is passed in as an argument. You'll need to handle that separately:
arr= [3,[4,5]]
arr= arr.flatten #=> [3,4,5]
[1,2].concat(arr) #=> [1,2,3,4,5]
Lastly, you can use our corelib gem (https://github.com/corlewsolutions/corelib) which adds useful helpers to the Ruby core classes. In particular we have an Array#add_all method which will automatically flatten multidimensional arrays before executing the concat.
It may help someone as I need to only show selected value, don't need to declare something in component and etc.
If your status is coming from the database then you can show selected value this way.
<div class="form-group">
<label for="status">Status</label>
<select class="form-control" name="status" [(ngModel)]="category.status">
<option [value]="1" [selected]="category.status ==1">Active</option>
<option [value]="0" [selected]="category.status ==0">In Active</option>
</select>
</div>
The problem is that button1 is a local variable. You could do it by just change the way you add the actionListener.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//button is pressed
System.out.println("You clicked the button");
}});
Or you make button1
a global variable.
You can use
$now = new DateTime();
$date = $now->modify('+1 day')->format('Y-m-d H:i:s');
Unfortunately, this does not work on macOS. Despite the fact that I have export CONDA_DEFAULT_ENV='$HOME/anaconda3/envs/dev'
in my .zshrc and "python.pythonPath": "${env.CONDA_DEFAULT_ENV}/bin/python",
in my VSCode prefs, the built-in terminal does not use that environment's Python, even if I have started VSCode from the command line where that variable is set.
For Swift 3, many Foundation
types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString
.
SELECT DATE_FORMAT(somedate, "%d/%m/%Y") AS formatted_date
..........
ORDER BY formatted_date DESC
In some cases, it might be a bad idea to first add the column to the DataGridView and then hide it.
I for example have a class that has an NHibernate proxy for an Image property for company logos. If I accessed that property (e.g. by calling its ToString method to show that in a DataGridView), it would download the image from the SQL server. If I had a list of Company objects and used that as the dataSource of the DataGridView like that, then (I suspect) it would download ALL the logos BEFORE I could hide the column.
To prevent this, I used the custom attribute
[System.ComponentModel.Browsable(false)]
on the image property, so that the DataGridView ignores the property (doesn't create the column and doesn't call the ToString methods).
public class Company
{
...
[System.ComponentModel.Browsable(false)]
virtual public MyImageClass Logo { get; set;}
The eval
is dangerous - you shouldn't execute user input.
If you have 2.6 or newer, use ast instead of eval:
>>> import ast
>>> ast.literal_eval('["A","B" ,"C" ," D"]')
["A", "B", "C", " D"]
Once you have that, strip
the strings.
If you're on an older version of Python, you can get very close to what you want with a simple regular expression:
>>> x='[ "A", " B", "C","D "]'
>>> re.findall(r'"\s*([^"]*?)\s*"', x)
['A', 'B', 'C', 'D']
This isn't as good as the ast solution, for example it doesn't correctly handle escaped quotes in strings. But it's simple, doesn't involve a dangerous eval, and might be good enough for your purpose if you're on an older Python without ast.
I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String)
method where the TraceSource
object was initialised with a string making it a 'named source'.
For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt
. For the following code:
TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
I successfully managed to log with the following diagnostics configuration:
<system.diagnostics>
<sources>
<source name="sourceName" switchName="switchName">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracelog.txt" />
</listeners>
</source>
</sources>
<switches>
<add name="switchName" value="Verbose" />
</switches>
</system.diagnostics>
widthRange.map(function(_, i) { return i });
or
widthRange.map((_, i) => i);
There is a library called BoofCV which claims to better than ZBar and other libraries.
Here are the steps to use that (any OS).
Pre-requisites:
pip install pyboof
Class to decode:
import os
import numpy as np
import pyboof as pb
pb.init_memmap() #Optional
class QR_Extractor:
# Src: github.com/lessthanoptimal/PyBoof/blob/master/examples/qrcode_detect.py
def __init__(self):
self.detector = pb.FactoryFiducial(np.uint8).qrcode()
def extract(self, img_path):
if not os.path.isfile(img_path):
print('File not found:', img_path)
return None
image = pb.load_single_band(img_path, np.uint8)
self.detector.detect(image)
qr_codes = []
for qr in self.detector.detections:
qr_codes.append({
'text': qr.message,
'points': qr.bounds.convert_tuple()
})
return qr_codes
Usage:
qr_scanner = QR_Extractor()
output = qr_scanner.extract('Your-Image.jpg')
print(output)
Tested and works on Python 3.8 (Windows & Ubuntu)
As of Xcode 7 you can turn on Fast, Whole Module Optimization
. This should increase your performance immediately.
It is simplified a lot in version Java 8. I have given some util methods below.
To get the day of the month in the format of
int
for the given day, month, and year.
public static int findDay(final int month, final int day, final int year) {
// System.out.println(LocalDate.of(year, month, day).getDayOfMonth());
return LocalDate.of(year, month, day).getDayOfMonth();
}
To get current day of the month in the format of
int
.
public static int findDay(final int month, final int day, final int year) {
// System.out.println(LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfMonth());
return LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfMonth();
}
To get the day of the week in the format of
String
for the given day, month, and year.
public static String findDay(final int month, final int day, final int year) {
// System.out.println(LocalDate.of(year, month, day).getDayOfWeek());
return LocalDate.of(year, month, day).getDayOfWeek().toString();
}
To get current day of the week in the format of
String
.
public static String findDay(final int month, final int day, final int year) {
// System.out.println(LocalDate.now(ZoneId.of("Asia/Kolkata"))..getDayOfWeek());
return LocalDate.now(ZoneId.of("Asia/Kolkata")).getDayOfWeek().toString();
}
System.Diagnostics.Process.Start( "notepad.exe", "text.txt");
If you are using visual studio code:
This is related to protractor test script execution related and I faced the same issue and it was resolved like this.
Dan Beaulieu's answer in swift5 (also working since swift 3.0.1).
extension DispatchQueue {
static func background(delay: Double = 0.0, background: (()->Void)? = nil, completion: (() -> Void)? = nil) {
DispatchQueue.global(qos: .background).async {
background?()
if let completion = completion {
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
completion()
})
}
}
}
}
DispatchQueue.background(delay: 3.0, background: {
// do something in background
}, completion: {
// when background job finishes, wait 3 seconds and do something in main thread
})
DispatchQueue.background(background: {
// do something in background
}, completion:{
// when background job finished, do something in main thread
})
DispatchQueue.background(delay: 3.0, completion:{
// do something in main thread after 3 seconds
})
Try this python obfuscator:
pyob.oxyry.com pyob.oxyry.c
__all__ = ['foo']
a = 'a'
_b = 'b'
def foo():
print(a)
def bar():
print(_b)
def _baz():
print(a + _b)
foo()
bar()
_baz()
will translated to
__all__ =['foo']#line:1
OO00OO0OO0O00O0OO ='a'#line:3
_O00OO0000OO0O0O0O ='b'#line:4
def foo ():#line:6
print (OO00OO0OO0O00O0OO )#line:7
def O0000000OOOO00OO0 ():#line:9
print (_O00OO0000OO0O0O0O )#line:10
def _OOO00000O000O0OOO ():#line:12
print (OO00OO0OO0O00O0OO +_O00OO0000OO0O0O0O )#line:13
foo ()#line:15
O0000000OOOO00OO0 ()#line:16
_OOO00000O000O0OOO ()#line:17
one of the other tool (besides file) you can use is xdg-mime
eg xdg-mime query filetype <file>
if you have yum,
yum install xdg-utils.noarch
An example comparison of xdg-mime and file on a Subrip(subtitles) file
$ xdg-mime query filetype subtitles.srt
application/x-subrip
$ file --mime-type subtitles.srt
subtitles.srt: text/plain
in the above file only show it as plain text.
The tool that richardtz suggests is excellent.
Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.
You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge
For future reference:
yyyy => 4 digit year
MM => 2 digit month (you must type MM in ALL CAPS)
dd => 2 digit "day of the month"
HH => 2-digit "hour in day" (0 to 23)
mm => 2-digit minute (you must type mm in lowercase)
ss => 2-digit seconds
SSS => milliseconds
So "yyyy-MM-dd HH:mm:ss" returns "2018-01-05 09:49:32"
But "MMM dd, yyyy hh:mm a" returns "Jan 05, 2018 09:49 am"
The so-called examples at https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html show only output. They do not tell you what formats to use!
$ npm uninstall -g angular-cli
$ npm cache clean
$ npm install -g angular-cli
np.count_nonzero(~np.isnan(data))
~
inverts the boolean matrix returned from np.isnan
.
np.count_nonzero
counts values that is not 0\false. .sum
should give the same result. But maybe more clearly to use count_nonzero
Testing speed:
In [23]: data = np.random.random((10000,10000))
In [24]: data[[np.random.random_integers(0,10000, 100)],:][:, [np.random.random_integers(0,99, 100)]] = np.nan
In [25]: %timeit data.size - np.count_nonzero(np.isnan(data))
1 loops, best of 3: 309 ms per loop
In [26]: %timeit np.count_nonzero(~np.isnan(data))
1 loops, best of 3: 345 ms per loop
In [27]: %timeit data.size - np.isnan(data).sum()
1 loops, best of 3: 339 ms per loop
data.size - np.count_nonzero(np.isnan(data))
seems to barely be the fastest here. other data might give different relative speed results.
Sorting with multiple fields in Java8
package com.java8.chapter1;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import static java.util.Comparator.*;
public class Example1 {
public static void main(String[] args) {
List<Employee> empList = getEmpList();
// Before Java 8
empList.sort(new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
int res = o1.getDesignation().compareTo(o2.getDesignation());
if (res == 0) {
return o1.getSalary() > o2.getSalary() ? 1 : o1.getSalary() < o2.getSalary() ? -1 : 0;
} else {
return res;
}
}
});
for (Employee emp : empList) {
System.out.println(emp);
}
System.out.println("---------------------------------------------------------------------------");
// In Java 8
empList.sort(comparing(Employee::getDesignation).thenComparing(Employee::getSalary));
empList.stream().forEach(System.out::println);
}
private static List<Employee> getEmpList() {
return Arrays.asList(new Employee("Lakshman A", "Consultent", 450000),
new Employee("Chaitra S", "Developer", 250000), new Employee("Manoj PVN", "Developer", 250000),
new Employee("Ramesh R", "Developer", 280000), new Employee("Suresh S", "Developer", 270000),
new Employee("Jaishree", "Opearations HR", 350000));
}
}
class Employee {
private String fullName;
private String designation;
private double salary;
public Employee(String fullName, String designation, double salary) {
super();
this.fullName = fullName;
this.designation = designation;
this.salary = salary;
}
public String getFullName() {
return fullName;
}
public String getDesignation() {
return designation;
}
public double getSalary() {
return salary;
}
@Override
public String toString() {
return "Employee [fullName=" + fullName + ", designation=" + designation + ", salary=" + salary + "]";
}
}
You can add a Form and name it as Form1, add a Frame to it as Frame1 as well as Label1 too. Set Frame1 width to 200, Back Color to Blue. Place the code in the module and check if it helps.
Sub Main()
Dim i As Integer
Dim response
Form1.Show vbModeless
Form1.Frame1.Width = 0
For i = 10 To 10000
With Form1
.Label1.Caption = Round(i / 100, 0) & "%"
.Frame1.Width = Round(i / 100, 0) * 2
DoEvents
End With
Next i
Application.Wait Now + 0.0000075
Unload Form1
response = MsgBox("100% Done", vbOKOnly)
End Sub
If you want to display on the Status Bar then you can use other way that's simpler:
Sub Main()
Dim i As Integer
Dim response
For i = 10 To 10000
Application.StatusBar = Round(i / 100, 0) & "%"
Next i
Application.Wait Now + 0.0000075
response = MsgBox("100% Done", vbOKOnly)
End Sub
for disable sorting on any column in datatable use the following
aoColumnDefs: [{ "aTargets": [ 0 ], "bSortable": false}],
it means "aTargets": [ 0 ]
is the column id starting from 0
so in your case it becomes:
$(".tableSort").dataTable({
aaSorting: [[0, 'asc']],
aoColumnDefs: [
{ "aTargets": [ -1 ], "bSortable": false},
]
});
You can add the SVG as background-image
of an empty :after
or :before
.
Here you go:
.anchor:before {
display: block;
content: ' ';
background-image: url('../images/anchor.svg');
background-size: 28px 28px;
height: 28px;
width: 28px;
}
I was looking into this and loved the approach from peege using a for loop! (because I'm learning VBA at the moment)
However, if we are trying to match "any" value of another column, how about using nested loops like the following?
Sub MatchAndColor()
Dim lastRow As Long
Dim sheetName As String
sheetName = "Sheet1" 'Insert your sheet name here
lastRow = Sheets(sheetName).Range("A" & Rows.Count).End(xlUp).Row
For lRowA = 1 To lastRow 'Loop through all rows
For lRowB = 1 To lastRow
If Sheets(sheetName).Cells(lRowA, "A") = Sheets(sheetName).Cells(lRowB, "B") Then
Sheets(sheetName).Cells(lRowA, "A").Interior.ColorIndex = 3 'Set Color to RED
End If
Next lRowB
Next lRowA
End Sub
You can use a Custom SuccessHandler extending SimpleUrlAuthenticationSuccessHandler for redirecting users to different URLs when login according to their assigned roles.
CustomSuccessHandler class provides custom redirect functionality:
package com.mycompany.uomrmsweb.configuration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
System.out.println("Can't redirect");
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication) {
String url="";
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
List<String> roles = new ArrayList<String>();
for (GrantedAuthority a : authorities) {
roles.add(a.getAuthority());
}
if (isStaff(roles)) {
url = "/staff";
} else if (isAdmin(roles)) {
url = "/admin";
} else if (isStudent(roles)) {
url = "/student";
}else if (isUser(roles)) {
url = "/home";
} else {
url="/Access_Denied";
}
return url;
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
private boolean isUser(List<String> roles) {
if (roles.contains("ROLE_USER")) {
return true;
}
return false;
}
private boolean isStudent(List<String> roles) {
if (roles.contains("ROLE_Student")) {
return true;
}
return false;
}
private boolean isAdmin(List<String> roles) {
if (roles.contains("ROLE_SystemAdmin") || roles.contains("ROLE_ExaminationsStaff")) {
return true;
}
return false;
}
private boolean isStaff(List<String> roles) {
if (roles.contains("ROLE_AcademicStaff") || roles.contains("ROLE_UniversityAdmin")) {
return true;
}
return false;
}
}
Extending Spring SimpleUrlAuthenticationSuccessHandler class and overriding handle() method which simply invokes a redirect using configured RedirectStrategy [default in this case] with the URL returned by the user defined determineTargetUrl() method. This method extracts the Roles of currently logged in user from Authentication object and then construct appropriate URL based on there roles. Finally RedirectStrategy , which is responsible for all redirections within Spring Security framework , redirects the request to specified URL.
Registering CustomSuccessHandler using SecurityConfiguration class:
package com.mycompany.uomrmsweb.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
@Autowired
CustomSuccessHandler customSuccessHandler;
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").access("hasRole('USER')")
.antMatchers("/admin/**").access("hasRole('SystemAdmin') or hasRole('ExaminationsStaff')")
.antMatchers("/staff/**").access("hasRole('AcademicStaff') or hasRole('UniversityAdmin')")
.antMatchers("/student/**").access("hasRole('Student')")
.and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
.usernameParameter("username").passwordParameter("password")
.and().csrf()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
successHandler is the class responsible for eventual redirection based on any custom logic, which in this case will be to redirect the user [to student/admin/staff ] based on his role [USER/Student/SystemAdmin/UniversityAdmin/ExaminationsStaff/AcademicStaff].
$<?
$db = sqlite_open('mysqlitedb');
$cols = sqlite_fetch_column_types('form name'$db, SQLITE_ASSOC);
foreach ($cols as $column => $type) {
echo "Column: $column Type: $type\n";
}
No equivalent in the language... Based on IDEs...
For example in netbeans:
NetBeans/Creator supports this syntax:
// <editor-fold defaultstate="collapsed" desc="Your Fold Comment">
...
// </editor-fold>
This is an old topic but still top-ranked Google results and the solutions offered share the same floating point decimals issue. Here is the (very generic) function I use, thanks to MDN:
function round(value, exp) {
if (typeof exp === 'undefined' || +exp === 0)
return Math.round(value);
value = +value;
exp = +exp;
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0))
return NaN;
// Shift
value = value.toString().split('e');
value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp));
}
As we can see, we don't get these issues:
round(1.275, 2); // Returns 1.28
round(1.27499, 2); // Returns 1.27
This genericity also provides some cool stuff:
round(1234.5678, -2); // Returns 1200
round(1.2345678e+2, 2); // Returns 123.46
round("123.45"); // Returns 123
Now, to answer the OP's question, one has to type:
round(10.8034, 2).toFixed(2); // Returns "10.80"
round(10.8, 2).toFixed(2); // Returns "10.80"
Or, for a more concise, less generic function:
function round2Fixed(value) {
value = +value;
if (isNaN(value))
return NaN;
// Shift
value = value.toString().split('e');
value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + 2) : 2)));
// Shift back
value = value.toString().split('e');
return (+(value[0] + 'e' + (value[1] ? (+value[1] - 2) : -2))).toFixed(2);
}
You can call it with:
round2Fixed(10.8034); // Returns "10.80"
round2Fixed(10.8); // Returns "10.80"
Various examples and tests (thanks to @t-j-crowder!):
function round(value, exp) {_x000D_
if (typeof exp === 'undefined' || +exp === 0)_x000D_
return Math.round(value);_x000D_
_x000D_
value = +value;_x000D_
exp = +exp;_x000D_
_x000D_
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0))_x000D_
return NaN;_x000D_
_x000D_
// Shift_x000D_
value = value.toString().split('e');_x000D_
value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)));_x000D_
_x000D_
// Shift back_x000D_
value = value.toString().split('e');_x000D_
return +(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp));_x000D_
}_x000D_
function naive(value, exp) {_x000D_
if (!exp) {_x000D_
return Math.round(value);_x000D_
}_x000D_
var pow = Math.pow(10, exp);_x000D_
return Math.round(value * pow) / pow;_x000D_
}_x000D_
function test(val, places) {_x000D_
subtest(val, places);_x000D_
val = typeof val === "string" ? "-" + val : -val;_x000D_
subtest(val, places);_x000D_
}_x000D_
function subtest(val, places) {_x000D_
var placesOrZero = places || 0;_x000D_
var naiveResult = naive(val, places);_x000D_
var roundResult = round(val, places);_x000D_
if (placesOrZero >= 0) {_x000D_
naiveResult = naiveResult.toFixed(placesOrZero);_x000D_
roundResult = roundResult.toFixed(placesOrZero);_x000D_
} else {_x000D_
naiveResult = naiveResult.toString();_x000D_
roundResult = roundResult.toString();_x000D_
}_x000D_
$("<tr>")_x000D_
.append($("<td>").text(JSON.stringify(val)))_x000D_
.append($("<td>").text(placesOrZero))_x000D_
.append($("<td>").text(naiveResult))_x000D_
.append($("<td>").text(roundResult))_x000D_
.appendTo("#results");_x000D_
}_x000D_
test(0.565, 2);_x000D_
test(0.575, 2);_x000D_
test(0.585, 2);_x000D_
test(1.275, 2);_x000D_
test(1.27499, 2);_x000D_
test(1234.5678, -2);_x000D_
test(1.2345678e+2, 2);_x000D_
test("123.45");_x000D_
test(10.8034, 2);_x000D_
test(10.8, 2);_x000D_
test(1.005, 2);_x000D_
test(1.0005, 2);
_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
table, td, th {_x000D_
border: 1px solid #ddd;_x000D_
}_x000D_
td, th {_x000D_
padding: 4px;_x000D_
}_x000D_
th {_x000D_
font-weight: normal;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
td {_x000D_
font-family: monospace;_x000D_
}
_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Input</th>_x000D_
<th>Places</th>_x000D_
<th>Naive</th>_x000D_
<th>Thorough</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody id="results">_x000D_
</tbody>_x000D_
</table>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
In comparisons it makes a difference if a scalar is a number of a string. And it is not always decidable. I can report a case where perl retrieved a float in "scientific" notation and used that same a few lines below in a comparison:
use strict;
....
next unless $line =~ /and your result is:\s*(.*)/;
my $val = $1;
if ($val < 0.001) {
print "this is small\n";
}
And here $val
was not interpreted as numeric for e.g. "2e-77"
retrieved from $line
. Adding 0 (or 0.0 for good ole C programmers) helped.
I needed to have a button handler that created a form post to another application within the client's browser. I landed on this question but didn't see an answer that suited my scenario. This is what I came up with:
protected void Button1_Click(object sender, EventArgs e)
{
var formPostText = @"<html><body><div>
<form method=""POST"" action=""OtherLogin.aspx"" name=""frm2Post"">
<input type=""hidden"" name=""field1"" value=""" + TextBox1.Text + @""" />
<input type=""hidden"" name=""field2"" value=""" + TextBox2.Text + @""" />
</form></div><script type=""text/javascript"">document.frm2Post.submit();</script></body></html>
";
Response.Write(formPostText);
}
Check whether the jars are imported properly. I imported them using build path. But it didn't recognise the jar in WAR/lib folder. Later, I copied the same jar to war/lib folder. It works fine now. You can refresh / clean your project.
I use ­
, inserted manually where necessary.
I always find it a pity that people don’t use techniques because there is some—maybe old or strange—browser around which doesn’t handle them the way they were specified. I found that ­
is working properly in both recent Internet Explorer and Firefox browsers, that should be enough. You may include a browser check telling people to use something mature or continue at their own risk if they come around with some strange browser.
Syllabification isn’t that easy and I cannot recommend leaving it to some Javascript. It’s a language specific topic and may need to be carefully revised by the deskman if you don’t want it to turn your text irritating. Some languages, such as German, form compound words and are likely to lead to decomposition problems. E.g. Spargelder
(germ. saved money, pl.) may, by syllabification rules, be wrapped in two places (Spar-gel-der
). However, wrapping it in the second position, turns the first part to show up as Spargel-
(germ. asparagus), activating a completely misleading concept in the head of the reader and therefore shoud be avoided.
And what about the string Wachstube
? It could either mean ‘guardroom’ (Wach-stu-be
) or ‘tube of wax’ (Wachs-tu-be
). You may probably find other examples in other languages as well. You should aim to provide an environment in which the deskman can be supported in creating a well-syllabified text, proof-reading every critical word.
Assuming the question is about cleaning the workspace of the current job, you can run:
test -n "$WORKSPACE" && rm -rf "$WORKSPACE"/*
icacls . /grant John:(OI)(CI)F /T
where John is the usernameJust adding this because it seemed supremely easy this way and others may profit - all credit goes to Calin Darie
.
I did it! Using <intent-filter>
. Put the following into your manifest file:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>
This works perfectly!
Take a look at UnCSS. It helps in creating a CSS file of used CSS.
Write a simple server python server listening on a port (say 8080), bind the port -p 8080:8080 with the container, make a HTTP request to localhost:8080 to ask the python server running shell scripts with popen, run a curl or writing code to make a HTTP request curl -d '{"foo":"bar"}' localhost:8080
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import subprocess
import json
PORT_NUMBER = 8080
# This class will handles any incoming request from
# the browser
class myHandler(BaseHTTPRequestHandler):
def do_POST(self):
content_len = int(self.headers.getheader('content-length'))
post_body = self.rfile.read(content_len)
self.send_response(200)
self.end_headers()
data = json.loads(post_body)
# Use the post data
cmd = "your shell cmd"
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
(output, err) = p.communicate()
print "Command output : ", output
print "Command exit status/return code : ", p_status
self.wfile.write(cmd + "\n")
return
try:
# Create a web server and define the handler to manage the
# incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
# Wait forever for incoming http requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
With this command I had poor image quality
ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -vcodec copy -acodec copy -f mp4 -y MyVideoFFmpeg.mp4
With this, almost without delay, I got good image quality.
ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -b 900k -vcodec copy -r 60 -y MyVdeoFFmpeg.avi
For those have same problem in Grails ckeditor plugin Give
filebrowserUploadUrl:'/YourAppName/ck/ofm'
to invoke the function that handles image uploade.if you want use your own customized function you can give that file path.
Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.
Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.
I'm using .Net Core 2 mvc, this one work for me ( to get the previews page) :
HttpContext.Request.Headers["Referer"];
Here is a snippet from me in testing... obviously passing via get to the script may not be the best... should post or just send an id and grab guid from db... anyhow.. this worked. I take the URL and convert it to a path.
// Initialize a file URL to the variable
$file = $_GET['url'];
$file = str_replace(Polepluginforrvms_Plugin::$install_url, $DOC_ROOT.'/pole-permitter/', $file );
$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size = filesize($file);
header( "Content-type: application/octet-stream" );
header( "Content-Disposition: attachment; filename={$quoted}" );
header( "Content-length: " . $size );
header( "Pragma: no-cache" );
header( "Expires: 0" );
readfile( "{$file}" );
Using a single PowerShell command to retrieve the file ending:
powershell -nologo "& "Get-Content -Wait c:\logFile.log -Tail 10"
It applies to PowerShell 3.0 and newer.
Another option is to create a file called TAIL.CMD with this code:
powershell -nologo "& "Get-Content -Wait %1 -Tail %2"
Hi i tried to integrate with your code.
Can you have a look at this?
Thanks M.S
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<!--TODO: need to integrate this code into the project to change images added 05/21/2016:-->_x000D_
_x000D_
<script type="text/javascript">_x000D_
function changeImage(a) {_x000D_
document.getElementById("img").src=a;_x000D_
}_x000D_
</script>_x000D_
_x000D_
_x000D_
_x000D_
<title> Fluid Selection </title>_x000D_
<!-- css -->_x000D_
<link rel="stylesheet" href="bootstrap-3/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="css/main.css">_x000D_
<!-- end css -->_x000D_
<!-- Java script files -->_x000D_
<!-- Date.js date os javascript helper -->_x000D_
<script src="js/date.js"> </script>_x000D_
_x000D_
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->_x000D_
<script src="js/jquery-2.1.1.min.js"></script>_x000D_
_x000D_
<!-- Include all compiled plugins (below), or include individual files as needed -->_x000D_
<script src="bootstrap-3/js/bootstrap.min.js"> </script>_x000D_
<script src="js/library.js"> </script>_x000D_
<script src="js/sfds.js"> </script>_x000D_
<script src="js/main.js"> </script>_x000D_
_x000D_
<!-- End Java script files -->_x000D_
_x000D_
<!--added on 05/28/2016-->_x000D_
_x000D_
<style>_x000D_
/* The Modal (background) */_x000D_
.modal {_x000D_
display: none; /* Hidden by default */_x000D_
position: fixed; /* Stay in place */_x000D_
z-index:40001; /* High z-index to ensure it appears above all content */ _x000D_
padding-top: 100px; /* Location of the box */_x000D_
left: 0;_x000D_
top: 0;_x000D_
width: 100%; /* Full width */_x000D_
height: 100%; /* Full height */_x000D_
overflow: auto; /* Enable scroll if needed */_x000D_
_x000D_
background-color: rgba(0,0,0,0.9); /* Black w/ opacity */_x000D_
}_x000D_
_x000D_
/* Modal Content */_x000D_
.modal-content {_x000D_
position: relative;_x000D_
background-color: #fefefe;_x000D_
margin: auto;_x000D_
padding: 0;_x000D_
border: 1px solid #888;_x000D_
width: 40%;_x000D_
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);_x000D_
-webkit-animation-name: animatetop;_x000D_
-webkit-animation-duration: 0.4s;_x000D_
animation-name: animatetop;_x000D_
animation-duration: 0.4s_x000D_
opacity:.5; /* Sets opacity so it's partly transparent */ -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; _x000D_
/* IE _x000D_
transparency */ filter:alpha(opacity=50); /* More IE transparency */ z-index:40001; } _x000D_
}_x000D_
_x000D_
/* Add Animation */_x000D_
@-webkit-keyframes animatetop {_x000D_
from {top:-300px; opacity:0} _x000D_
to {top:0; opacity:1}_x000D_
}_x000D_
_x000D_
@keyframes animatetop {_x000D_
from {top:-300px; opacity:0}_x000D_
to {top:0; opacity:1}_x000D_
}_x000D_
_x000D_
/* The Close Button */_x000D_
.close {_x000D_
_x000D_
}_x000D_
_x000D_
.close:hover,_x000D_
.close:focus {_x000D_
color: #000;_x000D_
text-decoration: none;_x000D_
cursor:pointer;_x000D_
}_x000D_
_x000D_
/* The Close Button */_x000D_
.close2 {_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
.close2:focus {_x000D_
color: #000;_x000D_
text-decoration: none;_x000D_
cursor:pointer;_x000D_
}_x000D_
_x000D_
.modal-header {_x000D_
color: #000;_x000D_
padding: 2px 16px;_x000D_
}_x000D_
_x000D_
.modal-body {padding: 2px 16px;}_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
.modal-footer {_x000D_
padding: 2px 16px;_x000D_
background-color: #000099;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
_x000D_
</style>_x000D_
_x000D_
<script>_x000D_
$(document).ready(function() {_x000D_
_x000D_
_x000D_
$("#water").click(function(event){_x000D_
var $this= $(this);_x000D_
if($this.hasClass('clicked')){_x000D_
$this.removeClass('clicked');_x000D_
SFDS.setFluidType(0);_x000D_
$this.find('h3').text('Select the H20 Fluid Type');_x000D_
}else{_x000D_
SFDS.setFluidType(1);_x000D_
$this.addClass('clicked');_x000D_
$this.find('h3').text('H20 Selected');_x000D_
_x000D_
}_x000D_
});_x000D_
_x000D_
$("#saline").click(function(event){_x000D_
var $this= $(this);_x000D_
if($this.hasClass('clicked')){_x000D_
$this.removeClass('clicked');_x000D_
SFDS.setFluidType(0);_x000D_
$this.find('h3').text('Select the NaCL Fluid Type');_x000D_
}else{_x000D_
SFDS.setFluidType(1);_x000D_
$this.addClass('clicked');_x000D_
$this.find('h3').text('NaCL Selected');_x000D_
_x000D_
_x000D_
_x000D_
}_x000D_
});_x000D_
_x000D_
});_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<div class="container-fluid">_x000D_
<header>_x000D_
<div class="row">_x000D_
<div class="col-xs-6">_x000D_
<div id="date"><span class="date_time"></span></div>_x000D_
</div>_x000D_
<div class="col-xs-6">_x000D_
<div id="time" class="text-right"><span class="date_time"></span></div>_x000D_
</div>_x000D_
</div>_x000D_
</header>_x000D_
_x000D_
<div class="row">_x000D_
<div class="col-md-offset-1 col-sm-3 col-xs-8 col-xs-offset-2 col-sm-offset-0">_x000D_
<div id="fluid" class="main_button center-block">_x000D_
<div class="large_circle_button, main_img"> _x000D_
<h2>Select<br>Fluid</h2>_x000D_
<img class="center-block large_button_image" src="images/dropwater.png" alt=""/> _x000D_
</div>_x000D_
<h1></h1>_x000D_
</div>_x000D_
</div>_x000D_
<div class=" col-md-6 col-sm-offset-1 col-sm-8 col-xs-12">_x000D_
<div class="row">_x000D_
<div class="col-xs-12">_x000D_
<div id="water" class="large_rectangle_button">_x000D_
<div class="label_wrapper">_x000D_
<h3>Sterile<br>Water</h3>_x000D_
</div>_x000D_
<div id="thumb_img" class="image_wrapper">_x000D_
<img src="images/dropsterilewater.png" alt="Sterile Water" class="sterile_water_image" onclick='changeImage("images/dropsterilewater.png");'>_x000D_
</div>_x000D_
<img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-xs-12">_x000D_
<div id="saline" class="large_rectangle_button">_x000D_
<div class="label_wrapper">_x000D_
<h3>Sterile<br>0.9% NaCL</h3>_x000D_
</div>_x000D_
<div class="image_wrapper">_x000D_
<img src="images/cansterilesaline.png" alt= "Sterile Saline" class="sterile_salt_image" onclick='changeImage("images/imagecansterilesaline.png");'>_x000D_
</div>_x000D_
<img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-xs-12">_x000D_
<div class="small_rectangle_button">_x000D_
_x000D_
<!-- Trigger/Open The Modal -->_x000D_
<div id="myBtn" class="label_wrapper">_x000D_
<h3>Change<br>Cartridge</h3>_x000D_
</div>_x000D_
<div class="image_wrapper">_x000D_
<img src="images/changecartridge.png" alt="" class="change_cartrige_image" />_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<!-- The Modal -->_x000D_
<div id="myModal" class="modal">_x000D_
_x000D_
<!-- Modal content -->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<span class="close"><img src="images/x-icon.png"></span>_x000D_
<h2>Change Cartridge Instructions</h2>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<h4>Lorem ipsum dolor sit amet, dicant nonumes volutpat cu eum, in nulla molestie vim, nec probo option iracundia ut. Tale inermis scripserit ne cum, his no errem minimum commune, usu accumsan omnesque in. Eu has nihil dolor debitis, ad nobis impedit per. Dicat mnesarchum quo at, debet abhorreant consectetuer sea te, postea adversarium et eos. At alii dicit his, liber tantas suscipit sea in, id pri erat probatus. Vel nostro periculis dissentiet te, ut ubique noster vix. Id honestatis disputationi vel, ne vix assum constituam.</h4> _x000D_
<a href="#"><img src="images/video-icon.png" alt="click here for video"> </a>_x000D_
<a href="#close2" title="Close" class="close2"><img src="images/cancel-icon.png" alt="Cancel"></a>_x000D_
_x000D_
_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<h4></h4>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<!--for comparison-->_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
<script>_x000D_
// Get the modal_x000D_
var modal = document.getElementById('myModal');_x000D_
_x000D_
// Get the button that opens the modal_x000D_
var btn = document.getElementById("myBtn");_x000D_
_x000D_
// Get the <span> element that closes the modal_x000D_
var span = document.getElementsByClassName("close")[0];_x000D_
_x000D_
_x000D_
// When the user clicks the button, open the modal _x000D_
btn.onclick = function() {_x000D_
modal.style.display = "block";_x000D_
}_x000D_
_x000D_
// When the user clicks on <span> (x), close the modal_x000D_
span.onclick = function() {_x000D_
modal.style.display = "none";_x000D_
}_x000D_
_x000D_
// When the user clicks anywhere outside of the modal, close it_x000D_
window.onclick = function(event) {_x000D_
if (event.target == modal) {_x000D_
modal.style.display = "none";_x000D_
}_x000D_
_x000D_
_x000D_
}_x000D_
</script>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<footer class="footer navbar-fixed-bottom">_x000D_
<div class="container-fluid">_x000D_
<div class="row cols-bottom">_x000D_
<div class="col-sm-3">_x000D_
<a href="main.html">_x000D_
<div class="small_circle_button"> _x000D_
<img src="images/buttonback.png" alt="back to home" class="settings"/> <!-- width="49" height="48" -->_x000D_
</div>_x000D_
</div></a><div class=" col-sm-6">_x000D_
<div id="stop_button" >_x000D_
<img src="images/stop.png" alt="stop" class="center-block stop_button" /> <!-- width="140" height="128" -->_x000D_
</div>_x000D_
_x000D_
</div><div class="col-sm-3">_x000D_
<div id="parker" class="pull-right">_x000D_
<img src="images/parkerlogo.png" alt="parkerlogo" /> <!-- width="131" height="65" -->_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</footer>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
You have 2 different versions of JSON.NET library in your solution. To solve this you should upgrade them to latest version. Follow these steps:
1-Open solution explorer 2-Right Click on solution name 3-Select Manage Nuget Packages for Solution 4-Select Updates from menu 5-Update JSON.NET package
This will resolve your issue.
After a few futile hours battling with a 'SyntaxError: missing : after property id' message I can now expand on this topic:
border-width is a valid css property but it is not included in the jQuery css oject definition, so .css({border-width: '2px'}) will cause an error, but it's quite happy with .css({'border-width': '2px'}), presumably property names in quotes are just passed on as received.
I solved the problem by adding the line skip-grant-tables
to the my.ini:
# The MySQL server
[mysqld]
skip-grant-tables
port= 3306
...
Under XAMPP Control Panel > Section "MySQL" > Config > my.ini
One of the goals of compilers is to rule out classes of errors. Some unreachable code is there by accident, it's nice that javac rules out that class of error at compile time.
For every rule that catches erroneous code, someone will want the compiler to accept it because they know what they're doing. That's the penalty of compiler checking, and getting the balance right is one of the tricker points of language design. Even with the strictest checking there's still an infinite number of programs that can be written, so things can't be that bad.
I wrote this simple code that is testing localStorage size in bytes.
https://github.com/gkucmierz/Test-of-localStorage-limits-quota
const check = bytes => {
try {
localStorage.clear();
localStorage.setItem('a', '0'.repeat(bytes));
localStorage.clear();
return true;
} catch(e) {
localStorage.clear();
return false;
}
};
Github pages:
https://gkucmierz.github.io/Test-of-localStorage-limits-quota/
I have the same results on desktop chrome, opera, firefox, brave and mobile chrome which is ~5Mbytes
And half smaller result in safari ~2Mbytes
UNIQUE
constraint (of which a PRIMARY KEY
constraint is a variant). Checks that all values of a given field are unique across the table. This is X
-axis constraint (records)
CHECK
constraint (of which a NOT NULL
constraint is a variant). Checks that a certain condition holds for the expression over the fields of the same record. This is Y
-axis constraint (fields)
FOREIGN KEY
constraint. Checks that a field's value is found among the values of a field in another table. This is Z
-axis constraint (tables).
If you install the "cssnext" Post CSS plugin, then you can safely start using the syntax that you want to use right now.
Using cssnext will turn this:
input:not([type="radio"], [type="checkbox"]) {
/* css here */
}
Into this:
input:not([type="radio"]):not([type="checkbox"]) {
/* css here */
}
Pass address of a function as parameter to another function as shown below
#include <stdio.h>
void print();
void execute(void());
int main()
{
execute(print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void f()) // receive address of print
{
f();
}
Also we can pass function as parameter using function pointer
#include <stdio.h>
void print();
void execute(void (*f)());
int main()
{
execute(&print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void (*f)()) // receive address of print
{
f();
}
You could also use GenerationType.TABLE instead of IDENTITY which is only available after the insert.
Always use std::copy
because memcpy
is limited to only C-style POD structures, and the compiler will likely replace calls to std::copy
with memcpy
if the targets are in fact POD.
Plus, std::copy
can be used with many iterator types, not just pointers. std::copy
is more flexible for no performance loss and is the clear winner.
There's been some great answers, but, with many people using regex to find the word, but, for some reason, nobody else uses regex to replace the first character. For explanation, I'll provide a long solution and a shorter one.
The long solution (more explanatory). By using regular expression [^\s_\-/]*
we can find every word in the sentence. Subsequently, we can use the regular expression .
to match to the first character in a word. Using the regular expression version of replace for both of these, we can change the solution like this:
function toUpperCase(str) { return str.toUpperCase(); }_x000D_
function capitalizeWord(word) { return word.replace(/./, toUpperCase); }_x000D_
function capitalize(sentence) { return sentence.toLowerCase().replace(/[^\s_\-/]*/g, capitalizeWord); }_x000D_
_x000D_
console.log(capitalize("hello world")); // Outputs: Hello World
_x000D_
For a single function that does the same thing, we nest the replace
calls as follows:
function capitalize(sentence) {_x000D_
return sentence.toLowerCase().replace(/[^\s_\-/]*/g, function (word) {_x000D_
return word.replace(/./, function (ch) { return ch.toUpperCase(); } );_x000D_
} );_x000D_
}_x000D_
_x000D_
console.log(capitalize("hello world")); // Outputs: Hello World
_x000D_
The only way to add any book marks in MobileSafari (including ones on the home screen) is with the builtin UI, and that Apples does not provide anyway to do this from scripts within a page. In fact, I am pretty sure there is no mechanism for doing this on the desktop version of Safari either.
Just like everyone else said, you can't control border height. But there are workarounds, here's what I do:
table {
position: relative;
}
table::before { /* ::after works too */
content: "";
position: absolute;
right: 0; /* Change direction for a different side*/
z-index: 100;
width: 3px; /* Thickness */
height: 10px;
background: #555; /* Color */
}
You can set height
to inherit
for the height of the table or calc(inherit - 2px)
for a 2px smaller border.
Remember, inherit
has no effect when the table height isn't set.
Use height: 50%
for half a border.
Use this code "./" as root on the server as it works for me
<a href="./fruits/index.html">Back to Fruits List</a>
but when you are on a local machine use the following code "../" as the root relative path
<a href="../fruits/index.html">Back to Fruits List</a>
Ok Check and Add to Watch:
Now you can see a list of all SubKey with its validation state at end of value.
So search for the Invalid value.
For those of us accomplishing this with Angular JS, I used a directive
HTML:
<textarea elastic ng-model="someProperty"></textarea>
JS:
.directive('elastic', [
'$timeout',
function($timeout) {
return {
restrict: 'A',
link: function($scope, element) {
$scope.initialHeight = $scope.initialHeight || element[0].style.height;
var resize = function() {
element[0].style.height = $scope.initialHeight;
element[0].style.height = "" + element[0].scrollHeight + "px";
};
element.on("input change", resize);
$timeout(resize, 0);
}
};
}
]);
$timeout
queues an event that will fire after the DOM loads, which is what's necessary to get the right scrollHeight (otherwise you'll get undefined
)
Well, yes, and no...
I understand that you want your local copies to "override" what's in the remote, but, oh, man, if someone has modified the files in the remote repo in some different way, and you just ignore their changes and try to "force" your own changes without even looking at possible conflicts, well, I weep for you (and your coworkers) ;-)
That said, though, it's really easy to do the "right thing..."
Step 1:
git stash
in your local repo. That will save away your local updates into the stash, then revert your modified files back to their pre-edit state.
Step 2:
git pull
to get any modified versions. Now, hopefully, that won't get any new versions of the files you're worried about. If it doesn't, then the next step will work smoothly. If it does, then you've got some work to do, and you'll be glad you did.
Step 3:
git stash pop
That will merge your modified versions that you stashed away in Step 1 with the versions you just pulled in Step 2. If everything goes smoothly, then you'll be all set!
If, on the other hand, there were real conflicts between what you pulled in Step 2 and your modifications (due to someone else editing in the interim), you'll find out and be told to resolve them. Do it.
Things will work out much better this way - it will probably keep your changes without any real work on your part, while alerting you to serious, serious issues.
What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.
A session is a chunk of data maintained at the server that maintains state between HTTP requests. HTTP is fundamentally a stateless protocol; sessions are used to give it statefulness.
A cookie is a snippet of data sent to and returned from clients. Cookies are often used to facilitate sessions since it tells the server which client handled which session. There are other ways to do this (query string magic etc) but cookies are likely most common for this.
Add the following css to your html and try changing the top, right, bottom, left values.
.modal {
position: absolute;
top: 10px;
right: 100px;
bottom: 0;
left: 0;
z-index: 10040;
overflow: auto;
overflow-y: auto;
}
If you're willing to use a Volume and a ConfigMap, you can mount ConfigMap data as a script, and then run that script:
---
apiVersion: v1
kind: ConfigMap
metadata:
name: my-configmap
data:
entrypoint.sh: |-
#!/bin/bash
echo "Do this"
echo "Do that"
---
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: "ubuntu:14.04"
command:
- /bin/entrypoint.sh
volumeMounts:
- name: configmap-volume
mountPath: /bin/entrypoint.sh
readOnly: true
subPath: entrypoint.sh
volumes:
- name: configmap-volume
configMap:
defaultMode: 0700
name: my-configmap
This cleans up your pod spec a little and allows for more complex scripting.
$ kubectl logs my-pod
Do this
Do that
I assume that with interface you mean a C++ class with only pure virtual methods (i.e. without any code), instead with abstract class you mean a C++ class with virtual methods that can be overridden, and some code, but at least one pure virtual method that makes the class not instantiable. e.g.:
class MyInterface
{
public:
// Empty virtual destructor for proper cleanup
virtual ~MyInterface() {}
virtual void Method1() = 0;
virtual void Method2() = 0;
};
class MyAbstractClass
{
public:
virtual ~MyAbstractClass();
virtual void Method1();
virtual void Method2();
void Method3();
virtual void Method4() = 0; // make MyAbstractClass not instantiable
};
In Windows programming, interfaces are fundamental in COM. In fact, a COM component exports only interfaces (i.e. pointers to v-tables, i.e. pointers to set of function pointers). This helps defining an ABI (Application Binary Interface) that makes it possible to e.g. build a COM component in C++ and use it in Visual Basic, or build a COM component in C and use it in C++, or build a COM component with Visual C++ version X and use it with Visual C++ version Y. In other words, with interfaces you have high decoupling between client code and server code.
Moreover, when you want to build DLL's with a C++ object-oriented interface (instead of pure C DLL's), as described in this article, it's better to export interfaces (the "mature approach") instead of C++ classes (this is basically what COM does, but without the burden of COM infrastructure).
I'd use an interface if I want to define a set of rules using which a component can be programmed, without specifying a concrete particular behavior. Classes that implement this interface will provide some concrete behavior themselves.
Instead, I'd use an abstract class when I want to provide some default infrastructure code and behavior, and make it possible to client code to derive from this abstract class, overriding the pure virtual methods with some custom code, and complete this behavior with custom code. Think for example of an infrastructure for an OpenGL application. You can define an abstract class that initializes OpenGL, sets up the window environment, etc. and then you can derive from this class and implement custom code for e.g. the rendering process and handling user input:
// Abstract class for an OpenGL app.
// Creates rendering window, initializes OpenGL;
// client code must derive from it
// and implement rendering and user input.
class OpenGLApp
{
public:
OpenGLApp();
virtual ~OpenGLApp();
...
// Run the app
void Run();
// <---- This behavior must be implemented by the client ---->
// Rendering
virtual void Render() = 0;
// Handle user input
// (returns false to quit, true to continue looping)
virtual bool HandleInput() = 0;
// <--------------------------------------------------------->
private:
//
// Some infrastructure code
//
...
void CreateRenderingWindow();
void CreateOpenGLContext();
void SwapBuffers();
};
class MyOpenGLDemo : public OpenGLApp
{
public:
MyOpenGLDemo();
virtual ~MyOpenGLDemo();
// Rendering
virtual void Render(); // implements rendering code
// Handle user input
virtual bool HandleInput(); // implements user input handling
// ... some other stuff
};
public function testException() {
try {
$this->methodThatThrowsException();
$this->fail("Expected Exception has not been raised.");
} catch (Exception $ex) {
$this->assertEquals($ex->getMessage(), "Exception message");
}
}
<%= csrf_meta_tag %>
in your layoutbeforeSend
to include the csrf-token in the ajax request to set the header. This is only required for post
requests.The code to read the csrf-token is available in the rails/jquery-ujs
, so imho it is easiest to just use that, as follows:
$.ajax({
url: url,
method: 'post',
beforeSend: $.rails.CSRFProtection,
data: {
// ...
}
})
No, you must have an Intel Mac of some sort. I went to Best Buy and got a 24" iMac with 4G RAM for $1499 using their 18 month no interest promotion. I pay a minimum payment of something like $16 a month. As long as I pay the entire thing off within 18 months - no interest. That was the only way I was getting into iPhone development.
You could try writing the XDocument to an XmlWriter piped to an XmlReader for an XmlDocument.
If I understand the concepts properly, a direct conversion is not possible (the internal structure is different / simplified with XDocument). But then, I might be wrong...
In my case i have included jdbc api dependencies in the project so the "Hello World" not printed. After removing the below dependency it works like a charm.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
If you have start-stop-daemon
start-stop-daemon --start --quiet -u username -g usergroup --exec command ...
This is caused by a gradle dependency on some out-of-date thing which causes the error. Remove gradle dependencies until the error stops appearing. For me, it was:
implementation 'org.apache.directory.studio:org.apache.commons.io:2.4'
This line needed to be updated to a newer version such as:
api group: 'commons-io', name: 'commons-io', version: '2.6'
You can just use the return value of require
:
if(!require(somepackage)){
install.packages("somepackage")
library(somepackage)
}
I use library
after the install because it will throw an exception if the install wasn't successful or the package can't be loaded for some other reason. You make this more robust and reuseable:
dynamic_require <- function(package){
if(eval(parse(text=paste("require(",package,")")))) return True
install.packages(package)
return eval(parse(text=paste("require(",package,")")))
}
The downside to this method is that you have to pass the package name in quotes, which you don't do for the real require
.
Since ES6, you can use template literals:
const age = 3_x000D_
console.log(`I'm ${age} years old!`)
_x000D_
P.S. Note the use of backticks: ``
.
Just in case, to check variables you can use
$> mysqladmin variables -u user -p
This will display the current variables, in this case max_allowed_packet, and as someone said in another answer you can set it temporarily with
mysql> SET GLOBAL max_allowed_packet=1072731894
In my case the cnf file was not taken into account and I don't know why, so the SET GLOBAL code really helped.
Assuming you're using bash
#!/bin/bash
current_dir=$(pwd)
script_dir=$(dirname "$0")
echo $current_dir
echo $script_dir
This script should print the directory that you're in, and then the directory the script is in. For example, when calling it from /
with the script in /home/mez/
, it outputs
/
/home/mez
Remember, when assigning variables from the output of a command, wrap the command in $(
and )
- or you won't get the desired output.
All above information is correct, I'd also like to point out that the [AcceptVerbs()]
annotation exists in both the System.Web.Mvc and System.Web.Http namespaces.
You want to use the System.Web.Http if it's a Web API controller.
var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;
function changeIframe() {
$('#frame')[0].src = sites[index++];
index = index >= sites.length ? 0 : index;
}
An example of using logging.basicConfig
rather than logging.fileHandler()
logging.basicConfig(filename=logname,
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logging.info("Running Urban Planning")
self.logger = logging.getLogger('urbanGUI')
In order, the five parts do the following:
filename=logname
)filemode='a'
)format=...
)datefmt='%H:%M:%S'
)level=logging.DEBUG
).This is best practice
$("input[name='radioGroup']:checked").val()
make
in, and off itself, handles directory targets just the same as file targets. So, it's easy to write rules like this:
outDir/someTarget: Makefile outDir
touch outDir/someTarget
outDir:
mkdir -p outDir
The only problem with that is, that the directories timestamp depends on what is done to the files inside. For the rules above, this leads to the following result:
$ make
mkdir -p outDir
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget
This is most definitely not what you want. Whenever you touch the file, you also touch the directory. And since the file depends on the directory, the file consequently appears to be out of date, forcing it to be rebuilt.
However, you can easily break this loop by telling make to ignore the timestamp of the directory. This is done by declaring the directory as an order-only prerequsite:
# The pipe symbol tells make that the following prerequisites are order-only
# |
# v
outDir/someTarget: Makefile | outDir
touch outDir/someTarget
outDir:
mkdir -p outDir
This correctly yields:
$ make
mkdir -p outDir
touch outDir/someTarget
$ make
make: 'outDir/someTarget' is up to date.
TL;DR:
Write a rule to create the directory:
$(OUT_DIR):
mkdir -p $(OUT_DIR)
And have the targets for the stuff inside depend on the directory order-only:
$(OUT_DIR)/someTarget: ... | $(OUT_DIR)
You could use with open("path") as file:
so that it automatically closes, else if it's open in another process you can maybe try
as in Tims example you should use except IOError to not ignore any other problem with your code :)
try:
with open("path", "r") as file: # or just open
# Code here
except IOError:
# raise error or print
Not sure if it will work for all versions of Android (especially those with custom UI stuff), but I was able to remove the gray bar at the bottom by adding
android:layout_marginBottom="-3dp"
to the TabWidget XML...
import java.io.*;
import java.util.*;
import java.util.HashMap;
public class Solution
{
public static void main(String[] args)
{
HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1,"SUNDAY");
hm.put(2,"MONDAY");
hm.put(3,"TUESDAY");
hm.put(4,"WEDNESDAY");
hm.put(5,"THURSDAY");
hm.put(6,"FRIDAY");
hm.put(7,"SATURDAY");
Scanner in = new Scanner(System.in);
String month = in.next();
String day = in.next();
String year = in.next();
String format = year + "/" + month + "/" + day;
Date date = null;
try
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
date = formatter.parse(format);
}
catch(Exception e){
}
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println(hm.get(dayOfWeek));
}
}
That is not changing due to the default theme set to the screen.
So just change them for the widget you are drawing by wrapping your TextField with new ThemeData()
child: new Theme(
data: new ThemeData(
primaryColor: Colors.redAccent,
primaryColorDark: Colors.red,
),
child: new TextField(
decoration: new InputDecoration(
border: new OutlineInputBorder(
borderSide: new BorderSide(color: Colors.teal)),
hintText: 'Tell us about yourself',
helperText: 'Keep it short, this is just a demo.',
labelText: 'Life story',
prefixIcon: const Icon(
Icons.person,
color: Colors.green,
),
prefixText: ' ',
suffixText: 'USD',
suffixStyle: const TextStyle(color: Colors.green)),
),
));
You can find the .app file here:
~/Library/Developer/Xcode/DerivedData/{app name}/Build/Products/Deployment/
credit for path goes to this answer
SIDENOTE: I had a lot of fun trying to get this into my iPad after that. It worked however. Using Snow Leopard + Xcode 4.2 + iPad with IOS 5.1.1 :) - I used the iPhone configuration utility to get the app into the ipad (you have to add the app, then click on the device, then click "install" behind the app you just added in the "application library" of iphone configuration utility) and had to create a Distribution Provisioning Profile and get the WWDR certificate and finally change the build settings in Xcode after all the certificates were in place. See here
But after much fun I am now looking at my first app on my iPad :) - btw, for getting apps into the app store you need to create a app store Distribution Provisioning Profile, while for ad hoc installs like these you create an ad hoc one. There is a bit more to it, but I think these are the most important and tricky steps. Enjoy.
PS. Just remembered that you also have to set the build type (top left of Xcode) to "iOS device", otherwise it will never sign your application. So the path name above only has limited value: yes, it will have the .app file in it, but no you can't upload it (at least not using the iPhone configuration utility) since it is not code signed - you will get an "Could not copy validate signature" error. So change it to "iOS device" and build (remember to select the right certificates in the build section of Xcode as per the url info above). In that same build section, you can also set the "Installation Build Products Location" to a different path, so that you can determine where the .app (the one that is properly code signed) ends up.
That's constructor initialisation. It is the correct way to initialise members in a class constructor, as it prevents the default constructor being invoked.
Consider these two examples:
// Example 1
Foo(Bar b)
{
bar = b;
}
// Example 2
Foo(Bar b)
: bar(b)
{
}
In example 1:
Bar bar; // default constructor
bar = b; // assignment
In example 2:
Bar bar(b) // copy constructor
It's all about efficiency.
This worked for me-
let routeData = this.$router.resolve(
{
path: '/resources/c-m-communities',
query: {'dataParameter': 'parameterValue'}
});
window.open(routeData.href, '_blank');
I modified @Rafael_Andrs_Cspedes_Basterio answer
Modules go in site-packages
and executables go in your system's executable path. For your environment, this path is /usr/local/bin/
.
To avoid having to deal with this, simply use easy_install
, distribute
or pip
. These tools know which files need to go where.
Example valid nginx.conf for reverse proxy; In case someone is stuck like me.
where 10.x.x.x
is the server where you are running the nginx proxy server and to which you are connecting to with the browser, and 10.y.y.y
is where your real web server is running
events {
worker_connections 4096; ## Default: 1024
}
http {
server {
listen 80;
listen [::]:80;
server_name 10.x.x.x;
location / {
proxy_pass http://10.y.y.y:80/;
proxy_set_header Host $host;
}
}
}
Here is the snippet if you want to do SSL pass through. That is if 10.y.y.y
is running a HTTPS webserver. Here 10.x.x.x
, or where the nignx runs is listening to port 443, and all traffic to 443 is directed to your target web server
events {
worker_connections 4096; ## Default: 1024
}
stream {
server {
listen 443;
proxy_pass 10.y.y.y:443;
}
}
and you can serve it up in docker too
docker run --name nginx-container --rm --net=host -v /home/core/nginx/nginx.conf:/etc/nginx/nginx.conf nginx
In addition to the other answers, Class defines the method === to test whether an object is an instance of that class.
You can normally check for ASCII letters or numbers using simple conditions
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
/*This is an alphabet*/
}
For digits you can use
if (ch >= '0' && ch <= '9')
{
/*It is a digit*/
}
But since characters in C are internally treated as ASCII values you can also use ASCII values to check the same.
This gets the logical exclusive XOR for two (or more) variables
str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
any([str1, str2]) and not all([str1, str2])
The first problem with this setup is that it most likely traverses the whole list twice and, at a minimum, will check at least one of the elements twice. So it may increase code comprehension, but it doesn't lend to speed (which may differ negligibly depending on your use case).
The second problem with this setup is that it checks for exclusivity regardless of the number of variables. This is may at first be regarded as a feature, but the first problem becomes a lot more significant as the number of variables increases (if they ever do).
emulator -writable-system
For people using an Emulator: Another possibility is that you need to start the emulator with -writable-system. That was the only thing that worked for me when using the standard emulator packaged with android studio with a 4.1 image. Check here: https://stackoverflow.com/a/41332316/4962858
Yes, it is valid.
As for making it work with functors as well, the usual solution is something like this instead:
template <typename F>
void doOperation(F f)
{
int temp=0;
f(temp);
std::cout << "Result is " << temp << std::endl;
}
which can now be called as either:
doOperation(add2);
doOperation(add3());
The problem with this is that if it makes it tricky for the compiler to inline the call to add2
, since all the compiler knows is that a function pointer type void (*)(int &)
is being passed to doOperation
. (But add3
, being a functor, can be inlined easily. Here, the compiler knows that an object of type add3
is passed to the function, which means that the function to call is add3::operator()
, and not just some unknown function pointer.)
For the record, the spring.jpa.hibernate.ddl-auto
property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto
.
The values create
, create-drop
, validate
, and update
basically influence how the schema tool management will manipulate the database schema at startup.
For example, the update
operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.
The update
operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.
Typically in test case scenarios, you'll likely use create-drop
so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.
In development, it's often common to see developers use update
to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.
In production, it's often highly recommended you use none
or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.
I followed the most of the answers which was recommended here. First I got the following error:
fatal: unable to access 'https://github.com/folder/sample.git/': schannel: next InitializeSecurityContext failed: Unknown error (0x80092012) - The revocation function was unable to check revocation for the certificate.
Then I have tried the following command by @Salim Hamidi
git config --global http.proxy http://proxyuser:[email protected]:8080
But I got the following error:
fatal: unable to access 'https://github.com/folder/sample.git/': Received HTTP code 407 from proxy after CONNECT
This could happen if the proxy server can't verify the SSL certificate. So we want to make sure that the ssl verification is off (not recommended for non trusted sites), so I have done the following steps which was recommended by @Arpit but with slight changes:
1.First make sure to remove any previous proxy settings:
git config --global --unset http.proxy
2.Then list and get the gitconfig content
git config --list --show-origin
3.Last update the content of the gitconfig file as below:
[http]
sslCAInfo = C:/yourfolder/AppData/Local/Programs/Git/mingw64/ssl/certs/ca-bundle.crt
sslBackend = schannel
proxy = http://proxyuser:[email protected]:8080
sslverify = false
[https]
proxy = http://proxyuser:[email protected]:8080
sslverify = false
Here is some code:
private void dgvStandingOrder_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (dgvStandingOrder.Columns[e.ColumnIndex].Name == "IsSelected" && dgvStandingOrder.CurrentCell is DataGridViewCheckBoxCell)
{
bool isChecked = (bool)dgvStandingOrder[e.ColumnIndex, e.RowIndex].EditedFormattedValue;
if (isChecked == false)
{
dgvStandingOrder.Rows[e.RowIndex].Cells["Status"].Value = "";
}
dgvStandingOrder.EndEdit();
}
}
private void dgvStandingOrder_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
dgvStandingOrder.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void dgvStandingOrder_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dgvStandingOrder.CurrentCell is DataGridViewCheckBoxCell)
{
dgvStandingOrder.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
Smart pointers will clean themselves up after they go out of scope (thereby removing fear of most memory leaks). Shared pointers are smart pointers that keep a count of how many instances of the pointer exist, and only clean up the memory when the count reaches zero. In general, only use shared pointers (but be sure to use the correct kind--there is a different one for arrays). They have a lot to do with RAII.
Found out for Samsung, Installing Kies also update the usb driver which solve my problem with connecting my Samsung Galaxy S Advance with Android 4.1.2 to Android Studio on Windows 7 64bit. In this case the devise manager shows device driver is updated and working, but when I connect my phone Android Studio does not recognize my device.
You can use Java jar
tool. List the content of jar file in a txt file and you can see all the classes in the jar.
jar tvf jarfile.jar
-t list table of contents for archive
-v generate verbose output on standard output
-f specify archive file name
On your backEnd, you should add:
@RequestMapping(value="/blabla", produces="text/plain" , method = RequestMethod.GET)
On the frontEnd (Service):
methodBlabla()
{
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.get(this.url,{ headers, responseType: 'text'});
}
Swift 3 : Xcode 8 helper function:
func getDayOfWeek(fromDate date: Date) -> String? {
let cal = Calendar(identifier: .gregorian)
let dayOfWeek = cal.component(.weekday, from: date)
switch dayOfWeek {
case 1:
return "Sunday"
case 2:
return "Monday"
case 3:
return "Tuesday"
case 4:
return "Wednesday"
case 5:
return "Thursday"
case 6:
return "Friday"
case 7:
return "Saturday"
default:
return nil
}
}
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
Following the instructions here http://help.loftware.com/pages/viewpage.action?pageId=27099554 I had to install the Microsoft Access Database Engine 2010 Redistributable before I had the Excel driver installed to use the DSN-less connection I wanted to use from perl.
Press Ctrl + F10 to rotate the emulator screen.
If you want a method other than findcontrol try the following:
GridViewRow row = Gridview1.SelectedRow;
int CustomerId = int.parse(row.Cells[0].Text);// to get the column value
CheckBox checkbox1= row.Cells[0].Controls[0] as CheckBox; // you can access the controls like this
If you don't want the url to put it on option's value, i'll give u example :
<select class="abc">
<option value="0" href="hello">Hell</option>
<option value="1" href="dello">Dell</option>
<option value="2" href="cello">Cell</option>
</select>
$("select").bind('change',function(){
alert($(':selected',this).attr('href'));
})
In my case i have used .woff files from git repository, and i noticed git has changed my binary files. That with some null character at the file endings. I have rechanged to the orgnal .woff source files and it has corrected!
Also i have understood visual studio controller sending corrupted error like ERR_CONNECTION_RESET from the controller when it gots null character
I shared for all who live this problem
EDIT: The smartest approach IMHO, it removes the last point and following text from a filename (aka the extension):
$name = basename($filename, '.' . end(explode('.', $filename)));
Cheers ;)
Notice that sapply with "[" can be used to extract either the first or second items in those lists so:
before$type_1 <- sapply(strsplit(as.character(before$type),'_and_'), "[", 1)
before$type_2 <- sapply(strsplit(as.character(before$type),'_and_'), "[", 2)
before$type <- NULL
And here's a gsub method:
before$type_1 <- gsub("_and_.+$", "", before$type)
before$type_2 <- gsub("^.+_and_", "", before$type)
before$type <- NULL
As mentioned the dear user @Calvintwr, the function math.log10
has problem in a number outside of a range [-999999999999997, 999999999999997], where we get floating point errors. I had this problem with the JavaScript (the Google V8 and the NodeJS) and the C (the GNU GCC compiler), so a 'purely mathematically'
solution is impossible here.
Based on this gist and the answer the dear user @Calvintwr
import math
def get_count_digits(number: int):
"""Return number of digits in a number."""
if number == 0:
return 1
number = abs(number)
if number <= 999999999999997:
return math.floor(math.log10(number)) + 1
count = 0
while number:
count += 1
number //= 10
return count
I tested it on numbers with length up to 20 (inclusive) and all right. It must be enough, because the length max integer number on a 64-bit system is 19 (len(str(sys.maxsize)) == 19
).
assert get_count_digits(-99999999999999999999) == 20
assert get_count_digits(-10000000000000000000) == 20
assert get_count_digits(-9999999999999999999) == 19
assert get_count_digits(-1000000000000000000) == 19
assert get_count_digits(-999999999999999999) == 18
assert get_count_digits(-100000000000000000) == 18
assert get_count_digits(-99999999999999999) == 17
assert get_count_digits(-10000000000000000) == 17
assert get_count_digits(-9999999999999999) == 16
assert get_count_digits(-1000000000000000) == 16
assert get_count_digits(-999999999999999) == 15
assert get_count_digits(-100000000000000) == 15
assert get_count_digits(-99999999999999) == 14
assert get_count_digits(-10000000000000) == 14
assert get_count_digits(-9999999999999) == 13
assert get_count_digits(-1000000000000) == 13
assert get_count_digits(-999999999999) == 12
assert get_count_digits(-100000000000) == 12
assert get_count_digits(-99999999999) == 11
assert get_count_digits(-10000000000) == 11
assert get_count_digits(-9999999999) == 10
assert get_count_digits(-1000000000) == 10
assert get_count_digits(-999999999) == 9
assert get_count_digits(-100000000) == 9
assert get_count_digits(-99999999) == 8
assert get_count_digits(-10000000) == 8
assert get_count_digits(-9999999) == 7
assert get_count_digits(-1000000) == 7
assert get_count_digits(-999999) == 6
assert get_count_digits(-100000) == 6
assert get_count_digits(-99999) == 5
assert get_count_digits(-10000) == 5
assert get_count_digits(-9999) == 4
assert get_count_digits(-1000) == 4
assert get_count_digits(-999) == 3
assert get_count_digits(-100) == 3
assert get_count_digits(-99) == 2
assert get_count_digits(-10) == 2
assert get_count_digits(-9) == 1
assert get_count_digits(-1) == 1
assert get_count_digits(0) == 1
assert get_count_digits(1) == 1
assert get_count_digits(9) == 1
assert get_count_digits(10) == 2
assert get_count_digits(99) == 2
assert get_count_digits(100) == 3
assert get_count_digits(999) == 3
assert get_count_digits(1000) == 4
assert get_count_digits(9999) == 4
assert get_count_digits(10000) == 5
assert get_count_digits(99999) == 5
assert get_count_digits(100000) == 6
assert get_count_digits(999999) == 6
assert get_count_digits(1000000) == 7
assert get_count_digits(9999999) == 7
assert get_count_digits(10000000) == 8
assert get_count_digits(99999999) == 8
assert get_count_digits(100000000) == 9
assert get_count_digits(999999999) == 9
assert get_count_digits(1000000000) == 10
assert get_count_digits(9999999999) == 10
assert get_count_digits(10000000000) == 11
assert get_count_digits(99999999999) == 11
assert get_count_digits(100000000000) == 12
assert get_count_digits(999999999999) == 12
assert get_count_digits(1000000000000) == 13
assert get_count_digits(9999999999999) == 13
assert get_count_digits(10000000000000) == 14
assert get_count_digits(99999999999999) == 14
assert get_count_digits(100000000000000) == 15
assert get_count_digits(999999999999999) == 15
assert get_count_digits(1000000000000000) == 16
assert get_count_digits(9999999999999999) == 16
assert get_count_digits(10000000000000000) == 17
assert get_count_digits(99999999999999999) == 17
assert get_count_digits(100000000000000000) == 18
assert get_count_digits(999999999999999999) == 18
assert get_count_digits(1000000000000000000) == 19
assert get_count_digits(9999999999999999999) == 19
assert get_count_digits(10000000000000000000) == 20
assert get_count_digits(99999999999999999999) == 20
All example of codes tested with the Python 3.5
Git has the concept of "remotes", which are simply URLs to other copies of your repository. When you clone another repository, Git automatically creates a remote named "origin" and points to it.
You can see more information about the remote by typing git remote show origin
.
MaxLength
is now supported as of .NET 4.7.2, so as long as you upgrade your project to .NET 4.7.2 or above, it will work automatically.
You can see this in the release notes here - specifically:
Enable ASP.NET developers to specify MaxLength attribute for Multiline asp:TextBox. [449020, System.Web.dll, Bug]
You dont have to mess with recursion and other complex algorithms. You can find all subsets using bit patterns (decimal to binary) of all numbers between 0 and 2^(N-1). Here N is cardinality or number-of-items in that set. The technique is explained here with an implementation and demo.
As an addition
To disable all rules for the next line // tslint:disable-next-line
To disable specific rules for the next line: // tslint:disable-next-line:rule1 rule2...
To disable all rules for the current line: someCode(); // tslint:disable-line
To disable specific rules for the current line: someCode(); // tslint:disable-line:rule1
Without GNU extension:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
const char str1[] = "First";
const char str2[] = "Second";
char *res;
res = malloc(strlen(str1) + strlen(str2) + 1);
if (!res) {
fprintf(stderr, "malloc() failed: insufficient memory!\n");
return EXIT_FAILURE;
}
strcpy(res, str1);
strcat(res, str2);
printf("Result: '%s'\n", res);
free(res);
return EXIT_SUCCESS;
}
Alternatively with GNU extension:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
const char str1[] = "First";
const char str2[] = "Second";
char *res;
if (-1 == asprintf(&res, "%s%s", str1, str2)) {
fprintf(stderr, "asprintf() failed: insufficient memory!\n");
return EXIT_FAILURE;
}
printf("Result: '%s'\n", res);
free(res);
return EXIT_SUCCESS;
}
If you are sure that this change is suitable for the environment you're working in: set the FK conditions on the secondary tables to UPDATE CASCADING.
For example, if using SSMS as GUI:
When you then update a value in the PK column in your primary table, the FK references in the other tables will be updated to point at the new value, preserving data integrity.
If you don't mind installing an additional light library, you can do this:
pip install plazy
Usage:
import plazy
txt_filter = lambda x : True if x.endswith('.txt') else False
files = plazy.list_files(root='data', filter_func=txt_filter, is_include_root=True)
The result should look something like this:
['data/a.txt', 'data/b.txt', 'data/sub_dir/c.txt']
It works on both Python 2.7 and Python 3.
Github: https://github.com/kyzas/plazy#list-files
Disclaimer: I'm an author of plazy
.
For the sake of ease of use and understandability.
You can simply put a Tooltip anywhere on your form (from toolbox). You will then be given an options in the Properties of everything else in your form to determine what is displayed in that Tooltip (it reads something like "ToolTip on toolTip1"). Anytime you hover on an object, the text in that property will be displayed as a tooltip.
This does not cover custom on-the-fly tooltips like the original question is asking for. But I am leaving this here for others that do not need
'Load'- inserts a file's contents.(Parse file every time the file is being called)
'Require'- inserts a file parsed content.(File parsed once and stored in memory)
'Include'- includes the module into the class and can use methods inside the module as class's instance method
'Extend'- includes the module into the class and can use methods inside the module as class method
Simple and precise (Source: Socket.IO google group):
socket.emit
allows you to emit custom events on the server and client
socket.send
sends messages which are received with the 'message'
event