How do you extract IP addresses from files using a regex in a linux shell?
I wrote an informative blog article about this topic: How to Extract IPv4 and IPv6 IP Addresses from Plain Text Using Regex.
In the article there's a detailed guide of the most common different patterns for IPs, often required to be extracted and isolated from plain text using regular expressions.
This guide is based on CodVerter's IP Extractor source code tool for handling IP addresses extraction and detection when necessary.
If you wish to validate and capture IPv4 Address this pattern can do the job:
\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[.]){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
or to validate and capture IPv4 Address with Prefix ("slash notation"):
\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[.]){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?/[0-9]{1,2})\b
or to capture subnet mask or wildcard mask:
(255|254|252|248|240|224|192|128|0)[.](255|254|252|248|240|224|192|128|0)[.](255|254|252|248|240|224|192|128|0)[.](255|254|252|248|240|224|192|128|0)
or to filter out subnet mask addresses you do it with regex negative lookahead:
\b((?!(255|254|252|248|240|224|192|128|0)[.](255|254|252|248|240|224|192|128|0)[.](255|254|252|248|240|224|192|128|0)[.](255|254|252|248|240|224|192|128|0)))(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[.]){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
For IPv6 validation you can go to the article link I have added at the top of this answer.
Here is an example for capturing all the common patterns (taken from CodVerter`s IP Extractor Help Sample):
If you wish you can test the IPv4 regex here.
How to keep form values after post
If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:
<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />
Why doesn't logcat show anything in my Android?
If you are using a device, the simplest check is to restart eclipse.
** you don't have to shutdown eclipse **
use File > Restart
in a quick second or two you should see your LogCat return
Get button click inside UITableViewCell
I find it simplest to subclass the button inside your cell (Swift 3):
class MyCellInfoButton: UIButton {
var indexPath: IndexPath?
}
In your cell class:
class MyCell: UICollectionViewCell {
@IBOutlet weak var infoButton: MyCellInfoButton!
...
}
In the table view's or collection view's data source, when dequeueing the cell, give the button its index path:
cell.infoButton.indexPath = indexPath
So you can just put these code into your table view controller:
@IBAction func handleTapOnCellInfoButton(_ sender: MyCellInfoButton) {
print(sender.indexPath!) // Do whatever you want with the index path!
}
And don't forget to set the button's class in your Interface Builder and link it to the handleTapOnCellInfoButton
function!
edited:
Using dependency injection. To set up calling a closure:
class MyCell: UICollectionViewCell {
var someFunction: (() -> Void)?
...
@IBAction func didTapInfoButton() {
someFunction?()
}
}
and inject the closure in the willDisplay method of the collection view's delegate:
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
(cell as? MyCell)?.someFunction = {
print(indexPath) // Do something with the indexPath.
}
}
Can't access 127.0.0.1
If it's a DNS problem, you could try:
- ipconfig /flushdns
- ipconfig /registerdns
If this doesn't fix it, you could try editing the hosts file located here:
C:\Windows\System32\drivers\etc\hosts
And ensure that this line (and no other line referencing localhost) is in there:
127.0.0.1 localhost
How do I add a new class to an element dynamically?
Since everyone has given you jQuery/JS answers to this, I will provide an additional solution. The answer to your question is still no, but using LESS (a CSS Pre-processor) you can do this easily.
.first-class {
background-color: yellow;
}
.second-class:hover {
.first-class;
}
Quite simply, any time you hover over .second-class
it will give it all the properties of .first-class
. Note that it won't add the class permanently, just on hover. You can learn more about LESS here: Getting Started with LESS
Here is a SASS way to do it as well:
.first-class {
background-color: yellow;
}
.second-class {
&:hover {
@extend .first-class;
}
}
How to validate an OAuth 2.0 access token for a resource server?
Google way
Google Oauth2 Token Validation
Request:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=1/fFBGRNJru1FQd44AzqT3Zg
Respond:
{
"audience":"8819981768.apps.googleusercontent.com",
"user_id":"123456789",
"scope":"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
"expires_in":436
}
Microsoft way
Microsoft - Oauth2 check an authorization
Github way
Github - Oauth2 check an authorization
Request:
GET /applications/:client_id/tokens/:access_token
Respond:
{
"id": 1,
"url": "https://api.github.com/authorizations/1",
"scopes": [
"public_repo"
],
"token": "abc123",
"app": {
"url": "http://my-github-app.com",
"name": "my github app",
"client_id": "abcde12345fghij67890"
},
"note": "optional note",
"note_url": "http://optional/note/url",
"updated_at": "2011-09-06T20:39:23Z",
"created_at": "2011-09-06T17:26:27Z",
"user": {
"login": "octocat",
"id": 1,
"avatar_url": "https://github.com/images/error/octocat_happy.gif",
"gravatar_id": "somehexcode",
"url": "https://api.github.com/users/octocat"
}
}
Amazon way
Login With Amazon - Developer Guide (Dec. 2015, page 21)
Request :
https://api.amazon.com/auth/O2/tokeninfo?access_token=Atza|IQEBLjAsAhRmHjNgHpi0U-Dme37rR6CuUpSR...
Response :
HTTP/l.l 200 OK
Date: Fri, 3l May 20l3 23:22:l0 GMT
x-amzn-RequestId: eb5be423-ca48-lle2-84ad-5775f45l4b09
Content-Type: application/json
Content-Length: 247
{
"iss":"https://www.amazon.com",
"user_id": "amznl.account.K2LI23KL2LK2",
"aud": "amznl.oa2-client.ASFWDFBRN",
"app_id": "amznl.application.436457DFHDH",
"exp": 3597,
"iat": l3ll280970
}
How to read a configuration file in Java
Create a configuration file and put your entries there.
SERVER_PORT=10000
THREAD_POOL_COUNT=3
ROOT_DIR=/home/
You can load this file using Properties.load(fileName)
and retrieved values you get(key)
;
Basic calculator in Java
public class SwitchExample {
public static void main(String[] args) throws Exception {
System.out.println(":::::::::::::::::::::Start:::::::::::::::::::");
System.out.println("\n\n");
System.out.println("1. Addition");
System.out.println("2. Multiplication");
System.out.println("3. Substraction");
System.out.println("4. Division");
System.out.println("0. Exit");
System.out.println("\n");
System.out.println("Enter Your Choice ::::::: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int usrChoice = Integer.parseInt(str);
switch (usrChoice) {
case 1:
doAddition();
break;
case 2:
doMultiplication();
break;
case 3:
doSubstraction();
break;
case 4:
doDivision();
break;
case 0:
System.out.println("Thank you.....");
break;
default:
System.out.println("Invalid Value");
}
System.out.println(":::::::::::::::::::::End:::::::::::::::::::");
}
public static void doAddition() throws Exception {
System.out.println("******* Enter in Addition Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Addition : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Addition : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 + no2;
System.out.println("Addition of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doSubstraction() throws Exception {
System.out.println("******* Enter in Substraction Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Substraction : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Substraction : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 - no2;
System.out.println("Substraction of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doMultiplication() throws Exception {
System.out.println("******* Enter in Multiplication Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Multiplication : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Multiplication : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 * no2;
System.out.println("Multiplication of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doDivision() throws Exception {
System.out.println("******* Enter in Dividion Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Dividion : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Dividion : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
float result = no1 / no2;
System.out.println("Division of " + no1 + " and " + no2 + " is ::::::: " + result);
}
}
How do I run a terminal inside of Vim?
Try vterm, which is a pretty much full feature shell inside vim. It is slightly buggy with its history and clear functions, and still in development, but it still is pretty good
How do I move to end of line in Vim?
Also note the distinction between line (or perhaps physical line) and screen line. A line is terminated by the End Of Line character ("\n"). A screen line is whatever happens to be shown as one row of characters in your terminal or in your screen. The two come apart if you have physical lines longer than the screen width, which is very common when writing emails and such.
The distinction shows up in the end-of-line commands as well.
- $ and 0 move to the end or beginning of the physical line or paragraph, respectively:
- g$ and g0 move to the end or beginning of the screen line or paragraph, respectively.
If you always prefer the latter behavior, you can remap the keys like this:
:noremap 0 g0
:noremap $ g$
Detecting real time window size changes in Angular 4
The documentation for Platform
width()
and height()
, it's stated that these methods use window.innerWidth
and window.innerHeight
respectively. But using the methods are preferred since the dimensions are cached values, which reduces the chance of multiple and expensive DOM reads.
import { Platform } from 'ionic-angular';
...
private width:number;
private height:number;
constructor(private platform: Platform){
platform.ready().then(() => {
this.width = platform.width();
this.height = platform.height();
});
}
How to invoke a Linux shell command from Java
Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(final String[] args) throws IOException, InterruptedException {
//Build command
List<String> commands = new ArrayList<String>();
commands.add("/bin/cat");
//Add arguments
commands.add("/home/narek/pk.txt");
System.out.println(commands);
//Run macro on target
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("/home/narek"));
pb.redirectErrorStream(true);
Process process = pb.start();
//Read output
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null, previous = null;
while ((line = br.readLine()) != null)
if (!line.equals(previous)) {
previous = line;
out.append(line).append('\n');
System.out.println(line);
}
//Check result
if (process.waitFor() == 0) {
System.out.println("Success!");
System.exit(0);
}
//Abnormal termination: Log command parameters and output and throw ExecutionException
System.err.println(commands);
System.err.println(out.toString());
System.exit(1);
}
}
Breaking to a new line with inline-block?
Here is another solution (only relevant declarations listed):
.text span {
display:inline-block;
margin-right:100%;
}
When the margin is expressed in percentage, that percentage is taken from the width of the parent node, so 100% means as wide as the parent, which results in the next element getting "pushed" to a new line.
Looping through JSON with node.js
You may also want to use hasOwnProperty in the loop.
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
switch (prop) {
// obj[prop] has the value
}
}
}
node.js is single-threaded which means your script will block whether you want it or not. Remember that V8 (Google's Javascript engine that node.js uses) compiles Javascript into machine code which means that most basic operations are really fast and looping through an object with 100 keys would probably take a couple of nanoseconds?
However, if you do a lot more inside the loop and you don't want it to block right now, you could do something like this
switch (prop) {
case 'Timestamp':
setTimeout(function() { ... }, 5);
break;
case 'Start_Value':
setTimeout(function() { ... }, 10);
break;
}
If your loop is doing some very CPU intensive work, you will need to spawn a child process to do that work or use web workers.
Nested rows with bootstrap grid system?
Bootstrap Version 3.x
As always, read Bootstrap's great documentation:
3.x Docs: https://getbootstrap.com/docs/3.3/css/#grid-nesting
Make sure the parent level row is inside of a .container
element. Whenever you'd like to nest rows, just open up a new .row
inside of your column.
Here's a simple layout to work from:
<div class="container">
<div class="row">
<div class="col-xs-6">
<div class="big-box">image</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-6"><div class="mini-box">1</div></div>
<div class="col-xs-6"><div class="mini-box">2</div></div>
<div class="col-xs-6"><div class="mini-box">3</div></div>
<div class="col-xs-6"><div class="mini-box">4</div></div>
</div>
</div>
</div>
</div>
Bootstrap Version 4.0
4.0 Docs: http://getbootstrap.com/docs/4.0/layout/grid/#nesting
Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature
<div class="container">
<div class="row">
<div class="col big-box">
image
</div>
<div class="col">
<div class="row">
<div class="col mini-box">1</div>
<div class="col mini-box">2</div>
</div>
<div class="row">
<div class="col mini-box">3</div>
<div class="col mini-box">4</div>
</div>
</div>
</div>
</div>
Which will look like this (with a little bit of added styling):
How to detect when facebook's FB.init is complete
The Facebook API watches for the FB._apiKey so you can watch for this before calling your own application of the API with something like:
window.fbAsyncInit = function() {
FB.init({
//...your init object
});
function myUseOfFB(){
//...your FB API calls
};
function FBreadyState(){
if(FB._apiKey) return myUseOfFB();
setTimeout(FBreadyState, 100); // adjust time as-desired
};
FBreadyState();
};
Not sure this makes a difference but in my case--because I wanted to be sure the UI was ready--I've wrapped the initialization with jQuery's document ready (last bit above):
$(document).ready(FBreadyState);
Note too that I'm NOT using async = true to load Facebook's all.js, which in my case seems to be helping with signing into the UI and driving features more reliably.
Easy way to password-protect php page
I would simply look for a $_GET
variable and redirect the user if it's not correct.
<?php
$pass = $_GET['pass'];
if($pass != 'my-secret-password') {
header('Location: http://www.staggeringbeauty.com/');
}
?>
Now, if this page is located at say: http://example.com/secrets/files.php
You can now access it with: http://example.com/secrets/files.php?pass=my-secret-password
Keep in mind that this isn't the most efficient or secure way, but nonetheless it is a easy and fast way. (Also, I know my answer is outdated but someone else looking at this question may find it valuable)
Creating a new dictionary in Python
>>> dict.fromkeys(['a','b','c'],[1,2,3])
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
How to center text vertically with a large font-awesome icon?
When using a flexbox, vertical alignment of font awesome icons next to text can be very difficult. I tried margins and padding, but that moved all items. I tried different flex alignments like center, start, baseline, etc, to no avail. The easiest and cleanest way to adjust only the icon was to set it's containing div to position: relative; top: XX;
This did the job perfectly.
How to create empty data frame with column names specified in R?
Just create a data.frame
with 0 length variables
eg
nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)
## 'data.frame': 0 obs. of 3 variables:
## $ x: num
## $ y: int
## $ z: Factor w/ 0 levels:
or to create a data.frame with 5 columns named a,b,c,d,e
nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))
How to convert DataSet to DataTable
A DataSet
already contains DataTables
. You can just use:
DataTable firstTable = dataSet.Tables[0];
or by name:
DataTable customerTable = dataSet.Tables["Customer"];
Note that you should have using
statements for your SQL code, to ensure the connection is disposed properly:
using (SqlConnection conn = ...)
{
// Code here...
}
Nested ng-repeat
It's better to have a proper JSON format instead of directly using the one converted from XML.
[
{
"number": "2013-W45",
"days": [
{
"dow": "1",
"templateDay": "Monday",
"jobs": [
{
"name": "Wakeup",
"jobs": [
{
"name": "prepare breakfast",
}
]
},
{
"name": "work 9-5",
}
]
},
{
"dow": "2",
"templateDay": "Tuesday",
"jobs": [
{
"name": "Wakeup",
"jobs": [
{
"name": "prepare breakfast",
}
]
}
]
}
]
}
]
This will make things much easier and easy to loop through.
Now you can write the loop as -
<div ng-repeat="week in myData">
<div ng-repeat="day in week.days">
{{day.dow}} - {{day.templateDay}}
<b>Jobs:</b><br/>
<ul>
<li ng-repeat="job in day.jobs">
{{job.name}}
</li>
</ul>
</div>
</div>
Drawing a simple line graph in Java
Override the paintComponent method of your panel so you can custom draw. Like this:
@Override
public void paintComponent(Graphics g) {
Graphics2D gr = (Graphics2D) g; //this is if you want to use Graphics2D
//now do the drawing here
...
}
Why compile Python code?
Beginners assume Python is compiled because of .pyc files. The .pyc file is the compiled bytecode, which is then interpreted. So if you've run your Python code before and have the .pyc file handy, it will run faster the second time, as it doesn't have to re-compile the bytecode
compiler:
A compiler is a piece of code that translates the high level language into machine language
Interpreters:
Interpreters also convert the high level language into machine readable binary equivalents. Each time when an interpreter gets a high level language code to be executed, it converts the code into an intermediate code before converting it into the machine code. Each part of the code is interpreted and then execute separately in a sequence and an error is found in a part of the code it will stop the interpretation of the code without translating the next set of the codes.
Sources:
http://www.toptal.com/python/why-are-there-so-many-pythons
http://www.engineersgarage.com/contribution/difference-between-compiler-and-interpreter
How can I have a newline in a string in sh?
This isn't ideal, but I had written a lot of code and defined strings in a way similar to the method used in the question. The accepted solution required me to refactor a lot of the code so instead, I replaced every \n
with "$'\n'"
and this worked for me.
Set time to 00:00:00
We can set java.util.Date time part to 00:00:00 By using LocalDate class of Java 8/Joda-datetime api:
Date datewithTime = new Date() ; // ex: Sat Apr 21 01:30:44 IST 2018
LocalDate localDate = LocalDate.fromDateFields(datewithTime);
Date datewithoutTime = localDate.toDate(); // Sat Apr 21 00:00:00 IST 2018
Only local connections are allowed Chrome and Selenium webdriver
First off, What you are seeing is not an error. It is an informational message.
When you run this driver, it will enable your scripts to access this and run commands on Google Chrome.
This can be done via scripts running in the local network (Only local connections are allowed.
) or via scripts running on outside networks (All remote connections are allowed.
). It is always safer to use the Local Connection option. By default your Chromedriver is accessible via port 9515
.
See this answer if you wish to allow all connections instead of just local.
If your Chromedriver only shows the above two messages (as per the question), then there is a problem. It has to show a message like this, which says it started successfully.
Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416}) on port 9515
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
To troubleshoot this...
Step 1: Check your Chromedriver version
$ chromedriver --version
ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416})
My version is 83.0.4103.39
.
Step 2: Check your Chrome Browser version
Open Google Chrome.
Options --> Help --> About Google Chrome
Or open a terminal and run the following command (works on Ubuntu).
$ google-chrome --version
Google Chrome 83.0.4103.61
My version is: Version 83.0.4103.61
Step 3: Compare versions of Chromedriver and Google Chrome
Both these versions are starting with 83, which means they are both compatible. Hence, you should see a message like below, when you run the below command.
$ chromedriver
Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416}) on port 9515
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
If your versions mismatch, then you will see the following message. You will not see the line which says, ChromeDriver was started successfully.
.
$ chromedriver
Starting ChromeDriver 80.0.3987.106 (f68069574609230cf9b635cd784cfb1bf81bb53a-refs/branch-heads/3987@{#882}) on port 9515
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Step 4: Download the correct version of Chromedriver
Download the correct version that matches your browser version. Use this page for downloads. After you download, extract the content, and move it to one of the following two folders. Open each of the following two folders and see whether your current Chromedriver is there. If it is on both folders, replace both. And do STEP 3 again.
/usr/bin/chromedriver
/usr/local/bin/chromedriver
Regex date validation for yyyy-mm-dd
you can test this expression:
^\d{4}[\-\/\s]?((((0[13578])|(1[02]))[\-\/\s]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\-\/\s]?(([0-2][0-9])|(30)))|(02[\-\/\s]?[0-2][0-9]))$
Description:
validates a yyyy-mm-dd, yyyy mm dd, or yyyy/mm/dd date
makes sure day is within valid range for the month - does NOT validate Feb. 29 on a leap year, only that Feb. Can have 29 days
Matches (tested) : 0001-12-31 | 9999 09 30 | 2002/03/03
reading from stdin in c++
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
Include another JSP file
At page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally, JSP include directive is used to include header banners and footers.
Syntax for include a jsp file:
<%@ include file="relative url">
Example
<%@include file="page_name.jsp" %>
Link error "undefined reference to `__gxx_personality_v0'" and g++
It sounds like you're trying to link with your resulting object file with gcc
instead of g++
:
Note that programs using C++ object
files must always be linked with g++,
in order to supply the appropriate C++
libraries. Attempting to link a C++
object file with the C compiler gcc
will cause "undefined reference"
errors for C++ standard library
functions:
$ g++ -Wall -c hello.cc
$ gcc hello.o (should use g++)
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
.....
hello.o(.eh_frame+0x11):
undefined reference to `__gxx_personality_v0'
Source: An Introduction to GCC - for the GNU compilers gcc and g++
Using Excel VBA to run SQL query
Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):
Sub Module for Connecting to MS SQL with Remote Host & Username/Password
Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
add image to uitableview cell
Standard UITableViewCell already contains UIImageView that appears to the left to all your labels if its image is set. You can access it using imageView property:
cell.imageView.image = someImage;
If for some reason standard behavior does not suit your needs (note that you can customize properties of that standard image view) then you can add your own UIImageView to the cell as Aman suggested in his answer. But in that approach you'll have to manage cell's layout yourself (e.g. make sure that cell labels do not overlap image). And do not add subviews to the cell directly - add them to cell's contentView:
// DO NOT!
[cell addSubview:imv];
// DO:
[cell.contentView addSubview:imv];
Reading Excel file using node.js
You can use read-excel-file npm.
In that,
you can specify JSON Schema to convert XLSX into JSON Format.
const readXlsxFile = require('read-excel-file/node');
const schema = {
'Segment': {
prop: 'Segment',
type: String
},
'Country': {
prop: 'Country',
type: String
},
'Product': {
prop: 'Product',
type: String
}
}
readXlsxFile('sample.xlsx', { schema }).then(({ rows, errors }) => {
console.log(rows);
});
Way to *ngFor loop defined number of times instead of repeating over array?
Within your component, you can define an array of number (ES6) as described below:
export class SampleComponent {
constructor() {
this.numbers = Array(5).fill(0).map((x,i)=>i);
}
}
See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.
You can then iterate over this array with ngFor
:
@View({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Or shortly:
@View({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Hope it helps you,
Thierry
Edit: Fixed the fill statement and template syntax.
How to put multiple statements in one line?
I recommend not doing this...
What you are describing is not a comprehension.
PEP 8 Style Guide for Python Code, which I do recommend, has this to say on compound statements:
- Compound statements (multiple statements on the same line) are generally discouraged.
Yes:
if foo == 'blah':
do_blah_thing()
do_one()
do_two()
do_three()
Rather not:
if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()
Here is a sample comprehension to make the distinction:
>>> [i for i in xrange(10) if i == 9]
[9]
How do I format a Microsoft JSON date?
If you say in JavaScript,
var thedate = new Date(1224043200000);
alert(thedate);
you will see that it's the correct date, and you can use that anywhere in JavaScript code with any framework.
How to create materialized views in SQL Server?
You might need a bit more background on what a Materialized View actually is. In Oracle these are an object that consists of a number of elements when you try to build it elsewhere.
An MVIEW is essentially a snapshot of data from another source. Unlike a view the data is not found when you query the view it is stored locally in a form of table. The MVIEW is refreshed using a background procedure that kicks off at regular intervals or when the source data changes. Oracle allows for full or partial refreshes.
In SQL Server, I would use the following to create a basic MVIEW to (complete) refresh regularly.
First, a view. This should be easy for most since views are quite common in any database
Next, a table. This should be identical to the view in columns and data. This will store a snapshot of the view data.
Then, a procedure that truncates the table, and reloads it based on the current data in the view.
Finally, a job that triggers the procedure to start it's work.
Everything else is experimentation.
jquery .html() vs .append()
You can get the second method to achieve the same effect by:
var mySecondDiv = $('<div></div>');
$(mySecondDiv).find('div').attr('id', 'mySecondDiv');
$('#myDiv').append(mySecondDiv);
Luca mentioned that html()
just inserts hte HTML which results in faster performance.
In some occassions though, you would opt for the second option, consider:
// Clumsy string concat, error prone
$('#myDiv').html("<div style='width:'" + myWidth + "'px'>Lorem ipsum</div>");
// Isn't this a lot cleaner? (though longer)
var newDiv = $('<div></div>');
$(newDiv).find('div').css('width', myWidth);
$('#myDiv').append(newDiv);
Change image size via parent div
I am doing this way:
<div class="card-logo">
<img height="100%" width="100%" src="http://someimage.jpg">
</div>
and CSS:
.card-logo {
width: 20%;
}
I prefer this way, as if I need to upscale - I can use 150% as well
What does the "at" (@) symbol do in Python?
To say what others have in a different way: yes, it is a decorator.
In Python, it's like:
- Creating a function (follows under the @ call)
- Calling another function to operate on your created function. This returns a new function. The function that you call is the argument of the @.
- Replacing the function defined with the new function returned.
This can be used for all kinds of useful things, made possible because functions are objects and just necessary just instructions.
Get month name from date in Oracle
If you are trying to pull the value from a field, you could use:
select extract(month from [field_name])
from [table_name]
You can also insert day or year for the "month" extraction value above.
How do I join two SQLite tables in my Android application?
You need rawQuery method.
Example:
private final String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?";
db.rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)});
Use ? bindings instead of putting values into raw sql query.
Laravel Eloquent LEFT JOIN WHERE NULL
Although Other Answers work well, i want to give you alternate short version which i use very often:
Customer::select('customers.*')
->leftJoin('orders', 'customers.id', '=', 'orders.customer_id')
->whereNull('orders.customer_id')->first();
And as in laravel version 5.3
added one more feature which will make your work even simpler look below for example:
Customer::doesntHave('orders')->get();
WordPress asking for my FTP credentials to install plugins
"Whenever you use the WordPress control panel to automatically install, upgrade, or delete plugins, WordPress must make changes to files on the filesystem.
Before making any changes, WordPress first checks to see whether or not it has access to directly manipulate the file system.
If WordPress does not have the necessary permissions to modify the filesystem directly, you will be asked for FTP credentials so that WordPress can try to do what it needs to via FTP."
Solution:
In order to find out what user your instance of apache is running as, create a test script with the following content:
<?php echo(exec("whoami")); ?>
For me, it was daemon and not www-data. Then, fix the permission by:
sudo chown -R daemon /path/to/your/local/www/folder
Android - how to replace part of a string by another string?
In kotlin there is no replaceAll, so I created this loop to replace repeated values ??in a string or any variable.
var someValue = "https://www.google.com.br/"
while (someValue.contains(".")) {
someValue = someValue.replace(".", "")
}
Log.d("newValue :", someValue)
// in that case the stitches have been removed
//https://wwwgooglecombr/
Calling onclick on a radiobutton list using javascript
The problem here is that the rendering of a RadioButtonList wraps the individual radio buttons (ListItems) in span tags and even when you assign a client-side event handler to the list item directly using Attributes it assigns the event to the span. Assigning the event to the RadioButtonList assigns it to the table it renders in.
The trick here is to add the ListItems on the aspx page and not from the code behind. You can then assign the JavaScript function to the onClick property. This blog post; attaching client-side event handler to radio button list by Juri Strumpflohner explains it all.
This only works if you know the ListItems in advance and does not help where the items in the RadioButtonList need to be dynamically added using the code behind.
How to change the default message of the required field in the popover of form-control in bootstrap?
Combination of Mritunjay and Bartu's answers are full answer to this question. I copying the full example.
<input class="form-control" type="email" required="" placeholder="username"
oninvalid="this.setCustomValidity('Please Enter valid email')"
oninput="setCustomValidity('')"></input>
Here,
this.setCustomValidity('Please Enter valid email')" - Display the custom message on invalidated of the field
oninput="setCustomValidity('')" - Remove the invalidate message on validated filed.
pySerial write() won't take my string
It turns out that the string needed to be turned into a bytearray and to do this I editted the code to
ser.write("%01#RDD0010000107**\r".encode())
This solved the problem
How to normalize a NumPy array to within a certain range?
A simple solution is using the scalers offered by the sklearn.preprocessing library.
scaler = sk.MinMaxScaler(feature_range=(0, 250))
scaler = scaler.fit(X)
X_scaled = scaler.transform(X)
# Checking reconstruction
X_rec = scaler.inverse_transform(X_scaled)
The error X_rec-X will be zero. You can adjust the feature_range for your needs, or even use a standart scaler sk.StandardScaler()
How to convert time milliseconds to hours, min, sec format in JavaScript?
Extending on @Rick's answer, I prefer something like this:
function msToReadableTime(time){
const second = 1000;
const minute = second * 60;
const hour = minute * 60;
let hours = Math.floor(time / hour % 24);
let minutes = Math.floor(time / minute % 60);
let seconds = Math.floor(time / second % 60);
return hours + ':' + minutes + ":" + seconds;
}
Send array with Ajax to PHP script
dataString suggests the data is formatted in a string (and maybe delimted by a character).
$data = explode(",", $_POST['data']);
foreach($data as $d){
echo $d;
}
if dataString is not a string but infact an array (what your question indicates) use JSON.
How to create XML file with specific structure in Java
Use JAXB:
http://www.mkyong.com/java/jaxb-hello-world-example/
package com.mkyong.core;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
package com.mkyong.core;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBExample {
public static void main(String[] args) {
Customer customer = new Customer();
customer.setId(100);
customer.setName("mkyong");
customer.setAge(29);
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
How to create JSON Object using String?
JSONArray
may be what you want.
String message;
JSONObject json = new JSONObject();
json.put("name", "student");
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);
json.put("course", array);
message = json.toString();
// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}
CSS text-decoration underline color
You can do it if you wrap your text into a span like:
_x000D_
_x000D_
a {_x000D_
color: red;_x000D_
text-decoration: underline;_x000D_
}_x000D_
span {_x000D_
color: blue;_x000D_
text-decoration: none;_x000D_
}
_x000D_
<a href="#">_x000D_
<span>Text</span>_x000D_
</a>
_x000D_
_x000D_
_x000D_
Using SQL LIKE and IN together
substr([column name],
[desired starting position (numeric)],
[# characters to include (numeric)]) in ([complete as usual])
Example
substr([column name],1,4) in ('M510','M615', 'M515', 'M612')
TSQL PIVOT MULTIPLE COLUMNS
Since you want to pivot multiple columns of data, I would first suggest unpivoting the result
, score
and grade
columns so you don't have multiple columns but you will have multiple rows.
Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:
select ratio = col,
[current ratio], [gearing ratio], [performance ratio], total
from
(
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
) d
pivot
(
max(value)
for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;
See SQL Fiddle with Demo. This will give you the result:
| RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO | TOTAL |
|--------|---------------|---------------|-------------------|-----------|
| grade | Good | Good | Satisfactory | Good |
| result | 1.29400 | 0.33840 | 0.04270 | (null) |
| score | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
How do I use a regular expression to match any string, but at least 3 characters?
This is python regex, but it probably works in other languages that implement it, too.
I guess it depends on what you consider a character to be. If it's letters, numbers, and underscores:
\w{3,}
if just letters and digits:
[a-zA-Z0-9]{3,}
Python also has a regex method to return all matches from a string.
>>> import re
>>> re.findall(r'\w{3,}', 'This is a long string, yes it is.')
['This', 'long', 'string', 'yes']
Java: How can I compile an entire directory structure of code ?
Windows solution: Assuming all files contained in sub-directory 'src', and you want to compile them to 'bin'.
for /r src %i in (*.java) do javac %i -sourcepath src -d bin
If src contains a .java file immediately below it then this is faster
javac src\\*.java -d bin
How can I put an icon inside a TextInput in React Native?
You can use combination of View, Icon and TextInput like so:
<View style={styles.searchSection}>
<Icon style={styles.searchIcon} name="ios-search" size={20} color="#000"/>
<TextInput
style={styles.input}
placeholder="User Nickname"
onChangeText={(searchString) => {this.setState({searchString})}}
underlineColorAndroid="transparent"
/>
</View>
and use flex-direction for styling
searchSection: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
searchIcon: {
padding: 10,
},
input: {
flex: 1,
paddingTop: 10,
paddingRight: 10,
paddingBottom: 10,
paddingLeft: 0,
backgroundColor: '#fff',
color: '#424242',
},
Icons were taken from "react-native-vector-icons"
How to make overlay control above all other controls?
Controls in the same cell of a Grid are rendered back-to-front. So a simple way to put one control on top of another is to put it in the same cell.
Here's a useful example, which pops up a panel that disables everything in the view (i.e. the user control) with a busy message while a long-running task is executed (i.e. while the BusyMessage
bound property isn't null):
<Grid>
<local:MyUserControl DataContext="{Binding}"/>
<Grid>
<Grid.Style>
<Style TargetType="Grid">
<Setter Property="Visibility"
Value="Visible" />
<Style.Triggers>
<DataTrigger Binding="{Binding BusyMessage}"
Value="{x:Null}">
<Setter Property="Visibility"
Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
<Border HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Background="DarkGray"
Opacity=".7" />
<Border HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="White"
Padding="20"
BorderBrush="Orange"
BorderThickness="4">
<TextBlock Text="{Binding BusyMessage}" />
</Border>
</Grid>
</Grid>
How do I write the 'cd' command in a makefile?
Like this:
target:
$(shell cd ....); \
# ... commands execution in this directory
# ... no need to go back (using "cd -" or so)
# ... next target will be automatically in prev dir
Good luck!
How to set up Automapper in ASP.NET Core
I am using AutoMapper 6.1.1 and asp.net Core 1.1.2.
First of all, define Profile classes inherited by Profile Class of Automapper. I Created IProfile interface which is empty, the purpose is only to find the classes of this type.
public class UserProfile : Profile, IProfile
{
public UserProfile()
{
CreateMap<User, UserModel>();
CreateMap<UserModel, User>();
}
}
Now create a separate class e.g Mappings
public class Mappings
{
public static void RegisterMappings()
{
var all =
Assembly
.GetEntryAssembly()
.GetReferencedAssemblies()
.Select(Assembly.Load)
.SelectMany(x => x.DefinedTypes)
.Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
var t = ti.AsType();
if (t.Equals(typeof(IProfile)))
{
Mapper.Initialize(cfg =>
{
cfg.AddProfiles(t); // Initialise each Profile classe
});
}
}
}
}
Now in MVC Core web Project in Startup.cs file, in the constructor, call Mapping class which will initialize all mappings at the time of application
loading.
Mappings.RegisterMappings();
Detect the Enter key in a text input field
event.key === "Enter"
More recent and much cleaner: use event.key
. No more arbitrary number codes!
NOTE: The old properties (.keyCode
and .which
) are Deprecated.
const node = document.getElementsByClassName("input")[0];
node.addEventListener("keyup", function(event) {
if (event.key === "Enter") {
// Do work
}
});
Modern style, with lambda and destructuring
node.addEventListener('keyup', ({key}) => {
if (key === "Enter") return false
})
If you must use jQuery:
$(document).keyup(function(event) {
if ($(".input1").is(":focus") && event.key == "Enter") {
// Do work
}
});
Mozilla Docs
Supported Browsers
Extract text from a string
Just to add a non-regex solution:
'(' + $myString.Split('()')[1] + ')'
This splits the string at the parentheses and takes the string from the array with the program name in it.
If you don't need the parentheses, just use:
$myString.Split('()')[1]
How to get the separate digits of an int number?
Something like this will return the char[]
:
public static char[] getTheDigits(int value){
String str = "";
int number = value;
int digit = 0;
while(number>0){
digit = number%10;
str = str + digit;
System.out.println("Digit:" + digit);
number = number/10;
}
return str.toCharArray();
}
SQL Server: the maximum number of rows in table
Largest table I've encountered on SQL Server 8 on Windows2003 was 799 million with 5 columns. But whether or not it's good will is to be measured against the SLA and usage case - e.g. load 50-100,000,000 records and see if it still works.
Streaming video from Android camera to server
I've built an open-source SDK called Kickflip to make streaming video from Android a painless experience.
The SDK demonstrates use of Android 4.3's MediaCodec API to direct the device hardware encoder's packets directly to FFmpeg for RTMP (with librtmp) or HLS streaming of H.264 / AAC. It also demonstrates realtime OpenGL Effects (titling, chroma key, fades) and background recording.
Thanks SO, and especially, fadden.
How to set password for Redis?
Example:
redis 127.0.0.1:6379> AUTH PASSWORD
(error) ERR Client sent AUTH, but no password is set
redis 127.0.0.1:6379> CONFIG SET requirepass "mypass"
OK
redis 127.0.0.1:6379> AUTH mypass
Ok
YouTube: How to present embed video with sound muted
The accepted answer was not working for me, I followed this tutorial instead with success.
Basically:
<div id="muteYouTubeVideoPlayer"></div>
<script async src="https://www.youtube.com/iframe_api"></script>
<script>
function onYouTubeIframeAPIReady() {
var player;
player = new YT.Player('muteYouTubeVideoPlayer', {
videoId: 'YOUR_VIDEO_ID', // YouTube Video ID
width: 560, // Player width (in px)
height: 316, // Player height (in px)
playerVars: {
autoplay: 1, // Auto-play the video on load
controls: 1, // Show pause/play buttons in player
showinfo: 0, // Hide the video title
modestbranding: 1, // Hide the Youtube Logo
loop: 1, // Run the video in a loop
fs: 0, // Hide the full screen button
cc_load_policy: 0, // Hide closed captions
iv_load_policy: 3, // Hide the Video Annotations
autohide: 0 // Hide video controls when playing
},
events: {
onReady: function(e) {
e.target.mute();
}
}
});
}
// Written by @labnol
</script>
calling another method from the main method in java
Check out for the static before the main method, this declares the method as a class method, which means it needs no instance to be called. So as you are going to call a non static method, Java complains because you are trying to call a so called "instance method", which, of course needs an instance first ;)
If you want a better understanding about classes and instances, create a new class with instance and class methods, create a object in your main loop and call the methods!
class Foo{
public static void main(String[] args){
Bar myInstance = new Bar();
myInstance.do(); // works!
Bar.do(); // doesn't work!
Bar.doSomethingStatic(); // works!
}
}
class Bar{
public do() {
// do something
}
public static doSomethingStatic(){
}
}
Also remember, classes in Java should start with an uppercase letter.
How to append in a json file in Python?
Assuming you have a test.json
file with the following content:
{"67790": {"1": {"kwh": 319.4}}}
Then, the code below will load
the json file, update the data inside using dict.update()
and dump
into the test.json
file:
import json
a_dict = {'new_key': 'new_value'}
with open('test.json') as f:
data = json.load(f)
data.update(a_dict)
with open('test.json', 'w') as f:
json.dump(data, f)
Then, in test.json
, you'll have:
{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}
Hope this is what you wanted.
Example of SOAP request authenticated with WS-UsernameToken
The Hash Password Support and Token Assertion Parameters in Metro 1.2 explains very nicely what a UsernameToken with Digest Password looks like:
Digest Password Support
The WSS 1.1 Username Token
Profile allows digest passwords to
be sent in a wsse:UsernameToken
of a
SOAP message. Two more optional
elements are included in the
wsse:UsernameToken
in this case:
wsse:Nonce
and wsse:Created
. A
nonce is a random value that the
sender creates to include in each
UsernameToken that it sends. A
creation time is added to combine
nonces to a "freshness" time period.
The Password Digest in this case is
calculated as:
Password_Digest = Base64 ( SHA-1 ( nonce + created + password ) )
This is how a UsernameToken with
Digest Password looks like:
<wsse:UsernameToken wsu:Id="uuid_faf0159a-6b13-4139-a6da-cb7b4100c10c">
<wsse:Username>Alice</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">6S3P2EWNP3lQf+9VC3emNoT57oQ=</wsse:Password>
<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">YF6j8V/CAqi+1nRsGLRbuZhi</wsse:Nonce>
<wsu:Created>2008-04-28T10:02:11Z</wsu:Created>
</wsse:UsernameToken>
How to implement authenticated routes in React Router 4?
Here is the simple clean protected route
const ProtectedRoute
= ({ isAllowed, ...props }) =>
isAllowed
? <Route {...props}/>
: <Redirect to="/authentificate"/>;
const _App = ({ lastTab, isTokenVerified })=>
<Switch>
<Route exact path="/authentificate" component={Login}/>
<ProtectedRoute
isAllowed={isTokenVerified}
exact
path="/secrets"
component={Secrets}/>
<ProtectedRoute
isAllowed={isTokenVerified}
exact
path="/polices"
component={Polices}/>
<ProtectedRoute
isAllowed={isTokenVerified}
exact
path="/grants" component={Grants}/>
<Redirect from="/" to={lastTab}/>
</Switch>
isTokenVerified
is a method call to check the authorization token basically it returns boolean.
Adding click event handler to iframe
iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...
function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
document.getElementById("theiframe").contentWindow.location.reload();
}
}
<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>
I hope it will helpful to you....
How to use bitmask?
Bit masking is "useful" to use when you want to store (and subsequently extract) different data within a single data value.
An example application I've used before is imagine you were storing colour RGB values in a 16 bit value. So something that looks like this:
RRRR RGGG GGGB BBBB
You could then use bit masking to retrieve the colour components as follows:
const unsigned short redMask = 0xF800;
const unsigned short greenMask = 0x07E0;
const unsigned short blueMask = 0x001F;
unsigned short lightGray = 0x7BEF;
unsigned short redComponent = (lightGray & redMask) >> 11;
unsigned short greenComponent = (lightGray & greenMask) >> 5;
unsigned short blueComponent = (lightGray & blueMask);
How to make borders collapse (on a div)?
You could also use negative margins:
_x000D_
_x000D_
.column {_x000D_
float: left;_x000D_
overflow: hidden;_x000D_
width: 120px;_x000D_
}_x000D_
.cell {_x000D_
border: 1px solid red;_x000D_
width: 120px;_x000D_
height: 20px;_x000D_
box-sizing: border-box;_x000D_
}_x000D_
.cell:not(:first-child) {_x000D_
margin-top: -1px;_x000D_
}_x000D_
.column:not(:first-child) > .cell {_x000D_
margin-left: -1px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="column">_x000D_
<div class="cell"></div>_x000D_
<div class="cell"></div>_x000D_
<div class="cell"></div>_x000D_
</div>_x000D_
<div class="column">_x000D_
<div class="cell"></div>_x000D_
<div class="cell"></div>_x000D_
<div class="cell"></div>_x000D_
</div>_x000D_
<div class="column">_x000D_
<div class="cell"></div>_x000D_
<div class="cell"></div>_x000D_
<div class="cell"></div>_x000D_
</div>_x000D_
<div class="column">_x000D_
<div class="cell"></div>_x000D_
<div class="cell"></div>_x000D_
<div class="cell"></div>_x000D_
</div>_x000D_
<div class="column">_x000D_
<div class="cell"></div>_x000D_
<div class="cell"></div>_x000D_
<div class="cell"></div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Only allow specific characters in textbox
private void txtuser_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsLetter(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
How to round up with excel VBA round()?
I got a workaround myself:
'G = Maximum amount of characters for width of comment cell
G = 100
'CommentX
If THISWB.Sheets("Source").Cells(i, CommentColumn).Value = "" Then
CommentX = ""
Else
CommentArray = Split(THISWB.Sheets("Source").Cells(i, CommentColumn).Value, Chr(10)) 'splits on alt + enter
DeliverableComment = "Available"
End If
If CommentX <> "" Then
'this loops for each newline in a cell (alt+enter in cell)
For CommentPart = 0 To UBound(CommentArray)
'format comment to max G characters long
LASTSPACE = 0
LASTSPACE2 = 0
If Len(CommentArray(CommentPart)) > G Then
'find last space in G length character string to make sure the line ends with a whole word and the new line starts with a whole word
Do Until LASTSPACE2 >= Len(CommentArray(CommentPart))
If CommentPart = 0 And LASTSPACE2 = 0 And LASTSPACE = 0 Then
LASTSPACE = WorksheetFunction.Find("Ă¾", WorksheetFunction.Substitute(Left(CommentArray(CommentPart), G), " ", "Ă¾", (Len(Left(CommentArray(CommentPart), G)) - Len(WorksheetFunction.Substitute(Left(CommentArray(CommentPart), G), " ", "")))))
ActiveCell.AddComment Left(CommentArray(CommentPart), LASTSPACE)
Else
If LASTSPACE2 = 0 Then
LASTSPACE = WorksheetFunction.Find("Ă¾", WorksheetFunction.Substitute(Left(CommentArray(CommentPart), G), " ", "Ă¾", (Len(Left(CommentArray(CommentPart), G)) - Len(WorksheetFunction.Substitute(Left(CommentArray(CommentPart), G), " ", "")))))
ActiveCell.Comment.Text Text:=ActiveCell.Comment.Text & vbNewLine & Left(CommentArray(CommentPart), LASTSPACE)
Else
If Len(Mid(CommentArray(CommentPart), LASTSPACE2)) < G Then
LASTSPACE = Len(Mid(CommentArray(CommentPart), LASTSPACE2))
ActiveCell.Comment.Text Text:=ActiveCell.Comment.Text & vbNewLine & Mid(CommentArray(CommentPart), LASTSPACE2 - 1, LASTSPACE)
Else
LASTSPACE = WorksheetFunction.Find("Ă¾", WorksheetFunction.Substitute(Mid(CommentArray(CommentPart), LASTSPACE2, G), " ", "Ă¾", (Len(Mid(CommentArray(CommentPart), LASTSPACE2, G)) - Len(WorksheetFunction.Substitute(Mid(CommentArray(CommentPart), LASTSPACE2, G), " ", "")))))
ActiveCell.Comment.Text Text:=ActiveCell.Comment.Text & vbNewLine & Mid(CommentArray(CommentPart), LASTSPACE2 - 1, LASTSPACE)
End If
End If
End If
LASTSPACE2 = LASTSPACE + LASTSPACE2 + 1
Loop
Else
If CommentPart = 0 And LASTSPACE2 = 0 And LASTSPACE = 0 Then
ActiveCell.AddComment CommentArray(CommentPart)
Else
ActiveCell.Comment.Text Text:=ActiveCell.Comment.Text & vbNewLine & CommentArray(CommentPart)
End If
End If
Next CommentPart
ActiveCell.Comment.Shape.TextFrame.AutoSize = True
End If
Feel free to thank me. Works like a charm to me and the autosize function also works!
Gets byte array from a ByteBuffer in java
Note that the bb.array() doesn't honor the byte-buffers position, and might be even worse if the bytebuffer you are working on is a slice of some other buffer.
I.e.
byte[] test = "Hello World".getBytes("Latin1");
ByteBuffer b1 = ByteBuffer.wrap(test);
byte[] hello = new byte[6];
b1.get(hello); // "Hello "
ByteBuffer b2 = b1.slice(); // position = 0, string = "World"
byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".
byte[] world = new byte[5];
b2.get(world); // world = "World"
Which might not be what you intend to do.
If you really do not want to copy the byte-array, a work-around could be to use the byte-buffer's arrayOffset() + remaining(), but this only works if the application supports index+length of the byte-buffers it needs.
Align a div to center
this works nicely
width:40%; // the width of the content div
right:0;
margin-right:30%; // 1/2 the remaining space
This resizes nicely with adaptive layouts also..
CSS example would be:
.centered-div {
position:fixed;
background-color:#fff;
text-align:center;
width:40%;
right:0;
margin-right:30%;
}
Fatal error: Namespace declaration statement has to be the very first statement in the script in
The library isn't working at all, setSizeLimit
is broken, setImageSize
is ignored as-well, just don't use this.
$result = $newUpload
->setFileTypes(array("jpg", "gif", "png", "jpeg"))
->setSizeLimit(array("min"=>100, "max"=>100000))
->setImageSize(array("height"=>200, "width"=>200))
->uploadTo('ads/')
->save($_FILES['newad_image']);
$page.=$result;
Gives this:
Notice: Undefined offset: 1 in C:\xampp\htdocs\project\lib\ImageUploader.php on line 229
Notice: Undefined offset: 0 in C:\xampp\htdocs\project\lib\ImageUploader.php on line 229
EDIT: The size seems to be in Bytes, even though the error says Kilobytes.
How to animate GIFs in HTML document?
try
_x000D_
_x000D_
<img src="https://cdn.glitch.com/0e4d1ff3-5897-47c5-9711-d026c01539b8%2Fbddfd6e4434f42662b009295c9bab86e.gif?v=1573157191712" alt="this slowpoke moves" width="250" alt="404 image"/>
_x000D_
_x000D_
_x000D_
and switch the src with your source. If the alt pops up, try a different url. If it doesn't work, restart your computer or switch your browser.
Import JSON file in React
there are multiple ways to do this without using any third-party code or libraries (the recommended way).
1st STATIC WAY: create a .json file then import it in your react component example
my file name is "example.json"
{"example" : "my text"}
the example key inside the example.json can be anything just keep in mind to use double quotes to prevent future issues.
How to import in react component
import myJson from "jsonlocation";
and you can use it anywhere like this
myJson.example
now there are a few things to consider. With this method, you are forced to declare your import at the top of the page and cannot dynamically import anything.
Now, what about if we want to dynamically import the JSON data? example a multi-language support website?
2 DYNAMIC WAY
1st declare your JSON file exactly like my example above
but this time we are importing the data differently.
let language = require('./en.json');
this can access the same way.
but wait where is the dynamic load?
here is how to load the JSON dynamically
let language = require(`./${variable}.json`);
now make sure all your JSON files are within the same directory
here you can use the JSON the same way as the first example
myJson.example
what changed? the way we import because it is the only thing we really need.
I hope this helps.
REST API - file (ie images) processing - best practices
Your second solution is probably the most correct. You should use the HTTP spec and mimetypes the way they were intended and upload the file via multipart/form-data
. As far as handling the relationships, I'd use this process (keeping in mind I know zero about your assumptions or system design):
POST
to /users
to create the user entity.
POST
the image to /images
, making sure to return a Location
header to where the image can be retrieved per the HTTP spec.
PATCH
to /users/carPhoto
and assign it the ID of the photo given in the Location
header of step 2.
Java, How to implement a Shift Cipher (Caesar Cipher)
Hello...I have created a java client server application in swing for caesar cipher...I have created a new formula that can decrypt the text properly...
sorry only for lower case..!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarserver extends JFrame implements ActionListener {
static String cs = "abcdefghijklmnopqrstuvwxyz";
static JLabel l1, l2, l3, l5, l6;
JTextField t1;
JButton close, b1;
static String en;
int num = 0;
JProgressBar progress;
ceasarserver() {
super("SERVER");
JPanel p = new JPanel(new GridLayout(10, 1));
l1 = new JLabel("");
l2 = new JLabel("");
l3 = new JLabel("");
l5 = new JLabel("");
l6 = new JLabel("Enter the Key...");
t1 = new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
close = new JButton("Close");
close.setMnemonic('C');
close.setPreferredSize(new Dimension(300, 25));
close.addActionListener(this);
b1 = new JButton("Decrypt");
b1.setMnemonic('D');
b1.addActionListener(this);
p.add(l1);
p.add(l2);
p.add(l3);
p.add(l6);
p.add(t1);
p.add(b1);
p.add(progress);
p.add(l5);
p.add(close);
add(p);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == close)
System.exit(0);
else if (e.getSource() == b1) {
int key = Integer.parseInt(t1.getText());
String d = "";
int i = 0, j, k;
while (i < en.length()) {
j = cs.indexOf(en.charAt(i));
k = (j + (26 - key)) % 26;
d = d + cs.charAt(k);
i++;
}
while (num < 21) {
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
progress.setValue(num);
Rectangle progressRect = progress.getBounds();
progressRect.x = 0;
progressRect.y = 0;
progress.paintImmediately(progressRect);
num++;
}
l5.setText("Decrypted text: " + d);
}
}
public static void main(String args[]) throws IOException {
new ceasarserver();
String strm = new String();
ServerSocket ss = new ServerSocket(4321);
l1.setText("Secure data transfer Server Started....");
Socket s = ss.accept();
l2.setText("Client Connected !");
while (true) {
Scanner br1 = new Scanner(s.getInputStream());
en = br1.nextLine();
l3.setText("Client:" + en);
}
}
The client class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarclient extends JFrame {
String cs = "abcdefghijklmnopqrstuvwxyz";
static JLabel l1, l2, l3, l4, l5;
JButton b1, b2, b3;
JTextField t1, t2;
JProgressBar progress;
int num = 0;
String en = "";
ceasarclient(final Socket s) {
super("CLIENT");
JPanel p = new JPanel(new GridLayout(10, 1));
setSize(500, 500);
t1 = new JTextField(30);
b1 = new JButton("Send");
b1.setMnemonic('S');
b2 = new JButton("Close");
b2.setMnemonic('C');
l1 = new JLabel("Welcome to Secure Data transfer!");
l2 = new JLabel("Enter the word here...");
l3 = new JLabel("");
l4 = new JLabel("Enter the Key:");
b3 = new JButton("Encrypt");
b3.setMnemonic('E');
t2 = new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
p.add(l1);
p.add(l2);
p.add(t1);
p.add(l4);
p.add(t2);
p.add(b3);
p.add(progress);
p.add(b1);
p.add(l3);
p.add(b2);
add(p);
setVisible(true);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(en);
} catch (Exception ex) {
}
;
l3.setText("Encrypted Text Sent.");
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String strw = t1.getText();
int key = Integer.parseInt(t2.getText());
int i = 0, j, k;
while (i < strw.length()) {
j = cs.indexOf(strw.charAt(i));
k = (j + key) % 26;
en = en + cs.charAt(k);
i++;
}
while (num < 21) {
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException exe) {
}
progress.setValue(num);
Rectangle progressRect = progress.getBounds();
progressRect.x = 0;
progressRect.y = 0;
progress.paintImmediately(progressRect);
num++;
}
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pack();
}
public static void main(String args[]) throws IOException {
final Socket s = new Socket(InetAddress.getLocalHost(), 4321);
new ceasarclient(s);
}
}
IntelliJ how to zoom in / out
File>Settings...>Editor>General>
then you'll find this in the menu Mouse,
"change the font size(Zoom) with Ctrl+Mouse Wheel"
Wrapping a react-router Link in an html button
Update for React Router version 6:
The various answers here are like a timeline of react-router's evolution
Using the latest hooks from react-router v6, this can now be done easily with the useNavigate
hook.
import { useNavigate } from 'react-router-dom'
function MyLinkButton() {
const navigate = useNavigate()
return (
<button onClick={() => navigate("/home")}>
Go Home
</button>
);
}
Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?
After commenting @Marcin answer, I have more carefully checked one of my students code where I found the same weird behavior, even after only 2 epochs ! (So @Marcin's explanation was not very likely in my case).
And I found that the answer is actually very simple: the accuracy computed with the Keras method evaluate
is just plain wrong when using binary_crossentropy with more than 2 labels. You can check that by recomputing the accuracy yourself (first call the Keras method "predict" and then compute the number of correct answers returned by predict): you get the true accuracy, which is much lower than the Keras "evaluate" one.
AngularJS $location not changing the path
I had this same problem, but my call to $location was ALREADY within a digest. Calling $apply() just gave a $digest already in process error.
This trick worked (and be sure to inject $location
into your controller):
$timeout(function(){
$location...
},1);
Though no idea why this was necessary...
Get user's non-truncated Active Directory groups from command line
A little stale post, but I figured what the heck. Does "whoami" meet your needs?
I just found out about it today (from the same Google search that brought me here, in fact). Windows has had a whoami tool since XP (part of an add on toolkit) and has been built-in since Vista.
whoami /groups
Lists all the AD groups for the currently logged-on user. I believe it does require you to be logged on AS that user, though, so this won't help if your use case requires the ability to run the command to look at another user.
Group names only:
whoami /groups /fo list |findstr /c:"Group Name:"
Missing Microsoft RDLC Report Designer in Visual Studio
This trouble passed me. If you can't repair this trouble, perhaps can you review all Framework versions that you have in your system. For example, if you have ReportViewer for Framework 4.5 and your project is assembly in Framework 2 or another Framework minor at 4.5. The differents versions Framework sometime have problems.
Login failed for user 'DOMAIN\MACHINENAME$'
A colleague had the same error and it was due to a little configuration error in IIS.
The wrong Application Pool was assigned for the web application.
Indeed we use a custom Application Pool with a specific Identity to meet our needs.
In his local IIS Manager -> Sites -> Default Web Site -> Our Web App Name -> Basic Settings...
The Application Pool was "DefaultAppPool" instead of our custom Application Pool.
Setting the correct application pool solved the problem.
Function passed as template argument
Function pointers can be passed as template parameters, and this is part of standard C++
. However in the template they are declared and used as functions rather than pointer-to-function. At template instantiation one passes the address of the function rather than just the name.
For example:
int i;
void add1(int& i) { i += 1; }
template<void op(int&)>
void do_op_fn_ptr_tpl(int& i) { op(i); }
i = 0;
do_op_fn_ptr_tpl<&add1>(i);
If you want to pass a functor type as a template argument:
struct add2_t {
void operator()(int& i) { i += 2; }
};
template<typename op>
void do_op_fntr_tpl(int& i) {
op o;
o(i);
}
i = 0;
do_op_fntr_tpl<add2_t>(i);
Several answers pass a functor instance as an argument:
template<typename op>
void do_op_fntr_arg(int& i, op o) { o(i); }
i = 0;
add2_t add2;
// This has the advantage of looking identical whether
// you pass a functor or a free function:
do_op_fntr_arg(i, add1);
do_op_fntr_arg(i, add2);
The closest you can get to this uniform appearance with a template argument is to define do_op
twice- once with a non-type parameter and once with a type parameter.
// non-type (function pointer) template parameter
template<void op(int&)>
void do_op(int& i) { op(i); }
// type (functor class) template parameter
template<typename op>
void do_op(int& i) {
op o;
o(i);
}
i = 0;
do_op<&add1>(i); // still need address-of operator in the function pointer case.
do_op<add2_t>(i);
Honestly, I really expected this not to compile, but it worked for me with gcc-4.8 and Visual Studio 2013.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
How to add button in ActionBar(Android)?
you have to create an entry inside res/menu,
override onCreateOptionsMenu
and inflate it
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.yourentry, menu);
return true;
}
an entry for the menu could be:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_cart"
android:icon="@drawable/cart"
android:orderInCategory="100"
android:showAsAction="always"/>
</menu>
How do I use a Boolean in Python?
Boolean types are defined in documentation:
http://docs.python.org/library/stdtypes.html#boolean-values
Quoted from doc:
Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to cast any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).
They are written as False and True, respectively.
So in java code remove braces, change true
to True
and you will be ok :)
VBA - Select columns using numbers?
In this way, you can start to select data even behind column "Z" and select a lot of columns.
Sub SelectColumNums()
Dim xCol1 As Integer, xNumOfCols as integer
xCol1 = 26
xNumOfCols = 17
Range(Columns(xCol1), Columns(xCol1 + xNumOfCols)).Select
End Sub
Number of occurrences of a character in a string
Because LINQ
can do everything...:
string test = "key1=value1&key2=value2&key3=value3";
var count = test.Where(x => x == '&').Count();
Or if you like, you can use the Count
overload that takes a predicate :
var count = test.Count(x => x == '&');
Unable to locate tools.jar
No, according to your directory structure, you have installed a JRE, not a JDK. There's a difference.
C:\Program Files\Java\jre6\lib
^^^^
It should be something like:
C:\Program Files\Java\jdk1.6.0_24
enum to string in modern C++11 / C++14 / C++17 and future C++20
If your enum
looks like
enum MyEnum
{
AAA = -8,
BBB = '8',
CCC = AAA + BBB
};
You can move the content of the enum
to a new file:
AAA = -8,
BBB = '8',
CCC = AAA + BBB
And then the values can be surrounded by a macro:
// default definition
#ifned ITEM(X,Y)
#define ITEM(X,Y)
#endif
// Items list
ITEM(AAA,-8)
ITEM(BBB,'8')
ITEM(CCC,AAA+BBB)
// clean up
#undef ITEM
Next step may be include the items in the enum
again:
enum MyEnum
{
#define ITEM(X,Y) X=Y,
#include "enum_definition_file"
};
And finally you can generate utility functions about this enum
:
std::string ToString(MyEnum value)
{
switch( value )
{
#define ITEM(X,Y) case X: return #X;
#include "enum_definition_file"
}
return "";
}
MyEnum FromString(std::string const& value)
{
static std::map<std::string,MyEnum> converter
{
#define ITEM(X,Y) { #X, X },
#include "enum_definition_file"
};
auto it = converter.find(value);
if( it != converter.end() )
return it->second;
else
throw std::runtime_error("Value is missing");
}
The solution can be applied to older C++ standards and it does not use modern C++ elements but it can be used to generate lot of code without too much effort and maintenance.
Design Documents (High Level and Low Level Design Documents)
High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.
LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.
Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.
As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.
Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.
String isNullOrEmpty in Java?
To check if a string got any characters, ie. not null or whitespaces, check StringUtils.hasText
-method (if you are using Spring of course)
Example:
StringUtils.hasText(null) == false
StringUtils.hasText("") == false
StringUtils.hasText(" ") == false
StringUtils.hasText("12345") == true
StringUtils.hasText(" 12345 ") == true
Set background image according to screen resolution
Put into css file:
html { background: url(images/bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; }
URL images/bg.jpg is your background image
Add characters to a string in Javascript
You can also keep adding strings to an existing string like so:
var myString = "Hello ";
myString += "World";
myString += "!";
the result would be -> Hello World!
Passing Parameters JavaFX FXML
You have to create one Context Class.
public class Context {
private final static Context instance = new Context();
public static Context getInstance() {
return instance;
}
private Connection con;
public void setConnection(Connection con)
{
this.con=con;
}
public Connection getConnection() {
return con;
}
private TabRoughController tabRough;
public void setTabRough(TabRoughController tabRough) {
this.tabRough=tabRough;
}
public TabRoughController getTabRough() {
return tabRough;
}
}
You have to just set instance of controller in initialization using
Context.getInstance().setTabRough(this);
and you can use it from your whole application just using
TabRoughController cont=Context.getInstance().getTabRough();
Now you can pass parameter to any controller from whole application.
Initializing array of structures
It's a designated initializer, introduced with the C99 standard; it allows you to initialize specific members of a struct or union object by name. my_data
is obviously a typedef for a struct
type that has a member name
of type char *
or char [N]
.
concatenate char array in C
in rare cases when you can't use strncat
, strcat
or strcpy
. And you don't have access to <string.h>
so you can't use strlen
. Also you maybe don't even know the size of the char arrays and you still want to concatenate because you got only pointers. Well, you can do old school malloc and count characters yourself like..
char *combineStrings(char* inputA, char* inputB) {
size_t len = 0, lenB = 0;
while(inputA[len] != '\0') len++;
while(inputB[lenB] != '\0') lenB++;
char* output = malloc(len+lenB);
sprintf((char*)output,"%s%s",inputA,inputB);
return output;
}
It just needs #include <stdio.h>
which you will have most likely included already
SQL Server SELECT into existing table
It would work as given below :
insert into Gengl_Del Select Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration
from Gengl where BOOK='" & lblBook.Caption & "' AND DocNO=" & txtVno.Text & ""
MySQL: Get column name or alias from query
I think this should do what you need (builds on the answer above) . I am sure theres a more pythony way to write it, but you should get the general idea.
cursor.execute(query)
columns = cursor.description
result = []
for value in cursor.fetchall():
tmp = {}
for (index,column) in enumerate(value):
tmp[columns[index][0]] = column
result.append(tmp)
pprint.pprint(result)
What does 'stale file handle' in Linux mean?
When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).
Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle
message because you asked for some nonexistent data.
When you perform a cd
operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.
How do I add indices to MySQL tables?
A better option is to add the constraints directly during CREATE TABLE query (assuming you have the information about the tables)
CREATE TABLE products(
productId INT AUTO_INCREMENT PRIMARY KEY,
productName varchar(100) not null,
categoryId INT NOT NULL,
CONSTRAINT fk_category
FOREIGN KEY (categoryId)
REFERENCES categories(categoryId)
ON UPDATE CASCADE
ON DELETE CASCADE
) ENGINE=INNODB;
Regular expression matching a multiline block of text
My preference.
lineIter= iter(aFile)
for line in lineIter:
if line.startswith( ">" ):
someVaryingText= line
break
assert len( lineIter.next().strip() ) == 0
acids= []
for line in lineIter:
if len(line.strip()) == 0:
break
acids.append( line )
At this point you have someVaryingText as a string, and the acids as a list of strings.
You can do "".join( acids )
to make a single string.
I find this less frustrating (and more flexible) than multiline regexes.
Java - Using Accessor and Mutator methods
You need to remove the static
from your accessor methods - these methods need to be instance methods and access the instance variables
public class IDCard {
public String name, fileName;
public int id;
public IDCard(final String name, final String fileName, final int id) {
this.name = name;
this.fileName = fileName
this.id = id;
}
public String getName() {
return name;
}
}
You can the create an IDCard
and use the accessor like this:
final IDCard card = new IDCard();
card.getName();
Each time you call new
a new instance of the IDCard
will be created and it will have it's own copies of the 3 variables.
If you use the static
keyword then those variables are common across every instance of IDCard
.
A couple of things to bear in mind:
- don't add useless comments - they add code clutter and nothing else.
- conform to naming conventions, use lower case of variable names -
name
not Name
.
How to detect pressing Enter on keyboard using jQuery?
$(document).keydown(function (event) {
//proper indentiation of keycode and which to be equal to 13.
if ( (event.keyCode || event.which) === 13) {
// Cancel the default action, if needed
event.preventDefault();
//call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
$("#btnsearch").trigger('click');
}
});
Android SDK installation doesn't find JDK
I spent a little over an hour trying just about every option presented. I eventually figured out that I had a lot of stale entries for software that I had uninstalled. I deleted all the registry nodes that had any stale data (pointed to the wrong directory). This included the
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime
Environment]
and
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment]
entries as a JRE included in the JDK.
I also got rid of all the JAVA entries in my environmental variables. I guess I blame it on bad uninstallers that do not clean up after themselves.
Get the POST request body from HttpServletRequest
I resolved that situation in this way. I created a util method that return a object extracted from request body, using the readValue method of ObjectMapper that is capable of receiving a Reader.
public static <T> T getBody(ResourceRequest request, Class<T> class) {
T objectFromBody = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
HttpServletRequest httpServletRequest = PortalUtil.getHttpServletRequest(request);
objectFromBody = objectMapper.readValue(httpServletRequest.getReader(), class);
} catch (IOException ex) {
log.error("Error message", ex);
}
return objectFromBody;
}
How to center a subview of UIView
This worked for me
childView.centerXAnchor.constraint(equalTo: parentView.centerXAnchor).isActive = true
childView.centerYAnchor.constraint(equalTo: parentView.centerYAnchor).isActive = true
Fastest way to count number of occurrences in a Python list
a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
print a.count("1")
It's probably optimized heavily at the C level.
Edit: I randomly generated a large list.
In [8]: len(a)
Out[8]: 6339347
In [9]: %timeit a.count("1")
10 loops, best of 3: 86.4 ms per loop
Edit edit: This could be done with collections.Counter
a = Counter(your_list)
print a['1']
Using the same list in my last timing example
In [17]: %timeit Counter(a)['1']
1 loops, best of 3: 1.52 s per loop
My timing is simplistic and conditional on many different factors, but it gives you a good clue as to performance.
Here is some profiling
In [24]: profile.run("a.count('1')")
3 function calls in 0.091 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.091 0.091 <string>:1(<module>)
1 0.091 0.091 0.091 0.091 {method 'count' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
In [25]: profile.run("b = Counter(a); b['1']")
6339356 function calls in 2.143 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.143 2.143 <string>:1(<module>)
2 0.000 0.000 0.000 0.000 _weakrefset.py:68(__contains__)
1 0.000 0.000 0.000 0.000 abc.py:128(__instancecheck__)
1 0.000 0.000 2.143 2.143 collections.py:407(__init__)
1 1.788 1.788 2.143 2.143 collections.py:470(update)
1 0.000 0.000 0.000 0.000 {getattr}
1 0.000 0.000 0.000 0.000 {isinstance}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
6339347 0.356 0.000 0.356 0.000 {method 'get' of 'dict' objects}
Print a list of space-separated elements in Python 3
Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.
The best way is to print joined string of numbers converted to strings.
print(" ".join(list(map(str,l))))
Note that I used map instead of loop.
I wrote a little code of all 4 different ways to compare time:
import time as t
a, b = 10, 210000
l = list(range(a, b))
tic = t.time()
for i in l:
print(i, end=" ")
print()
tac = t.time()
t1 = (tac - tic) * 1000
print(*l)
toe = t.time()
t2 = (toe - tac) * 1000
print(" ".join([str(i) for i in l]))
joe = t.time()
t3 = (joe - toe) * 1000
print(" ".join(list(map(str, l))))
toy = t.time()
t4 = (toy - joe) * 1000
print("Time",t1,t2,t3,t4)
Result:
Time 74344.76 71790.83 196.99 153.99
The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.
Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).
find vs find_by vs where
Apart from accepted answer, following is also valid
Model.find()
can accept array of ids, and will return all records which matches.
Model.find_by_id(123)
also accept array but will only process first id value present in array
Model.find([1,2,3])
Model.find_by_id([1,2,3])
C# generic list <T> how to get the type of T?
Given an object which I suspect to be some kind of IList<>
, how can I determine of what it's an IList<>
?
Here's a reliable solution. My apologies for length - C#'s introspection API makes this suprisingly difficult.
/// <summary>
/// Test if a type implements IList of T, and if so, determine T.
/// </summary>
public static bool TryListOfWhat(Type type, out Type innerType)
{
Contract.Requires(type != null);
var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);
innerType = interfaceTest(type);
if (innerType != null)
{
return true;
}
foreach (var i in type.GetInterfaces())
{
innerType = interfaceTest(i);
if (innerType != null)
{
return true;
}
}
return false;
}
Example usage:
object value = new ObservableCollection<int>();
Type innerType;
TryListOfWhat(value.GetType(), out innerType).Dump();
innerType.Dump();
Returns
True
typeof(Int32)
What data is stored in Ephemeral Storage of Amazon EC2 instance?
Basically, root volume (your entire virtual system disk) is ephemeral, but only if you choose to create AMI backed by Amazon EC2 instance store.
If you choose to create AMI backed by EBS then your root volume is backed by EBS and everything you have on your root volume will be saved between reboots.
If you are not sure what type of volume you have, look under EC2->Elastic Block Store->Volumes in your AWS console and if your AMI root volume is listed there then you are safe. Also, if you go to EC2->Instances and then look under column "Root device type" of your instance and if it says "ebs", then you don't have to worry about data on your root device.
More details here: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/RootDeviceStorage.html
Returning multiple values from a C++ function
The OO solution for this is to create a ratio class. It wouldn't take any extra code (would save some), would be significantly cleaner/clearer, and would give you some extra refactorings letting you clean up code outside this class as well.
Actually I think someone recommended returning a structure, which is close enough but hides the intent that this needs to be a fully thought-out class with constructor and a few methods, in fact, the "method" that you originally mentioned (as returning the pair) should most likely be a member of this class returning an instance of itself.
I know your example was just an "Example", but the fact is that unless your function is doing way more than any function should be doing, if you want it to return multiple values you are almost certainly missing an object.
Don't be afraid to create these tiny classes to do little pieces of work--that's the magic of OO--you end up breaking it down until every method is very small and simple and every class small and understandable.
Another thing that should have been an indicator that something was wrong: in OO you have essentially no data--OO isn't about passing around data, a class needs to manage and manipulate it's own data internally, any data passing (including accessors) is a sign that you may need to rethink something..
How do I filter date range in DataTables?
Here is my solution, cobbled together from the range filter example in the datatables docs, and letting moment.js do the dirty work of comparing the dates.
HTML
<input
type="text"
id="min-date"
class="date-range-filter"
placeholder="From: yyyy-mm-dd">
<input
type="text"
id="max-date"
class="date-range-filter"
placeholder="To: yyyy-mm-dd">
<table id="my-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Created At</th>
</tr>
</thead>
</table>
JS
Install Moment: npm install moment
// Assign moment to global namespace
window.moment = require('moment');
// Set up your table
table = $('#my-table').DataTable({
// ... do your thing here.
});
// Extend dataTables search
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var min = $('#min-date').val();
var max = $('#max-date').val();
var createdAt = data[2] || 0; // Our date column in the table
if (
( min == "" || max == "" )
||
( moment(createdAt).isSameOrAfter(min) && moment(createdAt).isSameOrBefore(max) )
)
{
return true;
}
return false;
}
);
// Re-draw the table when the a date range filter changes
$('.date-range-filter').change( function() {
table.draw();
} );
Notes
- Using moment decouples the date comparison logic, and makes it easy to work with different formats. In my table, I used
yyyy-mm-dd
, but you could use mm/dd/yyyy
as well. Be sure to reference moment's docs when parsing other formats, as you may need to modify what method you use.
Java SecurityException: signer information does not match
I am having this problem with Eclipse and JUnit 5.
My solution is inspired by the previous answer by user2066936
It is to reconfig the ordering of the import libraries:
- Right click the project.
- Open [Java Build Path].
- Click Order and Export.
- Then push JUNIT to upper priority.
How to terminate a thread when main program ends?
If you spawn a Thread like so - myThread = Thread(target = function)
- and then do myThread.start(); myThread.join()
. When CTRL-C is initiated, the main thread doesn't exit because it is waiting on that blocking myThread.join()
call. To fix this, simply put in a timeout on the .join() call. The timeout can be as long as you wish. If you want it to wait indefinitely, just put in a really long timeout, like 99999. It's also good practice to do myThread.daemon = True
so all the threads exit when the main thread(non-daemon) exits.
POST an array from an HTML form without javascript
You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:
<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>
If you use php:
print_r($_POST['comment'])
you will get this:
Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )
How to check whether a string is Base64 encoded or not
C#
This is performing great:
static readonly Regex _base64RegexPattern = new Regex(BASE64_REGEX_STRING, RegexOptions.Compiled);
private const String BASE64_REGEX_STRING = @"^[a-zA-Z0-9\+/]*={0,3}$";
private static bool IsBase64(this String base64String)
{
var rs = (!string.IsNullOrEmpty(base64String) && !string.IsNullOrWhiteSpace(base64String) && base64String.Length != 0 && base64String.Length % 4 == 0 && !base64String.Contains(" ") && !base64String.Contains("\t") && !base64String.Contains("\r") && !base64String.Contains("\n")) && (base64String.Length % 4 == 0 && _base64RegexPattern.Match(base64String, 0).Success);
return rs;
}
Skip a submodule during a Maven build
The notion of multi-module projects is there to service the needs of codependent segments of a project. Such a client depends on the services which in turn depends on say EJBs or data-access routines. You could group your continuous integration (CI) tests in this manner. I would rationalize that by saying that the CI tests need to be in lock-step with application logic changes.
Suppose your project is structured as:
project-root
|
+ --- ci
|
+ --- client
|
+ --- server
The project-root/pom.xml
defines modules
<modules>
<module>ci</module>
<module>client</module>
<module>server</module>
</modules>
The ci/pom.xml
defines profiles such as:
...
<profiles>
<profile>
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</profile>
<profile>
<id>CI</id>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>false</skip>
</configuration>
</plugin>
</profile>
</profiles>
This will result in Maven skipping tests in this module except when the profile named CI
is active.
Your CI server must be instructed to execute mvn clean package -P CI
. The Maven web site has an in-depth explanation of the profiling mechanism.
What is a pre-revprop-change hook in SVN, and how do I create it?
For Windows, here's a link to an example batch file that only allows changes to the log message (not other properties):
http://ayria.livejournal.com/33438.html
Basically copy the code below into a text file and name it pre-revprop-change.bat
and save it in the \hooks
subdirectory for your repository.
@ECHO OFF
:: Set all parameters. Even though most are not used, in case you want to add
:: changes that allow, for example, editing of the author or addition of log messages.
set repository=%1
set revision=%2
set userName=%3
set propertyName=%4
set action=%5
:: Only allow the log message to be changed, but not author, etc.
if /I not "%propertyName%" == "svn:log" goto ERROR_PROPNAME
:: Only allow modification of a log message, not addition or deletion.
if /I not "%action%" == "M" goto ERROR_ACTION
:: Make sure that the new svn:log message is not empty.
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if "%bIsEmpty%" == "true" goto ERROR_EMPTY
goto :eof
:ERROR_EMPTY
echo Empty svn:log messages are not allowed. >&2
goto ERROR_EXIT
:ERROR_PROPNAME
echo Only changes to svn:log messages are allowed. >&2
goto ERROR_EXIT
:ERROR_ACTION
echo Only modifications to svn:log revision properties are allowed. >&2
goto ERROR_EXIT
:ERROR_EXIT
exit /b 1
php get values from json encode
json_decode()
will return an object or array if second value it's true:
$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];
DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"
I bumped into this problem lately with Windows 10 from another direction, and found the answer from @JonSkeet very helpful in solving my problem.
I also did som further research with a test form and found that when the the current culture was set to "no"
or "nb-NO"
at runtime (Thread.CurrentThread.CurrentCulture = new CultureInfo("no");
), the ToString("yyyy-MM-dd HH:mm:ss") call responded differently in Windows 7 and Windows 10. It returned what I expected in Windows 7 and HH.mm.ss in Windows 10!
I think this is a bit scary! Since I believed that a culture was a culture in any Windows version at least.
How To Remove Outline Border From Input Button
using outline:none; we can remove that border in chrome
<style>
input[type="button"]
{
width:120px;
height:60px;
margin-left:35px;
display:block;
background-color:gray;
color:white;
border: none;
outline:none;
}
</style>
fill an array in C#
you could write an extension method
public static void Fill<T>(this T[] array, T value)
{
for(int i = 0; i < array.Length; i++)
{
array[i] = value;
}
}
How to include another XHTML in XHTML using JSF 2.0 Facelets?
<ui:include>
Most basic way is <ui:include>
. The included content must be placed inside <ui:composition>
.
Kickoff example of the master page /page.xhtml
:
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title>Include demo</title>
</h:head>
<h:body>
<h1>Master page</h1>
<p>Master page blah blah lorem ipsum</p>
<ui:include src="/WEB-INF/include.xhtml" />
</h:body>
</html>
The include page /WEB-INF/include.xhtml
(yes, this is the file in its entirety, any tags outside <ui:composition>
are unnecessary as they are ignored by Facelets anyway):
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h2>Include page</h2>
<p>Include page blah blah lorem ipsum</p>
</ui:composition>
This needs to be opened by /page.xhtml
. Do note that you don't need to repeat <html>
, <h:head>
and <h:body>
inside the include file as that would otherwise result in invalid HTML.
You can use a dynamic EL expression in <ui:include src>
. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).
<ui:define>
/<ui:insert>
A more advanced way of including is templating. This includes basically the other way round. The master template page should use <ui:insert>
to declare places to insert defined template content. The template client page which is using the master template page should use <ui:define>
to define the template content which is to be inserted.
Master template page /WEB-INF/template.xhtml
(as a design hint: the header, menu and footer can in turn even be <ui:include>
files):
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title><ui:insert name="title">Default title</ui:insert></title>
</h:head>
<h:body>
<div id="header">Header</div>
<div id="menu">Menu</div>
<div id="content"><ui:insert name="content">Default content</ui:insert></div>
<div id="footer">Footer</div>
</h:body>
</html>
Template client page /page.xhtml
(note the template
attribute; also here, this is the file in its entirety):
<ui:composition template="/WEB-INF/template.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<ui:define name="title">
New page title here
</ui:define>
<ui:define name="content">
<h1>New content here</h1>
<p>Blah blah</p>
</ui:define>
</ui:composition>
This needs to be opened by /page.xhtml
. If there is no <ui:define>
, then the default content inside <ui:insert>
will be displayed instead, if any.
<ui:param>
You can pass parameters to <ui:include>
or <ui:composition template>
by <ui:param>
.
<ui:include ...>
<ui:param name="foo" value="#{bean.foo}" />
</ui:include>
<ui:composition template="...">
<ui:param name="foo" value="#{bean.foo}" />
...
</ui:composition >
Inside the include/template file, it'll be available as #{foo}
. In case you need to pass "many" parameters to <ui:include>
, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <my:tagname foo="#{bean.foo}">
. See also When to use <ui:include>, tag files, composite components and/or custom components?
You can even pass whole beans, methods and parameters via <ui:param>
. See also JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?
Design hints
The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in /WEB-INF
folder, like as the include file and the template file in above example. See also Which XHTML files do I need to put in /WEB-INF and which not?
There doesn't need to be any markup (HTML code) outside <ui:composition>
and <ui:define>
. You can put any, but they will be ignored by Facelets. Putting markup in there is only useful for web designers. See also Is there a way to run a JSF page without building the whole project?
The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also Is it possible to use JSF+Facelets with HTML 4/5? and JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used.
CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also How to reference CSS / JS / image resource in Facelets template?
You can put Facelets files in a reusable JAR file. See also Structure for multiple JSF projects with shared code.
For real world examples of advanced Facelets templating, check the src/main/webapp
folder of Java EE Kickoff App source code and OmniFaces showcase site source code.