Well, once you have your font, you can invoke deriveFont
. For example,
helvetica = helvetica.deriveFont(Font.BOLD, 12f);
Changes the font's style to bold and its size to 12 points.
CSS min() and max() have fairly good usage rates in 2020.
The code below uses max() to get the largest of the [variablevalue] and [minimumvalue] and then passes that through to min() against the [maximumvalue] to get the smaller of the two. This creates an allowable font range (3.5rem is minimum, 6.5rem is maximum, 6vw is used only when in between).
font-size: min(max([variablevalue], [minimumvalue]), [maximumvalue]);
font-size: min(max(6vw, 3.5rem), 6.5rem);
I'm using this specifically with font-awesome as a video-play icon over an image within a bootstrap container element where max-width is set.
For a different approach, I would suggest using the XeTeX or LuaTex system. They allow you to access system fonts (TrueType, OpenType, etc) and set font features. In a typical LaTeX document, you just need to include this in your headers:
\usepackage{fontspec}
\defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
\setmainfont{Times}
\setmonofont{Lucida Sans Typewriter}
It's the fontspec
package that allows for \setmainfont
and \setmonofont
. The ability to choose a multitude of font features is beyond my expertise, but I would suggest looking up some examples and seeing if this would suit your needs.
Just don't forget to replace your favorite latex compiler by the appropriate one (xelatex or lualatex).
You can always use
UIFont *systemFont = [UIFont systemFontOfSize:12];
NSLog(@"what is it? %@ %@", systemFont.familyName, systemFont.fontName);
The answer is:
Up to iOS 6
Helvetica Helvetica
iOS 7
.Helvetica Neue Interface .HelveticaNeueInterface-M3
but you can just use Helvetica Neue
I use this method in my css file
@font-face {
font-family: FontName1;
src: url("fontname1.eot"); /* IE */
src: local('FontName1'), url('fontname1.ttf') format('truetype'); /* others */
}
@font-face {
font-family: FontName2;
src: url("fontname1.eot"); /* IE */
src: local('FontName2'), url('fontname2.ttf') format('truetype'); /* others */
}
@font-face {
font-family: FontName3;
src: url("fontname1.eot"); /* IE */
src: local('FontName3'), url('fontname3.ttf') format('truetype'); /* others */
}
Or add styles inline:
<p style="font-size:18px">Paragraph 1</p>
<p style="font-size:16px">Paragraph 2</p>
Look here http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#deriveFont%28float%29
JComponent has a setFont() method. You will control the font there, not on the String.
Such as
JButton b = new JButton();
b.setFont(b.getFont().deriveFont(18.0f));
To add to MattDMo's answer, you can get the exact font that's used on Linux like so (the example is from Xubuntu 14.04):
$ fc-match Monospace
DejaVuSansMono.ttf: "DejaVu Sans Mono" "Book"
My Swift code for change Navigation Bar title:
let attributes = [NSFontAttributeName : UIFont(name: "Roboto-Medium", size: 16)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
self.navigationController.navigationBar.titleTextAttributes = attributes
And if you want to change background font too then I have this in my AppDelegate:
let attributes = [NSFontAttributeName : UIFont(name: "Roboto-Medium", size: 16)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
UIBarButtonItem.appearance().setTitleTextAttributes(attributes, forState: UIControlState.Normal)
To change the font globally for ggplot2 plots.
theme_set(theme_gray(base_size = 20, base_family = 'Font Name' ))
Local fonts linking to your react js may be a failure. So, I prefer to use online css file from google to link fonts. Refer the following code,
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
or
<style>
@import url('https://fonts.googleapis.com/css?family=Roboto');
</style>
Swift: xcode 6.1
let font:UIFont? = UIFont(name: "Arial", size: 12.0)
let attrString = NSAttributedString(
string: titleData,
attributes: NSDictionary(
object: font!,
forKey: NSFontAttributeName))
Try this
<style>
@font-face {
font-family: Roboto Bold Condensed;
src: url(fonts/Roboto_Condensed/RobotoCondensed-Bold.ttf);
}
@font-face {
font-family:Roboto Condensed;
src: url(fonts/Roboto_Condensed/RobotoCondensed-Regular.tff);
}
div1{
font-family:Roboto Bold Condensed;
}
div2{
font-family:Roboto Condensed;
}
</style>
<div id='div1' >This is Sample text</div>
<div id='div2' >This is Sample text</div>
This answer will work for you if you need the following conditions met (none of the current answers met these conditions):
I believe that 3 is the minimal number of HTML elements to satisfy these conditions:
.input-icon{_x000D_
position: absolute;_x000D_
left: 3px;_x000D_
top: calc(50% - 0.5em); /* Keep icon in center of input, regardless of the input height */_x000D_
}_x000D_
input{_x000D_
padding-left: 17px;_x000D_
}_x000D_
.input-wrapper{_x000D_
position: relative;_x000D_
}
_x000D_
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"/>_x000D_
<div class="input-wrapper">_x000D_
<input id="stuff">_x000D_
<label for="stuff" class="fa fa-user input-icon"></label>_x000D_
</div>
_x000D_
Chrome doesn't render the fonts like Firefox or any other browser does. This is generally a problem in Chrome running on Windows only. If you want to make the fonts smooth, use the -webkit-font-smoothing
property on yer h4
tags like this.
h4 {
-webkit-font-smoothing: antialiased;
}
You can also use subpixel-antialiased
, this will give you different type of smoothing (making the text a little blurry/shadowed). However, you will need a nightly version to see the effects. You can learn more about font smoothing here.
"Helvetica Neue Condensed Bold" get working with firefox:
.class {
font-family: "Helvetica Neue";
font-weight: bold;
font-stretch: condensed;
}
But it's fail with Opera.
I experienced the same problem, but for different reasons.
After Will Madden's solution didn't help, I tried every alternative fix I could find via the Intertubes - also to no avail. Exploring further, I just happened to open up one of the font files at issue. The original content of the file had somehow been overwritten by Webpack to include some kind of configuration info, likely from previous tinkering with the file-loader. I replaced the corrupted files with the originals, and voilà, the errors disappeared (for both Chrome and Firefox).
Its already been said a few times but http://www.proggyfonts.com/ is just awesome. Im a big fan of the Proggy Clean Slashed Zero Bold Punctuation. I do most my work in c# so the bold punctuation is very nice for it.
PDF2SVG version 6.0 from PDFTron does a reasonable job. It produces OpenType (.otf
) fonts by default. Use --preserve_fontnames
to preserve "the font/font-family naming scheme as obtained from the source file."
PDF2SVG is a commercial product, but you can download a free demo executable (which includes watermarks on the SVG output but doesn't otherwise restrict usage). There may be other PDFTron products that also extract fonts, but I only recently discovered PDF2SVG myself.
You can select a child like
TextView tv = (TextView)lv.getChildAt(0);
tv.setTextColor(Color.RED);
tv.setTextSize(12);
Try -webkit-font-smoothing: subpixel-antialiased;
I like Consolas
a lot. This top-10 list is a good resource for others. It includes examples and descriptions.
Font myFont = new Font ("Courier New", 1, 17);
The 17 represents the font size. Once you have that, you can put:
g.setFont (myFont);
g.drawString ("Hello World", 10, 10);
<span id="span">HOI</span>
<script>
var span = document.getElementById("span");
console.log(span);
span.style.fontSize = "25px";
span.innerHTML = "String";
</script>
You have two errors in your code:
document.getElementById
-
This retrieves the element with an Id that is "span", you did not specify an id on the span-element.
Capitals in Javascript - Also you forgot the capital of Size.
Go through http://www.w3.org/TR/css3-fonts/
Try this:
@font-face {
font-family: 'EntezareZohoor2';
src: url('EntezareZohoor2.eot');
src: local('EntezareZohoor2'), local('EntezareZohoor2'), url('EntezareZohoor2.ttf') format('svg');
font-weight: normal;
font-style: normal;
}
If you want the font you chose to be applied and not the one in bootstrap without modifying the original bootstrap files you can rearrange the tags in your HTML documents so your CSS files that applies the font called after the bootstrap one. In this way since the browser reads the documents line after line first it will read the bootstrap files and apply it roles then it will read your file and override the roles in the bootstrap and replace it with the ones in your file.
Set line-height
to the vertical size of the picture, then do vertical-align:middle
like Josh said.
so if the picture is 20px
, you would have
{
line-height:20px;
font-size:14px;
vertical-align:middle;
}
If you are using windows then try with CTRL,SHIFT,+ and for decreasing font size you can use CTRL,SHIFT,-
Single line:
factLabel.numberOfLines = 1;
factLabel.minimumFontSize = 8;
factLabel.adjustsFontSizeToFitWidth = YES;
The above code will adjust your text's font size down to (for example) 8
trying to fit your text within the label.
numberOfLines = 1
is mandatory.
Multiple lines:
For numberOfLines > 1
there is a method to figure out the size of final text through NSString's sizeWithFont:... UIKit addition methods, for example:
CGSize lLabelSize = [yourText sizeWithFont:factLabel.font
forWidth:factLabel.frame.size.width
lineBreakMode:factLabel.lineBreakMode];
After that you can just resize your label using resulting lLabelSize
, for example (assuming that you will change only label's height):
factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, factLabel.frame.size.width, lLabelSize.height);
iOS6
Single line:
Starting with iOS6, minimumFontSize
has been deprecated. The line
factLabel.minimumFontSize = 8.;
can be changed to:
factLabel.minimumScaleFactor = 8./factLabel.font.pointSize;
iOS7
Multiple lines:
Starting with iOS7, sizeWithFont
becomes deprecated.
Multiline case is reduced to:
factLabel.numberOfLines = 0;
factLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(factLabel.frame.size.width, CGFLOAT_MAX);
CGSize expectSize = [factLabel sizeThatFits:maximumLabelSize];
factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, expectSize.width, expectSize.height);
iOS 13 (Swift 5):
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
The hex values are on the mainpage of http://glyphicons.com/ in the tooltips of the specific icon.
They are taking a 'shotgun' approach to referencing the font. The browser will attempt to match each font name with any installed fonts on the user's machine (in the order they have been listed).
In your example "HelveticaNeue-Light"
will be tried first, if this font variant is unavailable the browser will try "Helvetica Neue Light"
and finally "Helvetica Neue"
.
As far as I'm aware "Helvetica Neue"
isn't considered a 'web safe font', which means you won't be able to rely on it being installed for your entire user base. It is quite common to define "serif"
or "sans-serif"
as a final default position.
In order to use fonts which aren't 'web safe' you'll need to use a technique known as font embedding. Embedded fonts do not need to be installed on a user's computer, instead they are downloaded as part of the page. Be aware this increases the overall payload (just like an image does) and can have an impact on page load times.
A great resource for free fonts with open-source licenses is Google Fonts. (You should still check individual licenses before using them.) Each font has a download link with instructions on how to embed them in your website.
COMMENT FOR SWIFT 3.0 AND SWIFT WARNING
You can remove the warning message in line:
let initCoderMethod = class_getInstanceMethod(self, Selector("initWithCoder:"))
By replacing it with:
let initCoderMethod = class_getInstanceMethod(self, #selector(UIFontDescriptor.init(coder:)))
font-family: 'Open Sans'; font-weight: 600; important to change to a different font-family
From the description and from the reference to the search box in the Ubuntu site, I gather that you actually want an arrowhead character pointing to the right. There are no Unicode characters designed to be used as arrowheads, but some of them may visually resemble an arrowhead.
In particular, if you draw your idea of the character at Shapecatcher.com, you will find many suggestions, such as “>” RIGHT-POINTING ANGLE BRACKET' (U+232A) and “?” MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT (U+276D).
Such characters generally have limited support in fonts, so you would need to carefully write a longish font-family
list or to use a downloadable font. See my Guide to using special characters in HTML.
Especially if the intended use is as a symbol in a search box, as the reference to the Ubuntu page suggests, it is questionable whether you should use a character at all. It’s not really an element of text here; rather, a graphic symbol that accompanies text but isn’t a part of it. So why take all the trouble with using a character (safely), when it isn’t really a character?
The other answers are not wrong, but I found this to be the fastest way.
Results contain all font formats: woff, svg, ttf, eot.
AND as an added bonus they generate the css file for you too!
we had similar header issue with Amazon (AWS) S3 presigned Post failing on some browsers.
point was to tell bucket CORS to expose header <ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>
more details in this answer: https://stackoverflow.com/a/37465080/473040
Helvetica Neue is a paid font, so you shouldn't @font-face it, as you'd be freely distributing a copyrighted font. It's included in Mac systems but not in windows/linux ones, so yes, plenty of your users wont have it installed. Anyway, you can use 'Arial Narrow' as a windows substitute, which is it's windows equivalent.
Make sure your server is sending the font files with the right mime/type.
I recently have the same problem using nginx because some font mime types are missing from its vanilla /etc/nginx/mime.types
file.
I fixed the issue adding the missing mime types in the location where I needed them like this:
location /app/fonts/ {
#Fonts dir
alias /var/www/app/fonts/;
#Include vanilla types
include mime.types;
#Missing mime types
types {font/truetype ttf;}
types {application/font-woff woff;}
types {application/font-woff2 woff2;}
}
You can also check this out for extending the mime.types in nginx: extending default nginx mime.types file
I disagree with Chad Birch. We can force anti-aliasing, at least in Chrome using a simple css trick with the -webkit-text-stroke
property:-
-webkit-text-stroke: 1px transparent;
As far as I'm aware, you can't declare custom fonts in xml or themes. I usually just make custom classes extending textview that set their own font on instantiation and use those in my layout xml files.
ie:
public class Museo500TextView extends TextView {
public Museo500TextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setTypeface(Typeface.createFromAsset(context.getAssets(), "path/to/font.ttf"));
}
}
and
<my.package.views.Museo900TextView
android:id="@+id/dialog_error_text_header"
android:layout_width="190dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="12sp" />
import pylab as plb
plb.rcParams['font.size'] = 12
or
import matplotlib.pyplot as mpl
mpl.rcParams['font.size'] = 12
You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/
Example:
@font-face {
font-family: MyHelvetica;
src: local("Helvetica Neue Bold"),
local("HelveticaNeue-Bold"),
url(MgOpenModernaBold.ttf);
font-weight: bold;
}
See also: MDN @font-face
I once tried to do those round corners and drop shadows with css3. Later on, I found it is still poorly supported (Internet Explorer(s), of course!)
I ended up trying to do that in JS (HTML canvas with IE Canvas), but it impacts the performance a lot (even on my C2D machine). In short, if you really need the effect, consider JS libraries (most of them should be able to run on IE6) but don't over do it due to performance issues; if you still need an alternative... you could use SFiR, then PS it and SFiR it. CSS3 isn't ready today.
From Emacswiki, GNU Emacs 23 has a built-in key combination:
C-xC-+ and C-xC-- to increase or decrease the buffer text size
The new location of the theme file is: ~/.jupyter/custom/custom.css
you can change that using label property in property panel. This screen shot is example that
Please refer to this updated answer: https://stackoverflow.com/a/46830425/4031815
I'm not aware of any current technique to avoid the flicker as the font loads, however you can minimize it by sending proper cache headers for your font and making sure that that request goes through as quickly as possible.
According to The W3C:
This attribute sets the size of the font. Possible values:
- An integer between 1 and 7. This sets the font to some fixed size, whose rendering depends on the user agent. Not all user agents may render all seven sizes.
- A relative increase in font size. The value "+1" means one size larger. The value "-3" means three sizes smaller. All sizes belong to the scale of 1 to 7.
Hence, the conversion you're asking for is not possible. The browser is not required to use specific sizes with specific size
attributes.
Also note that use of the font
element is discouraged by W3 in favor of style sheets.
They use regular CSS.
Just use your regular font family like this:
font-family: 'Open Sans', sans-serif;
Now you decide what "weight" the font should have by adding
for semi-bold
font-weight:600;
for bold (700)
font-weight:bold;
for extra bold (800)
font-weight:800;
Like this its fallback proof, so if the google font should "fail" your backup font Arial/Helvetica(Sans-serif) use the same weight as the google font.
Pretty smart :-)
Note that the different font weights have to be specifically imported via the link tag url (family query param of the google font url) in the header.
For example the following link will include both weights 400 and 700:
<link href='fonts.googleapis.com/css?family=Comfortaa:400,700'; rel='stylesheet' type='text/css'>
In C# These ways you can Solve the problem, In UIkit these methods are available.
Label.Font = Label.Font.WithSize(5.0f);
Or
Label.Font = UIFont.FromName("Copperplate", 10.0f);
Or
Label.Font = UIFont.WithSize(5.0f);
I like Calibri.
Edit: As of iOS 3.2, this functionality is built in. If you need to support pre-3.2, you can still use this solution.
I created a simple module that extends UILabel
and handles loading .ttf files. I released it opensource under the Apache license and put it on github Here.
The important files are FontLabel.h
and FontLabel.m
.
It uses some of the code from Genericrich's answer.
Browse the source Here.
OR
Copy your font file into resources
Add a key to your Info.plist
file called UIAppFonts. ("Fonts provided by application)
Make this key an array
For each font you have, enter the full name of your font file (including the extension) as items to the UIAppFonts array
Save Info.plist
Now in your application you can simply call [UIFont fontWithName:@"CustomFontName" size:15]
to get the custom font to use with your UILabels
and UITextViews
, etc…
http://dev.w3.org/webfonts/WOFF2/spec/#IMT
It seem that w3c switched it to font/woff2
I see there is some discussion about the proper mime type. In the link we read:
This document defines a top-level MIME type "font" ...
... the officially defined IANA subtypes such as "application/font-woff" ...
The members of the W3C WebFonts WG believe the use of "application" top-level type is not ideal.
and later
6.5. WOFF 2.0
Type name:
font
Subtype name:
woff2
So proposition from W3C differs from IANA.
We can see that it also differs from woff type: http://dev.w3.org/webfonts/WOFF/spec/#IMT where we read:
Type name:
application
Subtype name:
font-woff
which is
application/font-woff
echo "<a href='#' style = \"font-color: #ff0000;\"> Movie List for {$key} 2013 </a>";
I noticed there was not an actual full code answer, so as i come across this, i have created a function, that does change the font, which can be easily modified. I have tested this in
private void SetFont(Form f, string name, int size, FontStyle style)
{
Font replacementFont = new Font(name, size, style);
f.Font = replacementFont;
}
Hint: replace Form to either Label, RichTextBox, TextBox, or any other relative control that uses fonts to change the font on them. By using the above function thus making it completely dynamic.
/// To call the function do this.
/// e.g in the form load event etc.
public Form1()
{
InitializeComponent();
SetFont(this, "Arial", 8, FontStyle.Bold);
// This sets the whole form and
// everything below it.
// Shaun Cassidy.
}
You can also, if you want a full libary so you dont have to code all the back end bits, you can download my dll from Github.
/// and then import the namespace
using Droitech.TextFont;
/// Then call it using:
TextFontClass fClass = new TextFontClass();
fClass.SetFont(this, "Arial", 8, FontStyle.Bold);
Simple.
You can use CSS3 font-face
or webfonts
@font-face usage
@font-face {
font-family: Delicious;
src: url('Delicious-Roman.otf');
}
webfonts
take a look at Google Webfonts, http://www.google.com/webfonts
Ctrl++
or
Ctrl+=
Ctrl+-
This feature is described here:
In text editors, you can now use Zoom In (Ctrl++ or Ctrl+=) and Zoom Out (Ctrl+-) commands to increase and decrease the font size. Like a change in the General > Appearance > Colors and Fonts preference page, the commands persistently change the font size in all editors of the same type. If the editor type's font is configured to use a default font, then that default font will be zoomed.
So, the font size change is not limited to the current file and the new value of the font size is available here Window > Preferences > General > Appearance > Colors and Fonts.
The solution seems to be to add multiple @font-face
rules, for example:
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans.ttf");
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Bold.ttf");
font-weight: bold;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Oblique.ttf");
font-style: italic, oblique;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-BoldOblique.ttf");
font-weight: bold;
font-style: italic, oblique;
}
By the way, it would seem Google Chrome doesn't know about the format("ttf")
argument, so you might want to skip that.
(This answer was correct for the CSS 2 specification. CSS3 only allows for one font-style rather than a comma-separated list.)
I think what you want to do is
<link rel="stylesheet" type="text/css" href="font/font-face/my-font-face.css">
_x000D_
Depending on your application, you'll probably want to use that Font assignment either on text change or focus/unfocus of the textbox in question.
Here's a quick sample of what it could look like (empty form, with just a textbox. Font turns bold when the text reads 'bold', case-insensitive):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
RegisterEvents();
}
private void RegisterEvents()
{
_tboTest.TextChanged += new EventHandler(TboTest_TextChanged);
}
private void TboTest_TextChanged(object sender, EventArgs e)
{
// Change the text to bold on specified condition
if (_tboTest.Text.Equals("Bold", StringComparison.OrdinalIgnoreCase))
{
_tboTest.Font = new Font(_tboTest.Font, FontStyle.Bold);
}
else
{
_tboTest.Font = new Font(_tboTest.Font, FontStyle.Regular);
}
}
}
Its because the font size (9px) is too small to display bold. Try 11px or more and it works fine.
No, there isn't a decent solution for body type, unless you're willing to cater only to those with bleeding-edge browsers.
Microsoft has WEFT, their own proprietary font-embedding technology, but I haven't heard it talked about in years, and I know no one who uses it.
I get by with sIFR for display type (headlines, titles of blog posts, etc.) and using one of the less-worn-out web-safe fonts for body type (like Trebuchet MS). If you're bored with all the web-safe fonts, you're probably defining the term too narrowly — look at this matrix of stock fonts that ship with major OSes and chances are you'll be able to find a font cascade that will catch nearly all web users.
For instance: font-family: "Lucida Grande", "Verdana", sans-serif
is a common font cascade; OS X comes with Lucida Grande, but those with Windows will get Verdana, a web-safe font with letters of similar size and shape to Lucida Grande. Linux users will also get Verdana if they've installed the web-safe fonts package that exists in most distros' package managers, or else they'll fall back to an ordinary sans-serif.
It may be useful to know that starting from Android 8.0 (API level 26) you can use a custom font in XML.
You can apply a custom font to the entire application in the following way.
Put the font in the folder res/font
.
In res/values/styles.xml
use it in the application theme.
<style name="AppTheme" parent="{whatever you like}">
<item name="android:fontFamily">@font/myfont</item>
</style>
If you are on a unixoid operating system and want to extract just a single file you can try the following. The structure of the chrome://cache
pages is URL, parsed HTTP header, hex dump of the HTTP header and then hex dump of the payload.
To extract a file copy all payload lines from a Chrome cache page to the clipboard (starting at the second 00000000: ...
line), paste them into a text editor and save them as a plain text file (e.g. file.txt
). If the payload is a gzipped WOFF file use xxd -r file.txt > file.woff.gz
to convert it back to a binary file and gunzip file.woff.gz
for decompression.
You can then use woff2otf to convert WOFF files to the OTF format or woff2 to convert WOFF 2.0 files to the TTF format. For batch processing this workflow should obviously be scripted.
We need to use reflections for achieving this
final int titleId = activity.getResources().getIdentifier("action_bar_title", "id", "android");
final TextView title;
if (activity.findViewById(titleId) != null) {
title = (TextView) activity.findViewById(titleId);
title.setTextColor(Color.BLACK);
title.setTextColor(configs().getColor(ColorKey.GENERAL_TEXT));
title.setTypeface(configs().getTypeface());
} else {
try {
Field f = bar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
title = (TextView) f.get(bar);
title.setTextColor(Color.BLACK);
title.setTypeface(configs().getTypeface());
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
}
To do that in Kotlin:
yourTextView.paint?.isUnderlineText = true
You can implement your OTF
font using @font-face like:
@font-face {
font-family: GraublauWeb;
src: url("path/GraublauWeb.otf") format("opentype");
}
@font-face {
font-family: GraublauWeb;
font-weight: bold;
src: url("path/GraublauWebBold.otf") format("opentype");
}
// Edit: OTF now works in most browsers, see comments
However if you want to support a wide variety of browsers i would recommend you to switch to WOFF
and TTF
font types. WOFF
type is implemented by every major desktop browser, while the TTF
type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.
@font-face {
font-family: GraublauWeb;
src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf") format("truetype");
}
If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:
@font-face {
font-family: GraublauWeb;
src: url("webfont.eot"); /* IE9 Compat Modes */
src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
url("webfont.woff") format("woff"), /* Modern Browsers */
url("webfont.ttf") format("truetype"), /* Safari, Android, iOS */
url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}
You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:
hope this helps
For Website you can use 'Roboto' font as below:
If you have created separate css file then put below line at the top of css file as:
@import url('https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,500,500i,700,700i,900,900i');
Or if you don't want to create separate file then add above line in between <style>...</style>
:
<style>
@import url('https://fonts.googleapis.com/css?
family=Roboto:300,300i,400,400i,500,500i,700,700i,900,900i');
</style>
then:
html, body {
font-family: 'Roboto', sans-serif;
}
table td{
color:#0000ff;
}
<table>
<tbody>
<tr>
<td>
<select name="test">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>
This is what worked for me for extracting TTFs from .dfont and .ttc files from Mac OS X: http://transfonter.org/ttc-unpack
The resulting TTFs work fine in Windows 7.
✕ is another great one that's not too thick. The HTML code is ✕
, or 2715
in hex.
Here is how I did it!
//create the font
try {
//create the font to use. Specify the size!
Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("Fonts\\custom_font.ttf")).deriveFont(12f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
//register the font
ge.registerFont(customFont);
} catch (IOException e) {
e.printStackTrace();
} catch(FontFormatException e) {
e.printStackTrace();
}
//use the font
yourSwingComponent.setFont(customFont);
I have a script written in PHP similar to that of @neverpanic that automatically downloads both the CSS and fonts (both hinted and unhinted) from Google. It then serves the correct CSS and fonts from your own server based on the User Agent. It keeps its own cache, so fonts and CSS of a User Agent will only be downloaded once.
It's in a premature stage, but it can be found here: DaAwesomeP / php-offline-fonts
If by non standard font, you mean custom font of a standard format, here's how I do it, and it works for all browsers I've checked so far:
@font-face {
font-family: TempestaSevenCondensed;
src: url("../fonts/pf_tempesta_seven_condensed.eot") /* EOT file for IE */
}
@font-face {
font-family: TempestaSevenCondensed;
src: url("../fonts/pf_tempesta_seven_condensed.ttf") /* TTF file for CSS3 browsers */
}
so you'll just need both the ttf and eot fonts. Some tools available online can make the conversion.
But if you want to attach font in a non standard format (bitmaps etc), I can't help you.
You need to declare @font-face
like this in your stylesheet
@font-face {
font-family: 'Awesome-Font';
font-style: normal;
font-weight: 400;
src: local('Awesome-Font'), local('Awesome-Font-Regular'), url(path/Awesome-Font.woff) format('woff');
}
Now if you want to apply this font to a paragraph simply use it like this..
p {
font-family: 'Awesome-Font', Arial;
}
For the best possible browser support, your CSS code should look like this :
@font-face {
font-family: 'MyWebFont';
src: url('webfont.eot'); /* IE9 Compat Modes */
src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
url('webfont.ttf') format('truetype'), /* Safari, Android, iOS */
url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}
body {
font-family: 'MyWebFont', Fallback, sans-serif;
}
For more info, see the article Using @font-face at CSS-tricks.com.
in Bootstrap, web inspector says the Headings are set to 'inherit'
all i needed to set my page to the new font was
div, p {font-family: Algerian}
that's in .scss
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Thin.otf);
font-weight: 200;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Light.otf);
font-weight: 300;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Regular.otf);
font-weight: normal;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Bold.otf);
font-weight: bold;
}
h3, h4, h5, h6 {
font-size:2em;
margin:0;
padding:0;
font-family:Kaffeesatz;
font-weight:normal;
}
h6 { font-weight:200; }
h5 { font-weight:300; }
h4 { font-weight:normal; }
h3 { font-weight:bold; }
label = new JLabel("A label");
label.setFont(new Font("Serif", Font.PLAIN, 14));
taken from How to Use HTML in Swing Components
... in the body tag and these from the content and the typeface looks better in general...
body, html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
text-rendering: optimizeLegibility;
text-rendering: geometricPrecision;
font-smooth: always;
font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-webkit-font-smoothing: antialiased;
-webkit-font-smoothing: subpixel-antialiased;
}
#content {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
IF it's still not working for you, I had forgotten to add the fa-ul
class onto the parent (UL) element:
<ul class="fa-ul">
Together with the 2 bits of advice provided already by others:
a) font-family: 'Font Awesome\ 5 Free';
b) font-weight: 900;
solved it for me.
FWIW, the include in my <head>
tags is just:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous" />
And I am using this with React and Preact. No need for any special React npm installs or components.
the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face
@font-face {
font-family: 'Name You Font';
src: url('assets/font/xxyourfontxxx.eot');
src: local('Cera Pro Medium'), local('CeraPro-Medium'),
url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
url('assets/font/xxyourfontxxx.woff') format('woff'),
url('assets/font/xxyourfontxxx.ttf') format('truetype');
font-weight: 500;
font-style: normal;
}
So you can just indicate your fontfamily name that you already choosed
NOTE: the font-weight and font-style depend on your .woff .ttf ... files
For the first one remove the spaces. Whitespace matters for the set command.
set guifont=Monaco:h20
For the second one it should be (the h specifies the height)
set guifont=Monospace:h20
My recommendation for setting the font is to do (if your version supports it)
set guifont=*
This will pop up a menu that allows you to select the font. After selecting the font, type
set guifont?
To show what the current guifont is set to. After that copy that line into your vimrc or gvimrc. If there are spaces in the font add a \
to escape the space.
set guifont=Monospace\ 20
Actually, you can achieve this pretty easy. Simply specify the line height as a number:
<p style="line-height:1.5">
<span style="font-size:12pt">The quick brown fox jumps over the lazy dog.</span><br />
<span style="font-size:24pt">The quick brown fox jumps over the lazy dog.</span>
</p>
The difference between number and percentage in the context of the line-height CSS property is that the number value is inherited by the descendant elements, but the percentage value is first computed for the current element using its font size and then this computed value is inherited by the descendant elements.
For more information about the line-height property, which indeed is far more complex than it looks like at first glance, I recommend you take a look at this online presentation.
The best I can find is to set input[type="password"] {font:small-caption;font-size:16px}
Demo:
input {_x000D_
font: small-caption;_x000D_
font-size: 16px;_x000D_
}
_x000D_
<input type="password">
_x000D_
Maybe this will help someone. I saw that on IIS 7 .ttf
is already a known mime-type. It's configured as:
application/octet-stream
So I just added that for all the CSS font types (.oet
, .svg
, .ttf
, .woff
) and IIS started serving them. Chrome dev tools also do not complain about re-interpreting the type.
Cheers, Michael
The default implementations of LayoutInflater do not support specifying the font typeface from xml. I have however seen it done in xml by providing a custom factory for the LayoutInflater that will parse such attributes from the xml tag.
The basic structure would like this.
public class TypefaceInflaterFactory implements LayoutInflater.Factory {
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
// CUSTOM CODE TO CREATE VIEW WITH TYPEFACE HERE
// RETURNING NULL HERE WILL TELL THE INFLATER TO USE THE
// DEFAULT MECHANISMS FOR INFLATING THE VIEW FROM THE XML
}
}
public class BaseActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater.from(this).setFactory(new TypefaceInflaterFactory());
}
}
This article provides a more in depth explanation of these mechanisms and how the author attempts to provide xml layout support for typefaces in this way. The code for the author's implementation can be found here.
Just wanted to add on to what @aioobe mentioned above...
In that approach you use HTML to color code your text. Though this is one of the most frequently used ways to color code the label text, but is not the most efficient way to do it.... considering that fact that each label will lead to HTML being parsed, rendering, etc. If you have large UI forms to be displayed, every millisecond counts to give a good user experience.
You may want to go through the below and give it a try....
Jide OSS (located at https://jide-oss.dev.java.net/) is a professional open source library with a really good amount of Swing components ready to use. They have a much improved version of JLabel named StyledLabel. That component solves your problem perfectly... See if their open source licensing applies to your product or not.
This component is very easy to use. If you want to see a demo of their Swing Components you can run their WebStart demo located at www.jidesoft.com (http://www.jidesoft.com/products/1.4/jide_demo.jnlp). All of their offerings are demo'd... and best part is that the StyledLabel is compared with JLabel (HTML and without) in terms of speed! :-)
A screenshot of the perf test can be seen at (http://img267.imageshack.us/img267/9113/styledlabelperformance.png)
In some browsers, fonts are set explicit for textareas and inputs, so they don’t inherit the fonts from higher elements. So, I think you need to apply the font styles for each textarea and input in the document as well (not just the body).
One idea might be to add clases to the body, then use CSS to style the document accordingly.
You might want to create static class which will contain all the fonts. That way, you won't create the font multiple times which might impact badly on performance. Just make sure that you create a sub-folder called "fonts" under "assets" folder.
Do something like:
public class CustomFontsLoader {
public static final int FONT_NAME_1 = 0;
public static final int FONT_NAME_2 = 1;
public static final int FONT_NAME_3 = 2;
private static final int NUM_OF_CUSTOM_FONTS = 3;
private static boolean fontsLoaded = false;
private static Typeface[] fonts = new Typeface[3];
private static String[] fontPath = {
"fonts/FONT_NAME_1.ttf",
"fonts/FONT_NAME_2.ttf",
"fonts/FONT_NAME_3.ttf"
};
/**
* Returns a loaded custom font based on it's identifier.
*
* @param context - the current context
* @param fontIdentifier = the identifier of the requested font
*
* @return Typeface object of the requested font.
*/
public static Typeface getTypeface(Context context, int fontIdentifier) {
if (!fontsLoaded) {
loadFonts(context);
}
return fonts[fontIdentifier];
}
private static void loadFonts(Context context) {
for (int i = 0; i < NUM_OF_CUSTOM_FONTS; i++) {
fonts[i] = Typeface.createFromAsset(context.getAssets(), fontPath[i]);
}
fontsLoaded = true;
}
}
This way, you can get the font from everywhere in your application.
I just visited this site and it really bugged me,
apparently there are a couple ways to disable the mouse click:
1)
<script language="javascript">
document.onmousedown=disableclick;
status="Right Click Disabled";
function disableclick(event)
{
if(event.button==2)
{
alert(status);
return false;
}
}
</script>
and
<body oncontextmenu="return false">
...
in this case what you will have to do in the dev tools is :
document.removeEventListener("onmousedown",disableclick);
document.oncontextmenu = function(){}
2)
using flash as a content wrapper - no solution here except taking a screenshot
3)
some sites want to prevent downloading images via right click -> save image as
so what they do is put this:
<div style="background-image: url(YourImage.jpg);">
<img src="transparent.gif"/>
</div>
which is a transparent image spreding on the full width and height of the screen all you need to do is go to the elements inspector and find the div and delete it.
In my case #1 did the trick
Why not?
#header {
text-align: center;
}
#header ul {
display: inline;
}
First install a pod :-
pod 'SwiftGifOrigin'
and import in your class
import SwiftGifOrigin
then write this code in viewDidiload method
yourImageView.image = UIImage.gif(name: "imageName")
Note:- plz do not include the file extension in the gif file name. Ex:-
//Don't Do this
yourImageView.image = UIImage.gif(name: "imageName.gif")
See source: https://github.com/swiftgif/SwiftGif
You may try indexed-file-reader (Apache License 2.0). The class IndexedFileReader has a method called readLines(int from, int to) which returns a SortedMap whose key is the line number and the value is the line that was read.
Example:
File file = new File("src/test/resources/file.txt");
reader = new IndexedFileReader(file);
lines = reader.readLines(6, 10);
assertNotNull("Null result.", lines);
assertEquals("Incorrect length.", 5, lines.size());
assertTrue("Incorrect value.", lines.get(6).startsWith("[6]"));
assertTrue("Incorrect value.", lines.get(7).startsWith("[7]"));
assertTrue("Incorrect value.", lines.get(8).startsWith("[8]"));
assertTrue("Incorrect value.", lines.get(9).startsWith("[9]"));
assertTrue("Incorrect value.", lines.get(10).startsWith("[10]"));
The above example reads a text file composed of 50 lines in the following format:
[1] The quick brown fox jumped over the lazy dog ODD
[2] The quick brown fox jumped over the lazy dog EVEN
Disclamer: I wrote this library
There is another way to do XOR:
bool XOR(bool a, bool b)
{
return (a + b) % 2;
}
Which obviously can be demonstrated to work via:
#include <iostream>
bool XOR(bool a, bool b)
{
return (a + b) % 2;
}
int main()
{
using namespace std;
cout << "XOR(true, true):\t" << XOR(true, true) << endl
<< "XOR(true, false):\t" << XOR(true, false) << endl
<< "XOR(false, true):\t" << XOR(false, true) << endl
<< "XOR(false, false):\t" << XOR(false, false) << endl
<< "XOR(0, 0):\t\t" << XOR(0, 0) << endl
<< "XOR(1, 0):\t\t" << XOR(1, 0) << endl
<< "XOR(5, 0):\t\t" << XOR(5, 0) << endl
<< "XOR(20, 0):\t\t" << XOR(20, 0) << endl
<< "XOR(6, 6):\t\t" << XOR(5, 5) << endl
<< "XOR(5, 6):\t\t" << XOR(5, 6) << endl
<< "XOR(1, 1):\t\t" << XOR(1, 1) << endl;
return 0;
}
There are two methods to setting and using variables within for loops and parentheses scope.
setlocal enabledelayedexpansion
see setlocal /?
for help. This only works on XP/2000 or newer versions of Windows.
then use !variable!
instead of %variable%
inside the loop...
Create a batch function using batch goto labels :Label
.
Example:
for /F "tokens=*" %%a in ('type %FileName%') do call :Foo %%a
goto End
:Foo
set z=%1
echo %z%
echo %1
goto :eof
:End
Batch functions are very useful mechanism.
FYI, this is not an answer to the post. But it may help future users who may get the error with the message:
TypeError: 'builtin_function_or_method' object is not subscriptable
In my case, it was occurred due to bad indentation.
Just indenting the line of code solved the issue.
That's because Bootstrap by default sets the width of the legend
element to 100%. You can fix this by changing your legend.scheduler-border
to also use:
legend.scheduler-border {
width:inherit; /* Or auto */
padding:0 10px; /* To give a bit of padding on the left and right */
border-bottom:none;
}
You'll also need to ensure your custom stylesheet is being added after Bootstrap to prevent Bootstrap overriding your styling - although your styles here should have higher specificity.
You may also want to add margin-bottom:0;
to it as well to reduce the gap between the legend and the divider.
The key is to use the reset_index() method.
Use:
import pandas
df1 = pandas.DataFrame( {
"Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] ,
"City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } )
g1 = df1.groupby( [ "Name", "City"] ).count().reset_index()
Now you have your new dataframe in g1:
Late answer, but my solution works in Eclipse XSLT. Eclipse uses XSLT 1 at time of this writing. You can install an XSLT 2 engine like Saxon. Or you can use the XSLT 1 solution below to insert current date and time.
<xsl:value-of select="java:util.Date.new()"/>
This will call Java's Data class to output the date. It will not work unless you also put the following "java:" definition in your <xsl:stylesheet>
tag.
<xsl:stylesheet [...snip...]
xmlns:java="java"
[...snip...]>
I hope that helps someone. This simple answer was difficult to find for me.
freopen("/my/newstdin", "r", stdin);
freopen("/my/newstdout", "w", stdout);
freopen("/my/newstderr", "w", stderr);
... do your stuff
freopen("/dev/stdin", "r", stdin);
...
...
This peaks the needle on my round-peg-square-hole-o-meter, what are you trying to accomplish?
Edit:
Remember that stdin, stdout and stderr are file descriptors 0, 1 and 2 for every newly created process. freopen() should keep the same fd's, just assign new streams to them.
So, a good way to ensure that this is actually doing what you want it to do would be:
printf("Stdout is descriptor %d\n", fileno(stdout));
freopen("/tmp/newstdout", "w", stdout);
printf("Stdout is now /tmp/newstdout and hopefully still fd %d\n",
fileno(stdout));
freopen("/dev/stdout", "w", stdout);
printf("Now we put it back, hopefully its still fd %d\n",
fileno(stdout));
I believe this is the expected behavior of freopen(), as you can see, you're still only using three file descriptors (and associated streams).
This would override any shell redirection, as there would be nothing for the shell to redirect. However, its probably going to break pipes. You might want to be sure to set up a handler for SIGPIPE, in case your program finds itself on the blocking end of a pipe (not FIFO, pipe).
So, ./your_program --stdout /tmp/stdout.txt --stderr /tmp/stderr.txt should be easily accomplished with freopen() and keeping the same actual file descriptors. What I don't understand is why you'd need to put them back once changing them? Surely, if someone passed either option, they would want it to persist until the program terminated?
public class TagYourDiseaseAdapter extends RecyclerView.Adapter { private ReCyclerViewItemClickListener mRecyclerViewItemClickListener; private Context mContext;
List<Datum> deviceList = Collections.emptyList();
/**
* Initialize the values
*
* @param context : context reference
* @param devices : data
*/
public TagYourDiseaseAdapter(Context context, List<Datum> devices,
ReCyclerViewItemClickListener mreCyclerViewItemClickListener) {
this.mContext = context;
this.deviceList = devices;
this.mRecyclerViewItemClickListener = mreCyclerViewItemClickListener;
}
/**
* @param parent : parent ViewPgroup
* @param viewType : viewType
* @return ViewHolder
* <p>
* Inflate the Views
* Create the each views and Hold for Reuse
*/
@Override
public TagYourDiseaseAdapter.OrderHistoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tag_disease, parent, false);
TagYourDiseaseAdapter.OrderHistoryViewHolder myViewHolder = new TagYourDiseaseAdapter.OrderHistoryViewHolder(view);
return myViewHolder;
}
/**
* @param holder :view Holder
* @param position : position of each Row
* set the values to the views
*/
@Override
public void onBindViewHolder(final TagYourDiseaseAdapter.OrderHistoryViewHolder holder, final int position) {
Picasso.with(mContext).load(deviceList.get(position).getIconUrl()).into(holder.document);
holder.name.setText(deviceList.get(position).getDiseaseName());
holder.radioButton.setOnCheckedChangeListener(null);
holder.radioButton.setChecked(deviceList.get(position).isChecked());
//if true, your checkbox will be selected, else unselected
//holder.radioButton.setChecked(objIncome.isSelected());
holder.radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
deviceList.get(position).setChecked(isChecked);
}
});
}
@Override
public int getItemCount() {
return deviceList.size();
}
/**
* Create The view First Time and hold for reuse
* View Holder for Create and Hold the view for ReUse the views instead of create again
* Initialize the views
*/
public class OrderHistoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView document;
TextView name;
CheckBox radioButton;
public OrderHistoryViewHolder(View itemView) {
super(itemView);
document = itemView.findViewById(R.id.img_tag);
name = itemView.findViewById(R.id.text_tag_name);
radioButton = itemView.findViewById(R.id.rdBtn_tag_disease);
radioButton.setOnClickListener(this);
//this.setIsRecyclable(false);
}
@Override
public void onClick(View view) {
mRecyclerViewItemClickListener.onItemClickListener(this.getAdapterPosition(), view);
}
}
}
Well, if in the HTML you import a script...
<script type="text/javascript" src="//stier.linuxfaq.org/ip.php"></script>
You can then use the variable userIP (which would be the visitor's IP address) anywhere on the page.
To redirect: <script>if (userIP == "555.555.555.55") {window.location.replace("http://192.168.1.3/flex-start/examples/navbar-fixed-top/");}</script>
Or to show it on the page: document.write (userIP);
DISCLAIMER: I am the author of the script I said to import. The script comes up with the IP by using PHP. The source code of the script is below.
<?php
//Gets the IP address
$ip = getenv("REMOTE_ADDR") ;
Echo "var userIP = '" . $ip . "';";
?>
// create table
var dt = new System.Data.DataTable("tableName");
// create fields
dt.Columns.Add("field1", typeof(int));
dt.Columns.Add("field2", typeof(string));
dt.Columns.Add("field3", typeof(DateTime));
// insert row values
dt.Rows.Add(new Object[]{
123456,
"test",
DateTime.Now
});
To simplify cleaning when using "out of source" build (i.e. you build in the build
directory), I use the following script:
$ cat ~/bin/cmake-clean-build
#!/bin/bash
if [ -d ../build ]; then
cd ..
rm -rf build
mkdir build
cd build
else
echo "build directory DOES NOT exist"
fi
Every time you need to clean up, you should source this script from the build
directory:
. cmake-clean-build
import re
pattern = re.compile("<(\d{4,5})>")
for i, line in enumerate(open('test.txt')):
for match in re.finditer(pattern, line):
print 'Found on line %s: %s' % (i+1, match.group())
A couple of notes about the regex:
?
at the end and the outer (...)
if you don't want to match the number with the angle brackets, but only want the number itselfUpdate: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.
More about regex in python can be found here : Regular Expression HOWTO
An example to make things concrete. If you have a selection thus:
<select onchange="" onblur="">
<option>....
</select>
the onblur()
is called when you navigate away. The onchange()
is called when you select a different option from the selection - i.e. you change what it's currently selected as.
You can simply use std::bind
with a your destroy function.
std::unique_ptr<Bar, std::function<void(Bar*)>> bar(create(), std::bind(&destroy,
std::placeholders::_1));
But of course you can also use a lambda.
std::unique_ptr<Bar, std::function<void(Bar*)>> ptr(create(), [](Bar* b){ destroy(b);});
You can just use -i
instead of -I {}
ls | xargs -i mv {} unix_{}
This also works perfectly.
ls
- lists all the files in the directoryxargs
- accepts all files line by line due to the -i
option{}
is the placeholder for all files, necessary if xargs
gets more than two arguments as inputUsing awk:
ls -lrt | grep '^-' | awk '{print "mv "$9" unix_"$9""}' | sh
Based on skube's approach, I found the minimal set of CSS I needed was:
.horizontal-scroll-except-first-column {_x000D_
width: 100%;_x000D_
overflow: auto;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table {_x000D_
margin-left: 8em;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th:first-child,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td:first-child {_x000D_
position: absolute;_x000D_
width: 8em;_x000D_
margin-left: -8em;_x000D_
background: #ccc;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td {_x000D_
/* Without this, if a cell wraps onto two lines, the first column_x000D_
* will look bad, and may need padding. */_x000D_
white-space: nowrap;_x000D_
}
_x000D_
<div class="horizontal-scroll-except-first-column">_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>FIXED</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> <td>66666</td> <td>77777</td> <td>88888</td> <td>99999</td> <td>AAAAA</td> <td>BBBBB</td> <td>CCCCC</td> <td>DDDDD</td> <td>EEEEE</td> <td>FFFFF</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>
_x000D_
Instead of importing the logout_view
function, you should provide a string in your urls.py
file:
So not (r'^login/', login_view),
but (r'^login/', 'login.views.login_view'),
That is the standard way of doing things. Then you can access the URL in your templates using:
{% url login.views.login_view %}
Enter the following command to check if a private key and public key are a matched set (identical) or not a matched set (differ) in $USER/.ssh directory. The cut command prevents the comment at the end of the line in the public key from being compared, allowing only the key to be compared.
ssh-keygen -y -f ~/.ssh/id_rsa | diff -s - <(cut -d ' ' -f 1,2 ~/.ssh/id_rsa.pub)
Output will look like either one of these lines.
Files - and /dev/fd/63 are identical
Files - and /dev/fd/63 differ
I wrote a shell script that users use to check file permission of their ~/.ssh/files and matched key set. It solves my challenges with user incidents setting up ssh. It may help you. https://github.com/BradleyA/docker-security-infrastructure/tree/master/ssh
Note: My previous answer (in Mar 2018) no longer works with the latest releases of openssh. Previous answer: diff -qs <(ssh-keygen -yf ~/.ssh/id_rsa) <(cut -d ' ' -f 1,2 ~/.ssh/id_rsa.pub)
You have several way for Select duplicate rows
.
for my solutions , first consider this table for example
CREATE TABLE #Employee
(
ID INT,
FIRST_NAME NVARCHAR(100),
LAST_NAME NVARCHAR(300)
)
INSERT INTO #Employee VALUES ( 1, 'Ardalan', 'Shahgholi' );
INSERT INTO #Employee VALUES ( 2, 'name1', 'lname1' );
INSERT INTO #Employee VALUES ( 3, 'name2', 'lname2' );
INSERT INTO #Employee VALUES ( 2, 'name1', 'lname1' );
INSERT INTO #Employee VALUES ( 3, 'name2', 'lname2' );
INSERT INTO #Employee VALUES ( 4, 'name3', 'lname3' );
First solution :
SELECT DISTINCT *
FROM #Employee;
WITH #DeleteEmployee AS (
SELECT ROW_NUMBER()
OVER(PARTITION BY ID, First_Name, Last_Name ORDER BY ID) AS
RNUM
FROM #Employee
)
SELECT *
FROM #DeleteEmployee
WHERE RNUM > 1
SELECT DISTINCT *
FROM #Employee
Secound solution : Use identity
field
SELECT DISTINCT *
FROM #Employee;
ALTER TABLE #Employee ADD UNIQ_ID INT IDENTITY(1, 1)
SELECT *
FROM #Employee
WHERE UNIQ_ID < (
SELECT MAX(UNIQ_ID)
FROM #Employee a2
WHERE #Employee.ID = a2.ID
AND #Employee.FIRST_NAME = a2.FIRST_NAME
AND #Employee.LAST_NAME = a2.LAST_NAME
)
ALTER TABLE #Employee DROP COLUMN UNIQ_ID
SELECT DISTINCT *
FROM #Employee
and end of all solution use this command
DROP TABLE #Employee
Swift 5:
let homeTab = UITabBarItem(title: "Home", image: UIImage(named: "YOUR_IMAGE_NAME_FROM_ASSETS")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal), tag: 1)
A simple way to look at it is that an id is unique to only one element.
A class is not unique and applied to multiple elements.
For example:
<p class = "content">This is some random <strong id="veryImportant"> stuff!</strong></p>
Content is a class since it'll probably apply to some other tags aswell where as "veryImportant" is only being used once and never again.
The return
statement stops a loop only if it's inside the function (i.e. it terminates both the loop and the function). Otherwise, you will get this error:
Uncaught SyntaxError: Illegal return statement(…)
To terminate a loop you should use break
.
Similar question has been asked in stackoverflow before.
See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?
Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host
Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:
- no DNS support
- misconfigured
- behind load balancing software
Switch to preg_replace
Docs and update the expression to use preg syntax (PCRE) instead of ereg syntax (POSIX) where there are differencesDocs (just as it says to do in the manual for ereg_replace
Docs).
Alternatively if one does not see "Untrust App Developer" dialog:
Go to your iPhone > Settings > General > Profile > "[email protected]" > Trust
This workedfor me
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
You can use double quotes instead of single quotes:
theAnchorText = "I'm home";
Alternatively, escape the apostrophe:
theAnchorText = 'I\'m home';
The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.
There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n
for a new line, or \t
for a tab.
I have been using python requests for async calls against github's gist API for some time.
For an example, see the code here:
https://github.com/davidthewatson/flasgist/blob/master/views.py#L60-72
This style of python may not be the clearest example, but I can assure you that the code works. Let me know if this is confusing to you and I will document it.
<div style="height:50rem; width:100%; margin: auto;">
<div style="height:50rem; width:20%; margin-left:4%; margin-right:0%; float:left; background-color: black;"></div>
<div style="height:50rem; width:20%; margin-left:4%; margin-right:0%; float:left; background-color: black;"></div>
<div style="height:50rem; width:20%; margin-left:4%; margin-right:0%; float:left; background-color: black;"></div>
<div style="height:50rem; width:20%; margin-left:4%; margin-right:0%; float:left; background-color: black;"></div>
</div>
_x000D_
margin-right isn't needed though.
try if( $(response).filter('#result').length ) // do something
The error occur because the mysql server is not starting on your computer. You should start it manually. Do following steps:
Download and install wamp server according to your bit version(32bit or 64bit) in your computer(http://wampserver-64bit.en.softonic.com/) this link allows you to download wamp server for 64bit.
As soon as you install it you can double click and run it..(you can see a icon in the right hand of the taskbar.It may be hidden .so you can click the arrow which show you the hide apps runing).So click the icon and go to Mysql
Then go to Service and there you can find Start/Resume Services click on it..
And now it is done.Open mysql workbench and see.It will work..
instead of this:
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
you could try the following using short circuiting:
style={{
textDecoration: completed && 'line-through'
}}
https://codeburst.io/javascript-short-circuit-conditionals-bbc13ac3e9eb
key bit of information from the link:
Short circuiting means that in JavaScript when we are evaluating an AND expression (&&), if the first operand is false, JavaScript will short-circuit and not even look at the second operand.
It's worth noting that this would return false if the first operand is false, so might have to consider how this would affect your style.
The other solutions might be more best practice, but thought it would be worth sharing.
It's not a better idea to override the core.common file of codeigniter. Because that's the more tested and system files....
I make a solution for this problem. In your ckeditor_helper.php file line- 65
if($k !== end (array_keys($data['config']))) {
$return .= ",";
}
Change this to-->
$segment = array_keys($data['config']);
if($k !== end($segment)) {
$return .= ",";
}
I think this is the best solution and then your problem notice will dissappear.
Just open your repository file and add this new function, then call it inside your controller:
public function distinctCategories(){
return $this->createQueryBuilder('cc')
->where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->groupBy('cc.blogarticle')
->getQuery()
->getResult()
;
}
Then within your controller:
public function index(YourRepository $repo)
{
$distinctCategories = $repo->distinctCategories();
return $this->render('your_twig_file.html.twig', [
'distinctCategories' => $distinctCategories
]);
}
Good luck!
From HTML 4 spec, which should be consistent across almost all browsers:
http://www.w3.org/TR/html401/interact/forms.html#checkbox
Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.
Successful is defined as follows:
A successful control is "valid" for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.
<div id="container">
<div><span>Two Words</span></div>
<div><span>Two Words</span></div>
<div><span>Two Words</span></div>
<div><span>Two Words</span></div>
</div>
#container{
width:450px;
height:200px;
margin:0px auto;
border:1px solid red;
}
#container div{
position:relative;
width:100px;
height:100px;
border:1px solid #ccc;
float:left;
margin-right:5px;
}
#container div span{
position:absolute;
bottom:0;
right:0;
}
Since AngularJS 1.3.4 you can use $setDirty()
on fields (source). For example, for each field with error and marked required you can do the following:
angular.forEach($scope.form.$error.required, function(field) {
field.$setDirty();
});
Consider a scenario where Test1, Test2 and Test3 are three classes. The Test3 class inherits Test2 and Test1 classes. If Test1 and Test2 classes have same method and you call it from child class object, there will be ambiguity to call method of Test1 or Test2 class but there is no such ambiguity for interface as in interface no implementation is there.
Gosh, NO!!! You're asking for a world of hurt if you store formatted dates in SQL Server. Always store your dates and times and one of the SQL Server "date/time" datatypes (DATETIME, DATE, TIME, DATETIME2, whatever). Let the front end code resolve the method of display and only store formatted dates when you're building a staging table to build a file from. If you absolutely must display ISO date/time formats from SQL Server, only do it at display time. I can't emphasize enough... do NOT store formatted dates/times in SQL Server.
{Edit}. The reasons for this are many but the most obvious are that, even with a nice ISO format (which is sortable), all future date calculations and searches (search for all rows in a given month, for example) will require at least an implicit conversion (which takes extra time) and if the stored formatted date isn't the format that you currently need, you'll need to first convert it to a date and then to the format you want.
The same holds true for front end code. If you store a formatted date (which is text), it requires the same gyrations to display the local date format defined either by windows or the app.
My recommendation is to always store the date/time as a DATETIME or other temporal datatype and only format the date at display time.
Probably because you forgot to implement the solution in the accepted answer. That's the code that makes trim()
work.
update
This answer only applies to older browsers. Newer browsers apparently support trim()
natively.
That way you haven't installed pip, you installed just the easy_install
i.e. setuptools
.
First you should remove all the packages you installed with easy_install
using (see uninstall):
easy_install -m PackageName
This includes pip
if you installed it using easy_install pip
.
After this you remove the setuptools
following the instructions from here:
If setuptools package is found in your global site-packages directory, you may safely remove the following file/directory:
setuptools-*.egg
If setuptools is installed in some other location such as the user site directory (eg: ~/.local, ~/Library/Python or %APPDATA%), then you may safely remove the following files:
pkg_resources.py
easy_install.py
setuptools/
setuptools-*.egg-info/
After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout
. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".
There was auto generated Copyright message in XML
and a blank line before <resources>
tag, once I removed it my build was successful.
check program with this input:abc/if you got something like ab ac bc abc program works well and you need a stronger RAM otherwise the program is wrong.
This solution works on Red Hat 7.2 & Docker 1.12.0
Edit the file /lib/systemd/system/docker.service in your text editor.
add -g /path/to/docker/ at the end of ExecStart directive. The complete line should look like this.
ExecStart=/usr/bin/dockerd -g /path/to/docker/
Execute the below command
systemctl daemon-reload
systemctl restart docker
Execute the command to check docker directory
docker info | grep "loop file\|Dir"
If you have /etc/sysconfig/docker file in Red Hat or docker 1.7.1 check this answer.
if you are working a lot with arrays and not lists for some reason, this generic typed return generic method Add
might help
public static T[] Add<T>(T[] array, T item)
{
T[] returnarray = new T[array.Length + 1];
for (int i = 0; i < array.Length; i++)
{
returnarray[i] = array[i];
}
returnarray[array.Length] = item;
return returnarray;
}
After refactoring a little bit, this is an example of a complete windows service installer with automatic start:
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace Example.of.name.space
{
[RunInstaller(true)]
public partial class ServiceInstaller : Installer
{
private readonly ServiceProcessInstaller processInstaller;
private readonly System.ServiceProcess.ServiceInstaller serviceInstaller;
public ServiceInstaller()
{
InitializeComponent();
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new System.ServiceProcess.ServiceInstaller();
// Service will run under system account
processInstaller.Account = ServiceAccount.LocalSystem;
// Service will have Automatic Start Type
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = "Windows Automatic Start Service";
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
serviceInstaller.AfterInstall += ServiceInstaller_AfterInstall;
}
private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
ServiceController sc = new ServiceController("Windows Automatic Start Service");
sc.Start();
}
}
}
Delete Dan from employee.data - No need to manage a new data.frame.
employee.data <- subset(employee.data, name!="Dan")
Necropost, but helpful: I came across this problem with an RA request failed since the files "already existed on the server" but wouldn't sync with my repository. I went to the source on my disk, deleted there, refreshed my Eclipse view, and updated the source. Error gone.
You can go to /etc/init.d/ - you will see a daemon template called skeleton.
You can duplicate it and then enter your script under the start function.
The Apache docs recommend against using a rewrite:
To redirect
http
URLs tohttps
, do the following:<VirtualHost *:80> ServerName www.example.com Redirect / https://www.example.com/ </VirtualHost> <VirtualHost *:443> ServerName www.example.com # ... SSL configuration goes here </VirtualHost>
This snippet should go into main server configuration file, not into .htaccess
as asked in the question.
This article might have come up only after the question was asked and answered, but seems to be the current way to go.
Here is my code snippet to fire the click event and pass the value to another form :
private void hearingsDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.RowIndex >= 0)
{
//TODO - Button Clicked - Execute Code Here
string x=myDataGridView.Rows[e.RowIndex].Cells[3].Value.ToString();
Form1 myform = new Form1();
myform.rowid= (int)x;
myform.Show();
}
}
I think if you want to add content directly to the body, the best way is:
document.body.innerHTML = document.body.innerHTML + "bla bla";
To replace it, use:
document.body.innerHTML = "bla bla";
I resolved this problem by doing 2 things:
It depends on what you're trying to achieve after changing the Java file. Until you want to test the maven process, you never need to do anything. Eclipse/MyEclipse will build what is necessary and put the output in the appropriate place within your project. You can also run or deploy it (if it's a web project, for example), without your needing to explicitly do anything with maven. In the end, to install your project in the maven repository, you will need to do a maven install. You may also have other maven goals that you wish to execute, which MyEclipse won't do automatically.
As I say, it depends on what you want to do.
Use window.open()
:
var win = window.open('http://stackoverflow.com/', '_blank');
if (win) {
//Browser has allowed it to be opened
win.focus();
} else {
//Browser has blocked it
alert('Please allow popups for this website');
}
Depending on the browsers implementation this will work
There is nothing you can do to make it open in a window rather than a tab.
With jQuery, I've done it this way:
function checkKey(e){
switch (e.keyCode) {
case 40:
alert('down');
break;
case 38:
alert('up');
break;
case 37:
alert('left');
break;
case 39:
alert('right');
break;
default:
alert('???');
}
}
if ($.browser.mozilla) {
$(document).keypress (checkKey);
} else {
$(document).keydown (checkKey);
}
Also, try these plugins, which looks like they do all that work for you:
http://www.openjs.com/scripts/events/keyboard_shortcuts
http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/
You can find the index number of a character in a string with this:
var str = "abcdefghi"
if let index = str.firstIndex(of: "c") {
let distance = str.distance(from: str.startIndex, to: index)
// distance is 2
}
Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:
public class ItemLinkedList {
private ItemInfoNode head;
private ItemInfoNode tail;
private int size = 0;
public int getSize() {
return size;
}
public void addBack(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, null, tail);
this.tail.next =node;
this.tail = node;
}
}
public void addFront(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, head, null);
this.head.prev = node;
this.head = node;
}
}
public ItemInfo removeBack() {
ItemInfo result = null;
if (head != null) {
size--;
result = tail.info;
if (tail.prev != null) {
tail.prev.next = null;
tail = tail.prev;
} else {
head = null;
tail = null;
}
}
return result;
}
public ItemInfo removeFront() {
ItemInfo result = null;
if (head != null) {
size--;
result = head.info;
if (head.next != null) {
head.next.prev = null;
head = head.next;
} else {
head = null;
tail = null;
}
}
return result;
}
public class ItemInfoNode {
private ItemInfoNode next;
private ItemInfoNode prev;
private ItemInfo info;
public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public void setInfo(ItemInfo info) {
this.info = info;
}
public void setNext(ItemInfoNode node) {
next = node;
}
public void setPrev(ItemInfoNode node) {
prev = node;
}
public ItemInfo getInfo() {
return info;
}
public ItemInfoNode getNext() {
return next;
}
public ItemInfoNode getPrev() {
return prev;
}
}
}
EDIT:
Declare ItemInfo as this:
public class ItemInfo {
private String name;
private String rfdNumber;
private double price;
private String originalPosition;
public ItemInfo(){
}
public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
this.name = name;
this.rfdNumber = rfdNumber;
this.price = price;
this.originalPosition = originalPosition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRfdNumber() {
return rfdNumber;
}
public void setRfdNumber(String rfdNumber) {
this.rfdNumber = rfdNumber;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getOriginalPosition() {
return originalPosition;
}
public void setOriginalPosition(String originalPosition) {
this.originalPosition = originalPosition;
}
}
Then, You can use your nodes inside the linked list like this:
public static void main(String[] args) {
ItemLinkedList list = new ItemLinkedList();
for (int i = 1; i <= 10; i++) {
list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));
}
while (list.size() > 0){
System.out.println(list.removeFront().getName());
}
}
I'm on Windows and I couldn't get any of this stuff to work. I kept getting errors about files being in the way. This worked though:
cd %APPDATA%\nvm\v8.10.0 # or whatever version you're using
mv npm npm-old
mv npm.cmd npm-old.cmd
cd node_modules\
mv npm npm-old
cd npm-old\bin
node npm-cli.js i -g npm@latest
cd %APPDATA%\nvm\v8.10.0 # or whatever version you're using
rm npm-old
rm npm-old.cmd
cd node_modules\
rm -rf npm-old
And boom, I'm back in business.
To get the current time in the local timezone as a naive datetime object:
from datetime import datetime
naive_dt = datetime.now()
If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).
To get the current time in UTC as a naive datetime object:
naive_utc_dt = datetime.utcnow()
To get the current time as an aware datetime object in Python 3.3+:
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time
To get the current time in the given time zone from the tz database:
import pytz
tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)
It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
Base on @mu ? answer here. I've written a cache dump script.
The script dumps all the content of a memcached server. It's tested with Ubuntu 12.04 and a localhost memcached, so your milage may vary.
#!/usr/bin/env bash
echo 'stats items' \
| nc localhost 11211 \
| grep -oe ':[0-9]*:' \
| grep -oe '[0-9]*' \
| sort \
| uniq \
| xargs -L1 -I{} bash -c 'echo "stats cachedump {} 1000" | nc localhost 11211'
What it does, it goes through all the cache slabs and print 1000 entries of each.
Please be aware of certain limits of this script i.e. it may not scale for a 5GB cache server for example. But it's useful for debugging purposes on a local machine.
If you're OK with a SQL command that spreads across multiple lines, then oedo's suggestion is the easiest:
INSERT INTO mytable (myfield) VALUES ('hi this is some text
and this is a linefeed.
and another');
I just had a situation where it was preferable to have the SQL statement all on one line, so I found that a combination of CONCAT_WS()
and CHAR()
worked for me.
INSERT INTO mytable (myfield) VALUES (CONCAT_WS(CHAR(10 using utf8), 'hi this is some text', 'and this is a linefeed.', 'and another'));
Response.Redirect(Request.Url.ToString());
The several answers that purport to show how to do this are all wrong because Java characters are not ASCII characters. Java uses a multibyte encoding of Unicode characters. The Unicode character set is a super set of ASCII. So there can be characters in a Java string that do not belong to ASCII. Such characters do not have an ASCII numeric value, so asking how to get the ASCII numeric value of a Java character is unanswerable.
But why do you want to do this anyway? What are you going to do with the value?
If you want the numeric value so you can convert the Java String to an ASCII string, the real question is "how do I encode a Java String as ASCII". For that, use the object StandardCharsets.US_ASCII
.
You need to have
#include <string>
in the header file too.The forward declaration on it's own doesn't do enough.
Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:
#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H
/* header goes in here */
#endif
This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.
First, a short description of $on()
, $broadcast()
and $emit()
:
.$on(name, listener)
- Listens for a specific event by a given name
.$broadcast(name, args)
- Broadcast an event down through the $scope
of all children.$emit(name, args)
- Emit an event up the $scope
hierarchy to all parents, including the $rootScope
Based on the following HTML (see full example here):
<div ng-controller="Controller1">
<button ng-click="broadcast()">Broadcast 1</button>
<button ng-click="emit()">Emit 1</button>
</div>
<div ng-controller="Controller2">
<button ng-click="broadcast()">Broadcast 2</button>
<button ng-click="emit()">Emit 2</button>
<div ng-controller="Controller3">
<button ng-click="broadcast()">Broadcast 3</button>
<button ng-click="emit()">Emit 3</button>
<br>
<button ng-click="broadcastRoot()">Broadcast Root</button>
<button ng-click="emitRoot()">Emit Root</button>
</div>
</div>
The fired events will traverse the $scopes
as follows:
$scope
$scope
then $rootScope
$scope
then Controller 3 $scope
$scope
then $rootScope
$scope
$scope
, Controller 2 $scope
then $rootScope
$rootScope
and $scope
of all the Controllers (1, 2 then 3) $rootScope
JavaScript to trigger events (again, you can see a working example here):
app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope){
$scope.broadcastAndEmit = function(){
// This will be seen by Controller 1 $scope and all children $scopes
$scope.$broadcast('eventX', {data: '$scope.broadcast'});
// Because this event is fired as an emit (goes up) on the $rootScope,
// only the $rootScope will see it
$rootScope.$emit('eventX', {data: '$rootScope.emit'});
};
$scope.emit = function(){
// Controller 1 $scope, and all parent $scopes (including $rootScope)
// will see this event
$scope.$emit('eventX', {data: '$scope.emit'});
};
$scope.$on('eventX', function(ev, args){
console.log('eventX found on Controller1 $scope');
});
$rootScope.$on('eventX', function(ev, args){
console.log('eventX found on $rootScope');
});
}]);
This code may help some one
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<style type="text/css">
.democlass{
color:red;
}
</style>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var row = table.insertRow(rowCount);
for(var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
row = table.insertRow(table.rows.length);
for(var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
}
row = table.insertRow(table.rows.length);
for(var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[2].cells[i].innerHTML;
}
row = table.insertRow(table.rows.length);
for(var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type=\"button\" value=\"Delete Row\" onclick=\"removeRow(this)\"/>";
} else {
newcell.innerHTML = table.rows[3].cells[i].innerHTML;
}
}
}
/**
* This method deletes the specified section of the table
* OR deletes the specified rows from the table.
*/
function removeRow(src) {
var oRow = src.parentElement.parentElement;
var rowsCount = 0;
for(var index = oRow.rowIndex; index >= 0; index--) {
document.getElementById("dataTable").deleteRow(index);
if(rowsCount == (4 - 1)) {
return;
}
rowsCount++;
}
//once the row reference is obtained, delete it passing in its rowIndex
/* document.getElementById("dataTable").deleteRow(oRow.rowIndex); */
}
</SCRIPT>
</HEAD>
<BODY>
<form name="myForm">
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD>
<INPUT type="checkbox" name="chk"/>
</TD>
<TD>
Code
</TD>
<TD>
<INPUT type="text" name="txt"/>
</TD>
<TD>
Select Country
</TD>
<TD>
<SELECT name="country">
<OPTION value="in">India</OPTION>
<OPTION value="de">Germany</OPTION>
<OPTION value="fr">France</OPTION>
<OPTION value="us">United States</OPTION>
<OPTION value="ch">Switzerland</OPTION>
</SELECT>
</TD>
</TR>
<TR>
<TD> </TD>
<TD>
First Name
</TD>
<TD>
<INPUT type="text" name="txt1"/>
</TD>
<TD>
Last Name
</TD>
<TD>
<INPUT type="text" name="txt2"/>
</TD>
</TR>
<TR>
<TD> </TD>
<TD>Phone</TD>
<TD>
<INPUT type="text" name="txt3"/>
</TD>
<TD>Address</TD>
<TD>
<INPUT type="text" name="txt4" class="democlass"/>
</TD>
</TR>
<TR>
<TD> </TD>
<TD> </TD>
<TD>
</TD>
<TD> </TD>
<TD>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
C programming language standard ISO/IEC 9899:1999 (commonly known as C99) allows one to use a designated initializer to initialize members of a structure or union as follows:
MY_TYPE a = { .stuff = 0.456, .flag = true, .value = 123 };
It is defined in paragraph 7
, section 6.7.8 Initialization
of ISO/IEC 9899:1999 standard as:
If a designator has the form
. identifier
then the current object (defined below) shall have structure or union type and the identifier shall be the name of a member of that type.
Note that paragraph 9
of the same section states that:
Except where explicitly stated otherwise, for the purposes of this subclause unnamed members of objects of structure and union type do not participate in initialization. Unnamed members of structure objects have indeterminate value even after initialization.
In GNU GCC implementation however omitted members are initialized as zero or zero-like type-appropriate value. As stated in section 6.27 Designated Initializers of GNU GCC documentation:
Omitted field members are implicitly initialized the same as objects that have static storage duration.
Microsoft Visual C++ compiler should support designated initializers since version 2013 according to official blog post C++ Conformance Roadmap. Paragraph Initializing unions and structs
of Initializers article at MSDN Visual Studio documentation suggests that unnamed members initialized to zero-like appropriate values similarly to GNU GCC.
ISO/IEC 9899:2011 standard (commonly known as C11) which had superseded ISO/IEC 9899:1999 retains designated initializers under section 6.7.9 Initialization
. It also retains paragraph 9
unchanged.
New ISO/IEC 9899:2018 standard (commonly known as C18) which had superseded ISO/IEC 9899:2011 retains designated initializers under section 6.7.9 Initialization
. It also retains paragraph 9
unchanged.
We can keep our ssh connection alive by having following Global configurations
Add the following line to the /etc/ssh/ssh_config
file:
ServerAliveInterval 60
you may also want to look at
var hours = (datevalue1 - datevalue2).TotalHours;
Another alternative is to use any web hosting with webdav support. You will need some space for this somewhere of course but it is straightforward to set up and a good alternative to running a full blown nexus server.
add this to your build section
<extensions>
<extension>
<artifactId>wagon-webdav-jackrabbit</artifactId>
<groupId>org.apache.maven.wagon</groupId>
<version>2.2</version>
</extension>
</extensions>
Add something like this to your distributionManagement section
<repository>
<id>release.repo</id>
<url>dav:http://repo.jillesvangurp.com/releases/</url>
</repository>
Finally make sure to setup the repository access in your settings.xml
add this to your servers section
<server>
<id>release.repo</id>
<username>xxxx</username>
<password>xxxx</password>
</server>
and a definition to your repositories section
<repository>
<id>release.repo</id>
<url>http://repo.jillesvangurp.com/releases</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
Finally, if you have any standard php hosting, you can use something like sabredav to add webdav capabilities.
Advantages: you have your own maven repository Downsides: you don't have any of the management capabilities in nexus; you need some webdav setup somewhere
If you only need it once, it's overkill to load a plugin.
For a date "dd/mm/yyyy", this works for me:
new Date(d.date.substring(6, 10),d.date.substring(3, 5)-1,d.date.substring(0, 2));
Just invert month and day for mm/dd/yyyy, the syntax is
new Date(y,m,d)
As a complete all-in one package, Visual Studio 2008 is the best IDE for C++ development with Windows
i was facing exactly the same issue and i made following changes to my URL after which it was working perfectly fine..
From:
http://localhost/Image4android/get_all_images.php
To:
http://192.168.1.2/Image4android/get_all_images.php
where the ip: 192.168.1.2 is IPv4 address. In windows Run > CMD > Ipconfig
Quoting directly from the help page for factor
:
To transform a factor f to its original numeric values, as.numeric(levels(f))[f]
is recommended and slightly more efficient than as.numeric(as.character(f))
.
You do not need to use {{ }} inside of ng-bind-html-unsafe:
<div ng-bind-html-unsafe="preview_data.preview.embed.html"></div>
Here's an example: http://plnkr.co/edit/R7JmGIo4xcJoBc1v4iki?p=preview
The {{ }} operator is essentially just a shorthand for ng-bind, so what you were trying amounts to a binding inside a binding, which doesn't work.
If you have both remote server then you can follow this:
pg_dump -U Username -h DatabaseEndPoint -a -t TableToCopy SourceDatabase | psql -h DatabaseEndPoint -p portNumber -U Username -W TargetDatabase
It will copy the mentioned table of source Database into same named table of target database, if you already have existing schema.
Dalef great solution in swift:
self.navigationController?.view.addSubview(view)
day1= (int)ClockInfoFromSystem.DayOfWeek;
Use following code to perform if-else conditioning in python: Here, I am checking the length of the string. If the length is less than 3 then do nothing, if more then 3 then I check the last 3 characters. If last 3 characters are "ing" then I add "ly" at the end otherwise I add "ing" at the end.
Code-
if (len(s)<=3):
return s
elif s[-3:]=="ing":
return s+"ly"
else: return s + "ing"
you can also use below solution -
public static String getRoundOffValue(double value){
DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00");
return df.format(value);
}
You could use a new annotation to solve this:
@XXXToXXX(targetEntity = XXXX.class, fetch = FetchType.LAZY)
In fact, fetch's default value is FetchType.LAZY too.
try this one :
public void itemClicked(View v) {
//code to check if this checkbox is checked!
CheckBox checkBox = (CheckBox)v;
if(checkBox.isChecked()){
}
}
Yes, but what does grouping by more two columns mean? Well, it's the same as grouping by each unique pair per row. The order you list the columns changes the way the rows are sorted.
In your example, you would write
GROUP BY fV.tier_id, f.form_template_id
Meanwhile, the code
GROUP BY f.form_template_id, fV.tier_id
would give similar results, but sorted differently.
There looks to be an issue with the latest version of the pip module pytesseract=0.3.7. I have downgraded it to pytesseract=0.3.6 and don't see the error.
The quotes you use are the issue:
<meta http-equiv=”refresh” content=”5" >
You should use the "
<meta http-equiv="refresh" content="5">
I think you already listed the best practice and that is NOT to use it unless REALLY necessary. I would strongly recommend looking at your code in more detail, using profiling tools potentially if needed to answer these questions first.
They are the same thing. .hide()
calls a jQuery function and allows you to add a callback function to it. So, with .hide()
you can add an animation for instance.
.css("display","none")
changes the attribute of the element to display:none
. It is the same as if you do the following in JavaScript:
document.getElementById('elementId').style.display = 'none';
The .hide()
function obviously takes more time to run as it checks for callback functions, speed, etc...
I'd rather tab indentation not work than breaking tabbing between form items.
If you want to indent to put in code in the Markdown box, use Ctrl+K (or ?K on a Mac).
In terms of actually stopping the action, jQuery (which Stack Overflow uses) will stop an event from bubbling when you return false from an event callback. This makes life easier for working with multiple browsers.
The property you are looking for that first td is rowspan
:
http://www.angelfire.com/fl5/html-tutorial/tables/tr_code.htm
<table>
<tr><td rowspan="2"></td><td colspan='4'></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
</table>
One downside of the solutions based on grid.arrange
is that they make it difficult to label the plots with letters (A, B, etc.), as most journals require.
I wrote the cowplot package to solve this (and a few other) issues, specifically the function plot_grid()
:
library(cowplot)
iris1 <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
geom_boxplot() + theme_bw()
iris2 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
geom_density(alpha = 0.7) + theme_bw() +
theme(legend.position = c(0.8, 0.8))
plot_grid(iris1, iris2, labels = "AUTO")
The object that plot_grid()
returns is another ggplot2 object, and you can save it with ggsave()
as usual:
p <- plot_grid(iris1, iris2, labels = "AUTO")
ggsave("plot.pdf", p)
Alternatively, you can use the cowplot function save_plot()
, which is a thin wrapper around ggsave()
that makes it easy to get the correct dimensions for combined plots, e.g.:
p <- plot_grid(iris1, iris2, labels = "AUTO")
save_plot("plot.pdf", p, ncol = 2)
(The ncol = 2
argument tells save_plot()
that there are two plots side-by-side, and save_plot()
makes the saved image twice as wide.)
For a more in-depth description of how to arrange plots in a grid see this vignette. There is also a vignette explaining how to make plots with a shared legend.
One frequent point of confusion is that the cowplot package changes the default ggplot2 theme. The package behaves that way because it was originally written for internal lab uses, and we never use the default theme. If this causes problems, you can use one of the following three approaches to work around them:
1. Set the theme manually for every plot. I think it's good practice to always specify a particular theme for each plot, just like I did with + theme_bw()
in the example above. If you specify a particular theme, the default theme doesn't matter.
2. Revert the default theme back to the ggplot2 default. You can do this with one line of code:
theme_set(theme_gray())
3. Call cowplot functions without attaching the package. You can also not call library(cowplot)
or require(cowplot)
and instead call cowplot functions by prepending cowplot::
. E.g., the above example using the ggplot2 default theme would become:
## Commented out, we don't call this
# library(cowplot)
iris1 <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
geom_boxplot()
iris2 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
geom_density(alpha = 0.7) +
theme(legend.position = c(0.8, 0.8))
cowplot::plot_grid(iris1, iris2, labels = "AUTO")
Updates:
The JavaScript try…catch mechanism cannot be used to intercept errors generated by asynchronous APIs. A common mistake for beginners is to try to use throw inside an error-first callback:
// THIS WILL NOT WORK:
const fs = require('fs');
try {
fs.readFile('/some/file/that/does-not-exist', (err, data) => {
// Mistaken assumption: throwing here...
if (err) {
throw err;
}
});
} catch (err) {
// This will not catch the throw!
console.error(err);
}
This will not work because the callback function passed to fs.readFile() is called asynchronously. By the time the callback has been called, the surrounding code, including the try…catch block, will have already exited. Throwing an error inside the callback can crash the Node.js process in most cases. If domains are enabled, or a handler has been registered with process.on('uncaughtException'), such errors can be intercepted.
reference: https://nodejs.org/api/errors.html
Try the following, but before running it note that the -k
flag will kill any running processes keeping the device busy.
The -i
flag makes fuser
ask before killing.
fuser -kim /address # kill any processes accessing file
unmount /address
I experienced this issue when trying to restore a database on MS SQL Server 2012.
Here's what worked for me:
I had to first run the RESTORE FILELISTONLY
command below on the backup file to list the logical file names:
RESTORE FILELISTONLY
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'
This displayed the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively:
LogicalName PhysicalName
com.my_db C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf
com.my_db_log C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf
All I had to do was to simply replace the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively in my database restore script:
USE master;
GO
ALTER DATABASE my_db SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
RESTORE DATABASE my_db
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'
WITH REPLACE,
MOVE 'com.my_db' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf',
MOVE 'com.my_db_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf'
GO
ALTER DATABASE my_db SET MULTI_USER;
GO
And the Database Restore task ran successfully:
That's all.
I hope this helps
Script grouping is counterproductive, you should load them in parallel using something like http://yepnopejs.com/ or http://headjs.com
On many Linux systems, like Ubuntu, the .vimrc
file doesn't exist by default, so it is recommended that you create it first.
Don't use the .viminfo
file that exist in the home directory. It is used for a different purpose.
Step 1: Go to your home directory
cd ~
Step 2: Create the file
vim .vimrc
Step 3: Add the configuration stated above
filetype plugin indent on
set tabstop=4
set shiftwidth=4
set expandtab
Step 3: Save file, by pressing Shift + ZZ.
.c1 {
height: unset;
}
The unset
value added in CSS3 also solves this problem and it's even more universal method than auto
or initial
because it sets to every CSS property its default value and additionally its default behawior relative to its parent.
Note that initial
value breaks aforementioned behavior.
From MDN:
Like these two other CSS-wide keywords, it can be applied to any CSS property, including the CSS shorthand all. This keyword resets the property to its inherited value if it inherits from its parent or to its initial value if not.
If you transferred these files through disk or other means, it is likely they were not saved properly.
Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.
Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.
The best documentation you'll find on the topic is the virtual host documentation in the apache manual.
There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.
The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost
line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost
entry for each port.
Assuming you're starting from scratch, this is much simpler than it may seem.
If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.
NameVirtualHost *:80
If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost
directive, and it will be removed in a future version.
Now your vhost definitions:
<VirtualHost *:80>
DocumentRoot "/home/user/site1/"
ServerName site1
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/home/user/site2/"
ServerName site2
</VirtualHost>
You can run as many sites as you want on the same port. The ServerName
being different is enough to tell Apache which vhost to use. Also, the ServerName
directive is always the domain/hostname and should never include a path.
If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81
The application that you are running is blocked because the application does not comply with security guidelines implemented in Java 7 Update 51
It looks as though it's not an array but an arbitrary object. If you have control over the PHP serialization, you might be able to change that.
As raina77ow pointed out, one way to do this in PHP would be by replacing something like this:
json_encode($something)
with something like:
json_encode(array_values($something))
But don't ignore the other answers here about Object.keys
. They should also accomplish what you want if you don't have the ability or the desire to change the serialization of your object.
For those arriving here from google, I've eventually come across this SO question, and this specific answer solved my problem. I've contacted Microsoft for the hotfix through the live chat on support.microsoft.com and they sent me a link to the hotfix by email.
No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.
XML has only one definition for a comment:
'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
XML forbids --
in comments to maintain compatibility with SGML.
I found my answer.
<?php
$profpic = "bg.jpg";
?>
<html>
<head>
<style type="text/css">
body {
background-image: url('<?php echo $profpic;?>');
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hey</title>
</head>
<body>
</body>
</html>
First, Set :
ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;
The correct path shouldn't end with "/", I had it wrong that caused the trouble
Right way:
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
In response to your postscript, that depends on what you would like.
You are getting (possible) multiple rows for each row in your left table because there are multiple matches for the join condition. If you want your total results to have the same number of rows as there is in the left part of the query you need to make sure your join conditions cause a 1-to-1 match.
Alternatively, depending on what you actually want you can use aggregate functions (if for example you just want a string from the right part you could generate a column that is a comma delimited string of the right side results for that left row.
If you are only looking at 1 or 2 columns from the outer join you might consider using a scalar subquery since you will be guaranteed 1 result.
You can return FileResult with this methods:
1: Return FileStreamResult
[HttpGet("get-file-stream/{id}"]
public async Task<FileStreamResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
var stream = await GetFileStreamById(id);
return new FileStreamResult(stream, mimeType)
{
FileDownloadName = fileName
};
}
2: Return FileContentResult
[HttpGet("get-file-content/{id}"]
public async Task<FileContentResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
var fileBytes = await GetFileBytesById(id);
return new FileContentResult(fileBytes, mimeType)
{
FileDownloadName = fileName
};
}
Another option could be:
var initial = function() {
console.log( 'initial function!' );
}
var iWantToExecuteThisOneToo = function () {
console.log( 'the other function that i wanted to execute!' );
}
function extendFunction( oldOne, newOne ) {
return (function() {
oldOne();
newOne();
})();
}
var extendedFunction = extendFunction( initial, iWantToExecuteThisOneToo );
You can use the CSS3 Linear Gradient property along with your background-image like this:
#landing-wrapper {
display:table;
width:100%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
background-position:center top;
height:350px;
}
Here's a demo:
#landing-wrapper {_x000D_
display: table;_x000D_
width: 100%;_x000D_
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
background-position: center top;_x000D_
height: 350px;_x000D_
color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
You can use this code without arrows.....i.e by clicking on header it automatically shows ascending and descending order of elements
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="scripts/angular.min.js"></script>
<script src="Scripts/Script.js"></script>
<style>
table {
border-collapse: collapse;
font-family: Arial;
}
td {
border: 1px solid black;
padding: 5px;
}
th {
border: 1px solid black;
padding: 5px;
text-align: left;
}
</style>
</head>
<body ng-app="myModule">
<div ng-controller="myController">
<br /><br />
<table>
<thead>
<tr>
<th>
<a href="#" ng-click="orderByField='name'; reverseSort = !reverseSort">
Name
</a>
</th>
<th>
<a href="#" ng-click="orderByField='dateOfBirth'; reverseSort = !reverseSort">
Date Of Birth
</a>
</th>
<th>
<a href="#" ng-click="orderByField='gender'; reverseSort = !reverseSort">
Gender
</a>
</th>
<th>
<a href="#" ng-click="orderByField='salary'; reverseSort = !reverseSort">
Salary
</a>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees | orderBy:orderByField:reverseSort">
<td>
{{ employee.name }}
</td>
<td>
{{ employee.dateOfBirth | date:"dd/MM/yyyy" }}
</td>
<td>
{{ employee.gender }}
</td>
<td>
{{ employee.salary }}
</td>
</tr>
</tbody>
</table>
</div>
<script>
var app = angular
.module("myModule", [])
.controller("myController", function ($scope) {
var employees = [
{
name: "Ben", dateOfBirth: new Date("November 23, 1980"),
gender: "Male", salary: 55000
},
{
name: "Sara", dateOfBirth: new Date("May 05, 1970"),
gender: "Female", salary: 68000
},
{
name: "Mark", dateOfBirth: new Date("August 15, 1974"),
gender: "Male", salary: 57000
},
{
name: "Pam", dateOfBirth: new Date("October 27, 1979"),
gender: "Female", salary: 53000
},
{
name: "Todd", dateOfBirth: new Date("December 30, 1983"),
gender: "Male", salary: 60000
}
];
$scope.employees = employees;
$scope.orderByField = 'name';
$scope.reverseSort = false;
});
</script>
</body>
</html>
The folks at MSSQLTips have some very helpful articles, the one most relevant for this is "Automating SQL Server 2005 Express Backups and Deletion of Older Backup Files"
The basic approach is to set up two tasks using the Windows Task Scheduler. One task runs a TSQL script that generates separate backup files for all MSSQL databases (except TEMPDB) with the database name and a date/time stamp in the file name into a specified directory. The second task runs a VBScript script that goes through that directory and deletes all files with a .BAK extension that are more than 3 days old.
Both scripts require minor editing for your environment (paths, how long to keep those database dumps) but are very close to drop-in-and-run.
Note that there are possible security implications if you're sloppy with these or with directory permissions, since they are plain text files that will need to run with some level of privilege. Don't be sloppy.
I'm not sure of a way to do this in 3D, but in 2D you can use the compass
command.
Here is a rough explanation of the concepts.
[ACK]
is the acknowledgement that the previously sent data packet was received.
[FIN]
is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN
).
So, suppose
[FIN,ACK]
indicating that it received the sent packet and wants to close the session.[FIN,ACK]
indicating that it received the termination request (the ACK
part) and that it too will close the connection (the FIN
part).However, if host A wants to close the session after sending the packet, it would only send a [FIN]
packet (nothing to acknowledge) but host B would respond with [FIN,ACK]
(acknowledges the request and responds with FIN
).
Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST]
instead of the usual [FIN,ACK]
. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.
You can find a more detailed and comprehensive explanation here.
In case you don't want to use the M2_HOME and want to direct the IntelliJ to the maven installation you can simply set it by:
A better way is to have a symlink e.g. 'latest' for the latest version and point your IntelliJ to use that for consistency, given latest points to the latest version of maven installed on your box.
You can do :
document.forms["loginForm"].submit()
But this won't call the onclick
action of your button, so you will need to call it by hand.
Be aware that you must use the name
of your form and not the id
to access it.
A couple of answers that should work above but this is how i would write it.
Also, i wouldn't declare controllers inside templates. It's better to declare them on your routes imo.
add-text.tpl.html
<div ng-controller="myController">
<form ng-submit="addText(myText)">
<input type="text" placeholder="Let's Go" ng-model="myText">
<button type="submit">Add</button>
</form>
<ul>
<li ng-repeat="text in arrayText">{{ text }}</li>
</ul>
</div>
app.js
(function() {
function myController($scope) {
$scope.arrayText = ['hello', 'world'];
$scope.addText = function(myText) {
$scope.arrayText.push(myText);
};
}
angular.module('app', [])
.controller('myController', myController);
})();
You should use white-space with display table
Example:
legend {
display:table; /* Enable line-wrapping in IE8+ */
white-space:normal; /* Enable line-wrapping in old versions of some other browsers */
}
I'm not sure about what you're trying to do... maybe something like
SELECT gid, COUNT(*) AS num FROM gd GROUP BY gid HAVING num > 10 ORDER BY lastupdated DESC
Python datetimes are a little clunky. Use arrow
.
> str(arrow.utcnow())
'2014-05-17T01:18:47.944126+00:00'
Arrow has essentially the same api as datetime, but with timezones and some extra niceties that should be in the main library.
A format compatible with Javascript can be achieved by:
arrow.utcnow().isoformat().replace("+00:00", "Z")
'2018-11-30T02:46:40.714281Z'
Javascript Date.parse
will quietly drop microseconds from the timestamp.
Question 1: Do erlang, python and haskell loose speed due to using arbitrary length integers or don't they as long as the values are less than MAXINT?
This is unlikely. I cannot say much about Erlang and Haskell (well, maybe a bit about Haskell below) but I can point a lot of other bottlenecks in Python. Every time the program tries to execute an operation with some values in Python, it should verify whether the values are from the proper type, and it costs a bit of time. Your factorCount
function just allocates a list with range (1, isquare + 1)
various times, and runtime, malloc
-styled memory allocation is way slower than iterating on a range with a counter as you do in C. Notably, the factorCount()
is called multiple times and so allocates a lot of lists. Also, let us not forget that Python is interpreted and the CPython interpreter has no great focus on being optimized.
EDIT: oh, well, I note that you are using Python 3 so range()
does not return a list, but a generator. In this case, my point about allocating lists is half-wrong: the function just allocates range
objects, which are inefficient nonetheless but not as inefficient as allocating a list with a lot of items.
Question 2: Why is haskell so slow? Is there a compiler flag that turns off the brakes or is it my implementation? (The latter is quite probable as haskell is a book with seven seals to me.)
Are you using Hugs? Hugs is a considerably slow interpreter. If you are using it, maybe you can get a better time with GHC - but I am only cogitating hypotesis, the kind of stuff a good Haskell compiler does under the hood is pretty fascinating and way beyond my comprehension :)
Question 3: Can you offer me some hints how to optimize these implementations without changing the way I determine the factors? Optimization in any way: nicer, faster, more "native" to the language.
I'd say you are playing an unfunny game. The best part of knowing various languages is to use them the most different way possible :) But I digress, I just do not have any recommendation for this point. Sorry, I hope someone can help you in this case :)
Question 4: Do my functional implementations permit LCO and hence avoid adding unnecessary frames onto the call stack?
As far as I remember, you just need to make sure that your recursive call is the last command before returning a value. In other words, a function like the one below could use such optimization:
def factorial(n, acc=1):
if n > 1:
acc = acc * n
n = n - 1
return factorial(n, acc)
else:
return acc
However, you would not have such optimization if your function were such as the one below, because there is an operation (multiplication) after the recursive call:
def factorial2(n):
if n > 1:
f = factorial2(n-1)
return f*n
else:
return 1
I separated the operations in some local variables for make it clear which operations are executed. However, the most usual is to see these functions as below, but they are equivalent for the point I am making:
def factorial(n, acc=1):
if n > 1:
return factorial(n-1, acc*n)
else:
return acc
def factorial2(n):
if n > 1:
return n*factorial(n-1)
else:
return 1
Note that it is up to the compiler/interpreter to decide if it will make tail recursion. For example, the Python interpreter does not do it if I remember well (I used Python in my example only because of its fluent syntax). Anyway, if you find strange stuff such as factorial functions with two parameters (and one of the parameters has names such as acc
, accumulator
etc.) now you know why people do it :)
try the following as there will be no varchar conversion
SELECT Subject, CAST(DeliveryDate AS DATE)
from Email_Administration
where MerchantId =@ MerchantID
I wanted the new application start up after the old one shuts down.
Using process.WaitForExit() to wait for your own process to shutdown makes no sense. It will always time out.
So, my approach is to use Application.Exit() then wait, but allow events to be processed, for a period of time. Then start a new application with the same arguments as the old.
static void restartApp() {
string commandLineArgs = getCommandLineArgs();
string exePath = Application.ExecutablePath;
try {
Application.Exit();
wait_allowingEvents( 1000 );
} catch( ArgumentException ex ) {
throw;
}
Process.Start( exePath, commandLineArgs );
}
static string getCommandLineArgs() {
Queue<string> args = new Queue<string>( Environment.GetCommandLineArgs() );
args.Dequeue(); // args[0] is always exe path/filename
return string.Join( " ", args.ToArray() );
}
static void wait_allowingEvents( int durationMS ) {
DateTime start = DateTime.Now;
do {
Application.DoEvents();
} while( start.Subtract( DateTime.Now ).TotalMilliseconds > durationMS );
}
You could create a JsonConverter
. See here for an example thats similar to your question.
If you need to skip the password prompt for some reason, you can input the password in the command (Dangerous)
mysql -u root --password=secret
It might be worth noting that this can also occur when Windows blocks downloads that it considers to be unsafe. This can be addressed by right-clicking the jar file (such as ojdbc7.jar), and checking the 'Unblock' box at the bottom.
Windows JAR File Properties Dialog:
So this is my first answer here, and because I needed something similar I did with pseudo elements for 2 inner shadows, and an extra DIV for an upper outer shadow. Don't know if this is the best solutions but maybe it will help someone.
HTML
<div class="shadow-block">
<div class="shadow"></div>
<div class="overlay">
<div class="overlay-inner">
content here
</div>
</div>
</div>
CSS
.overlay {
background: #f7f7f4;
height: 185px;
overflow: hidden;
position: relative;
width: 100%;
}
.overlay:before {
border-radius: 50% 50% 50% 50%;
box-shadow: 0 0 50px 2px rgba(1, 1, 1, 0.6);
content: " ";
display: block;
margin: 0 auto;
width: 80%;
}
.overlay:after {
border-radius: 50% 50% 50% 50%;
box-shadow: 0 0 70px 5px rgba(1, 1, 1, 0.5);
content: "-";
display: block;
margin: 0 auto;
position: absolute;
bottom: -65px;
left: -50%;
right: -50%;
width: 80%;
}
.shadow {
position: relative;
width:100%;
height:8px;
margin: 0 0 -22px 0;
-webkit-box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
border-radius: 50%;
}
Once I have followed all these steps, I start to receive error messages in all android classes calls like:
I revolved that including android.jar in the SDKs Platform Settings:
The short answer is YES. lucky you!
To do so, you need to override some styles of the Android default styles :
First, look at the definition of the themes in Android :
<style name="Theme.IconMenu">
<!-- Menu/item attributes -->
<item name="android:itemTextAppearance">@android:style/TextAppearance.Widget.IconMenu.Item</item>
<item name="android:itemBackground">@android:drawable/menu_selector</item>
<item name="android:itemIconDisabledAlpha">?android:attr/disabledAlpha</item>
<item name="android:horizontalDivider">@android:drawable/divider_horizontal_bright</item>
<item name="android:verticalDivider">@android:drawable/divider_vertical_bright</item>
<item name="android:windowAnimationStyle">@android:style/Animation.OptionsPanel</item>
<item name="android:moreIcon">@android:drawable/ic_menu_more</item>
<item name="android:background">@null</item>
</style>
So, the appearance of the text in the menu is in @android:style/TextAppearance.Widget.IconMenu.Item
Now, in the definition of the styles :
<style name="TextAppearance.Widget.IconMenu.Item" parent="TextAppearance.Small">
<item name="android:textColor">?textColorPrimaryInverse</item>
</style>
So now we have the name of the color in question, if you look in the color folder of the resources of the system :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="@android:color/bright_foreground_light_disabled" />
<item android:state_window_focused="false" android:color="@android:color/bright_foreground_light" />
<item android:state_pressed="true" android:color="@android:color/bright_foreground_light" />
<item android:state_selected="true" android:color="@android:color/bright_foreground_light" />
<item android:color="@android:color/bright_foreground_light" />
<!-- not selected -->
</selector>
Finally, here is what you need to do :
Override "TextAppearance.Widget.IconMenu.Item" and create your own style. Then link it to your own selector to make it the way you want. Hope this helps you. Good luck!
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myfun(){
$(document).ready(function(){
$("#select").click(
function(){
var data=$("#select").val();
$("#disp").val(data);
});
});
}
</script>
</head>
<body>
<p>id <input type="text" name="user" id="disp"></p>
<select id="select" onclick="myfun()">
<option name="1"value="one">1</option>
<option name="2"value="two">2</option>
<option name="3"value="three"></option>
</select>
</body>
</html>
Try: Controls("Check Box 1") = True
You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:
if ([category isEqualToString:@"Some String"])
{
// Both strings are equal without respect to their case.
}
Case-insensitive is like this:
if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
// Both strings are equal with respect to their case.
}
Source: https://gist.github.com/sagarjethi/c07723b2f4fa74ad8bdf229166cf79d8
For example your last commit
git push origin +aa61ab32^:master
Now you want to delete this commit then an Easy way to do this following
Steps
First reset the branch to the parent of the current commit
Force-push it to the remote.
git reset HEAD^ --hard git push origin -f
For particular commit, you want to reset is following
git reset bb676878^ --hard
git push origin -f
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
No, but you could have something like:
bool b;
b = b.YourExtensionMethod();
brute force (and only tested on an Oracle system, but I think this is pretty standard):
select distinct usr_id from users where user_id in (
select user_id from (
Select user_id, Count(User_Id) As Cc
From users
GROUP BY user_id
) Where Cc =3
)
and ancestry in ('England', 'France', 'Germany')
;
edit: I like @HuckIt's answer even better.
Thought I'd add a bit to the answer.
If you have multiple URL definitions then you'll have to name each of them separately. So you lose the flexibility when calling reverse since one reverse will expect a parameter while the other won't.
Another way to use regex to accommodate the optional parameter:
r'^project_config/(?P<product>\w+)/((?P<project_id>\w+)/)?$'
Yes, you would have to change the window.location.href to the url of the file you would want to download.
window.location.href = 'http://www.com/path/to/file';
I was facing this issue and fixed by putting a check in form attribute. This issue can happen when the FormGroup is not initialized.
<form [formGroup]="loginForm" *ngIf="loginForm">
OR
<form [formGroup]="loginForm" *ngIf="this.loginForm">
This will not render the form until it is initialized.
InternetAddress.Parse is going to be your friend! See the worked example below:
String to = "[email protected], [email protected], [email protected]";
String toCommaAndSpaces = "[email protected] [email protected], [email protected]";
If strict is true, many (but not all) of the RFC822 syntax rules for emails are enforced.
msg.setRecipients(Message.RecipientType.CC,
InternetAddress.parse(to, true));
Parse comma/space-separated list. Cut some slack. We allow spaces seperated list as well, plus invalid email formats.
msg.setRecipients(Message.RecipientType.BCC,
InternetAddress.parse(toCommaAndSpaces, false));
In terms of performance measurement, if you are considering the time performance then the Integer.toString(i); is expensive if you are calling less than 100 million times. Else if it is more than 100 million calls then the new Integer(10).toString() will perform better.
Below is the code through u can try to measure the performance,
public static void main(String args[]) {
int MAX_ITERATION = 10000000;
long starttime = System.currentTimeMillis();
for (int i = 0; i < MAX_ITERATION; ++i) {
String s = Integer.toString(10);
}
long endtime = System.currentTimeMillis();
System.out.println("diff1: " + (endtime-starttime));
starttime = System.currentTimeMillis();
for (int i = 0; i < MAX_ITERATION; ++i) {
String s1 = new Integer(10).toString();
}
endtime = System.currentTimeMillis();
System.out.println("diff2: " + (endtime-starttime));
}
In terms of memory, the
new Integer(i).toString();
will take more memory as it will create the object each time, so memory fragmentation will happen.
Simple
ng g component plainsight/some-name
It will create "plainsight" folder and generate some-name component inside it.
it's the same as think the next:
"starting with i = 0, while i is less than 8, and adding one to i at the end of the parenthesis, do the instructions between brackets"
It's also the same as:
while( i < 8 )
{
// instrucctions like:
Console.WriteLine(i);
i++;
}
the For sentences is a basis of coding, and it's as useful as necessary its understanding.
It's the way to repeat n-times the same instrucction, or browse ( or do something with each element) an array
I don't care if the page reloads or displays the results immediately;
Good!
Note: If you don't want to refresh the page see "Ok... but how do I Use Ajax anyway?" below.
I just want to have a button on my website make a PHP file run.
That can be done with a form with a single button:
<form action="">
<input type="submit" value="my button"/>
</form>
That's it.
Pretty much. Also note that there are cases where ajax is really the way to go.
That depends on what you want. In general terms you only need ajax when you want to avoid realoading the page. Still you have said that you don't care about that.
If I can write the code inside HTML just fine, why can't I just reference the file for it in there or make a simple call for it in Javascript?
Because the PHP code is not in the HTML just fine
. That's an illusion created by the way most server side scripting languages works (including PHP, JSP, and ASP). That code only exists on the server, and it is no reachable form the client (the browser) without a remote call of some sort.
You can see evidence of this if you ask your browser to show the source code of the page. There you will not see the PHP code, that is because the PHP code is not send to the client, therefore it cannot be executed from the client. That's why you need to do a remote call to be able to have the client trigger the execution of PHP code.
If you don't use a form (as shown above) you can do that remote call from JavaScript with a little thing called Ajax. You may also want to consider if what you want to do in PHP can be done directly in JavaScript.
Use a form to do the call. You can have it to direct the user to a particlar file:
<form action="myphpfile.php">
<input type="submit" value="click on me!">
</form>
The user will end up in the page myphpfile.php
. To make it work for the current page, set action to an empty string (which is what I did in the example I gave you early).
I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.
You want to make an operation on the server, you should make your form have the fields you need (even if type="hidden"
and use POST
):
<form action="" method="POST">
<input type="text" value="default value, you can edit it" name="myfield">
<input type="submit" value = "post">
</form>
What do I need to know about it to call a PHP file that will create a text file on a button press?
see: How to write into a file in PHP.
I'm glad you ask... Since you are a newb begginer, I'll give you a little template you can follow:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
//Ok we got a POST, probably from a FORM, read from $_POST.
var_dump($_PSOT); //Use this to see what info we got!
}
else
{
//You could assume you got a GET
var_dump($_GET); //Use this to see what info we got!
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta char-set="utf-8">
<title>Page title</title>
</head>
<body>
<form action="" method="POST">
<input type="text" value="default value, you can edit it" name="myfield">
<input type="submit" value = "post">
</form>
</body>
</html>
Note: you can remove var_dump
, it is just for debugging purposes.
I know the next stage, you will be asking how to:
There is a single answer for that: Sessions.
I'll give a more extensive template for Post-Redirect-Get
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
var_dump($_PSOT);
//Do stuff...
//Write results to session
session_start();
$_SESSION['stuff'] = $something;
//You can store stuff such as the user ID, so you can remeember him.
//redirect:
header('Location: ', true, 303);
//The redirection will cause the browser to request with GET
//The results of the operation are in the session variable
//It has empty location because we are redirecting to the same page
//Otherwise use `header('Location: anotherpage.php', true, 303);`
exit();
}
else
{
//You could assume you got a GET
var_dump($_GET); //Use this to see what info we got!
//Get stuff from session
session_start();
if (array_key_exists('stuff', $_SESSION))
{
$something = $_SESSION['stuff'];
//we got stuff
//later use present the results of the operation to the user.
}
//clear stuff from session:
unset($_SESSION['stuff']);
//set headers
header('Content-Type: text/html; charset=utf-8');
//This header is telling the browser what are we sending.
//And it says we are sending HTML in UTF-8 encoding
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta char-set="utf-8">
<title>Page title</title>
</head>
<body>
<?php if (isset($something)){ echo '<span>'.$something.'</span>'}?>;
<form action="" method="POST">
<input type="text" value="default value, you can edit it" name="myfield">
<input type="submit" value = "post">
</form>
</body>
</html>
Please look at php.net for any function call you don't recognize. Also - if you don't have already - get a good tutorial on HTML5.
Also, use UTF-8 because UTF-8!
Notes:
I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately.
If are you using a CMS (Codepress, Joomla, Drupal... etc)? That make put some contraints on how you got to do things.
Also, if you are using a framework, you should look at their documentation or ask at their forum/mailing list/discussion page/contact or try to ask the authors.
Well... Ajax is made easy by some JavaScript libraries. Since you are a begginer, I'll recomend jQuery.
So, let's send something to the server via Ajax with jQuery, I'll use $.post instead of $.ajax for this example.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
var_dump($_PSOT);
header('Location: ', true, 303);
exit();
}
else
{
var_dump($_GET);
header('Content-Type: text/html; charset=utf-8');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta char-set="utf-8">
<title>Page title</title>
<script>
function ajaxmagic()
{
$.post( //call the server
"test.php", //At this url
{
field: "value",
name: "John"
} //And send this data to it
).done( //And when it's done
function(data)
{
$('#fromAjax').html(data); //Update here with the response
}
);
}
</script>
</head>
<body>
<input type="button" value = "use ajax", onclick="ajaxmagic()">
<span id="fromAjax"></span>
</body>
</html>
The above code will send a POST request to the page test.php
.
Note: You can mix sessions
with ajax
and stuff if you want.
... for these or any other, please make another questions. That's too much for this one.
I know that this is super-duper old, but on the off chance that someone comes looking for this, as of Visual Basic 14, Vb supports interpolation. Sooooo cool!
Example:
SQLQueryString = $"
Insert into Employee values(
{txtEmployeeNo},
{txtContractsStartDate},
{txtSeatNo},
{txtFloor},
{txtLeaves}
)"
It works. Documentation Here
Edit: After writing this, I realized that the OP was talking about VBA. This will not work in VBA!!! However, I will leave this up here, because as someone new to VB, I stumbled upon this question looking for a solution to just this problem in VB.net. If this helps someone else, great.
It looks like this issue has to do with the difference between the Content-Type
and Accept
headers. In HTTP, Content-Type
is used in request and response payloads to convey the media type of the current payload. Accept
is used in request payloads to say what media types the server may use in the response payload.
So, having a Content-Type
in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type
does matter.
If a server is not able to process the Content-Type
of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept
header, it will return a 406 error.)
In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.
You could fix this in one of two ways:
Include the DataServiceVersion header in the request and set it be less than v3. For example:
DataServiceVersion: 2.0;
(Option 2 assumes that you aren't using any v3 features in your request payload.)
src="/clock.js"
be careful it's root of the domain.
P.S. and please use lowercase for attribute names.
Individual element copy, it seems to work for me with just a simple example.
maps := map[string]int {
"alice":12,
"jimmy":15,
}
maps2 := make(map[string]int)
for k2,v2 := range maps {
maps2[k2] = v2
}
maps2["miki"]=rand.Intn(100)
fmt.Println("maps: ",maps," vs. ","maps2: ",maps2)
Expanding on the answer using this:
body {
width: calc(100vw - 17px);
}
One commentor suggested adding left-padding as well to maintain the centering:
body {
padding-left: 17px;
width: calc(100vw - 17px);
}
But then things don't look correct if your content is wider than the viewport. To fix that, you can use media queries, like this:
@media screen and (min-width: 1058px) {
body {
padding-left: 17px;
width: calc(100vw - 17px);
}
}
Where the 1058px = content width + 17 * 2
This lets a horizontal scrollbar handle the x overflow and keeps the centered content centered when the viewport is wide enough to contain your fixed-width content
in my case there was a rule about hover-effect by the anchor, like this:
#content a:hover {
border-bottom: 1px solid #333;
}
Of course, text-decoration: none;
could not help in this situation.
And I spend a lot of time until I found it out.
So: An underscore is not to be confused with a border-bottom.
I also had this problem and it's solved as change line from res/values/styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
to
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
both solutions worked
You have to create a variable of the type of the class, and set it equal to a new instance of the object first.
GradeBook myGradeBook = new GradeBook();
Then call the method on the obect you just created.
myGradeBook.[method you want called]
ADB Build-Tools Will Not be downloaded automatically, by command android update sdk --no-ui
So for installing Buil-Tool type (in console):
android list sdk --all
Remember the number that is listed before the item and execute the following:
android update sdk -u --all --filter <number>
commands should be typed in /YourFolder/android-sdk-linux/tools
Also for remote folder (server opened by ssh for example) type:
**./android** list sdk --all
**./android** update sdk -u --all --filter <number>
For simple list of ADB packages type in terminal:
android list sdk
for install all packages:
android update sdk --no-ui
Or with filters (comma is separator):
android update sdk --no-ui --filter 3,5,8,14
I'm not experienced about python, so if there is any wrong in my words, just tell me. If your file hierarchy arranged like this:
project\
module_1.py
module_2.py
module_1.py
defines a function called func_1()
, module_2.py:
from module_1 import func_1
def func_2():
func_1()
if __name__ == '__main__':
func_2()
and you run python module_2.py
in cmd, it will do run what func_1()
defines. That's usually how we import same hierarchy files. But when you write from .module_1 import func_1
in module_2.py
, python interpreter will say No module named '__main__.module_1'; '__main__' is not a package
. So to fix this, we just keep the change we just make, and move both of the module to a package, and make a third module as a caller to run module_2.py
.
project\
package_1\
module_1.py
module_2.py
main.py
main.py:
from package_1.module_2 import func_2
def func_3():
func_2()
if __name__ == '__main__':
func_3()
But the reason we add a .
before module_1
in module_2.py
is that if we don't do that and run main.py
, python interpreter will say No module named 'module_1'
, that's a little tricky, module_1.py
is right beside module_2.py
. Now I let func_1()
in module_1.py
do something:
def func_1():
print(__name__)
that __name__
records who calls func_1. Now we keep the .
before module_1
, run main.py
, it will print package_1.module_1
, not module_1
. It indicates that the one who calls func_1()
is at the same hierarchy as main.py
, the .
imply that module_1
is at the same hierarchy as module_2.py
itself. So if there isn't a dot, main.py
will recognize module_1
at the same hierarchy as itself, it can recognize package_1
, but not what "under" it.
Now let's make it a bit complicated. You have a config.ini
and a module defines a function to read it at the same hierarchy as 'main.py'.
project\
package_1\
module_1.py
module_2.py
config.py
config.ini
main.py
And for some unavoidable reason, you have to call it with module_2.py
, so it has to import from upper hierarchy.module_2.py:
import ..config
pass
Two dots means import from upper hierarchy (three dots access upper than upper,and so on). Now we run main.py
, the interpreter will say:ValueError:attempted relative import beyond top-level package
. The "top-level package" at here is main.py
. Just because config.py
is beside main.py
, they are at same hierarchy, config.py
isn't "under" main.py
, or it isn't "leaded" by main.py
, so it is beyond main.py
. To fix this, the simplest way is:
project\
package_1\
module_1.py
module_2.py
config.py
config.ini
main.py
I think that is coincide with the principle of arrange project file hierarchy, you should arrange modules with different function in different folders, and just leave a top caller in the outside, and you can import how ever you want.
Using this code to multiple order by in single query.
$this->db->from($this->table_name);
$this->db->order_by("column1 asc,column2 desc");
$query = $this->db->get();
return $query->result();
The length function will do it. See http://www.techonthenet.com/oracle/functions/length.php
I was facing a similar issue, I had a file on my project, and wanted to test a class which had to deal with loading files from the FS and process them some way. What I did was:
test.txt
to my test projectalt-enter
(file properties)BuildAction
to Content
and Copy to Output Directory
to Copy if newer
, I guess Copy always
would have done it as wellthen on my tests I just had to Path.Combine(Environment.CurrentDirectory, "test.txt")
and that's it. Whenever the project is compiled it will copy the file (and all it's parent path, in case it was in, say, a folder) to the bin\Debug
(or whatever configuration you are using) folder.
Hopes this helps someone
True is only valid if you're using the .NET SqlClient library. It isn't valid when using OLEDB. Where SSPI is bvaid in both either you are using .net SqlClient library or OLEDB.
Basically, if you are not handling the exception in the same place as you are throwing it, then you can use "throws exception" at the definition of the function.
You can annotate your bean with jaxb annotations.
@XmlRootElement
public class MyJaxbBean {
public String name;
public int age;
public MyJaxbBean() {} // JAXB needs this
public MyJaxbBean(String name, int age) {
this.name = name;
this.age = age;
}
}
and then your method would look like this:
@GET @Produces("application/json")
public MyJaxbBean getMyBean() {
return new MyJaxbBean("Agamemnon", 32);
}
There is a chapter in the latest documentation that deals with this:
https://jersey.java.net/documentation/latest/user-guide.html#json
Many thanks for bernie's answer! Had to tweak it a bit - here's what worked for me:
import csv, sqlite3
conn = sqlite3.connect("pcfc.sl3")
curs = conn.cursor()
curs.execute("CREATE TABLE PCFC (id INTEGER PRIMARY KEY, type INTEGER, term TEXT, definition TEXT);")
reader = csv.reader(open('PC.txt', 'r'), delimiter='|')
for row in reader:
to_db = [unicode(row[0], "utf8"), unicode(row[1], "utf8"), unicode(row[2], "utf8")]
curs.execute("INSERT INTO PCFC (type, term, definition) VALUES (?, ?, ?);", to_db)
conn.commit()
My text file (PC.txt) looks like this:
1 | Term 1 | Definition 1
2 | Term 2 | Definition 2
3 | Term 3 | Definition 3
Would it be possible to leave the ability to right click and download just when done a separate watermark is placed on the image. Of course this won't prevent screen shots but thought it may be a good middle ground.
<form onsubmit="return false;" id="myForm">
</form>
$('#myForm').submit(function() {
doSomething();
});
If you are having a small script that you need to run (I simply needed to copy a file), I found it much easier to call the commands on the PHP script by calling
exec("sudo cp /tmp/testfile1 /var/www/html/testfile2");
and enabling such transaction by editing (or rather adding) a permitting line to the sudoers by first calling sudo visudo
and adding the following line to the very end of it
www-data ALL=(ALL) NOPASSWD:/bin/cp /tmp/testfile1 /var/www/html/testfile2
All I wanted to do was to copy a file and I have been having problems with doing so because of the root password problem, and as you mentioned I did NOT want to expose the system to have no password for all root transactions.
MSBuild in an independent build tool that is frequently bundled with other tools. It may have been installed on your computer with .NET (older versions), Visual Studio (newer versions), or even Team Foundation Build.
MSBuild needs configuration files, compilers, etc (a ToolSet) that matches the version of Visual Studio or TFS that will use it, as well as the version of .NET against which source code will be compiled.
Depending on how MSBuild was installed, the configuration files may be in one or more of these paths.
As described in other answers, a registry item and/or environmental variable point must to the ToolSet path.
Occasionally, an operation like installing a tool will leave the registry and/or environmental variable set incorrectly. The other answers are all variations on fixing them.
The only thing I have to add is the environmental variable didn't work for me when I left off the trailing \
Unfortunately, none of the previous answers were good for my case: different key objects may have the same hash code. Therefore, I wrote a simple Java-like HashMap version:
function HashMap() {
this.buckets = {};
}
HashMap.prototype.put = function(key, value) {
var hashCode = key.hashCode();
var bucket = this.buckets[hashCode];
if (!bucket) {
bucket = new Array();
this.buckets[hashCode] = bucket;
}
for (var i = 0; i < bucket.length; ++i) {
if (bucket[i].key.equals(key)) {
bucket[i].value = value;
return;
}
}
bucket.push({ key: key, value: value });
}
HashMap.prototype.get = function(key) {
var hashCode = key.hashCode();
var bucket = this.buckets[hashCode];
if (!bucket) {
return null;
}
for (var i = 0; i < bucket.length; ++i) {
if (bucket[i].key.equals(key)) {
return bucket[i].value;
}
}
}
HashMap.prototype.keys = function() {
var keys = new Array();
for (var hashKey in this.buckets) {
var bucket = this.buckets[hashKey];
for (var i = 0; i < bucket.length; ++i) {
keys.push(bucket[i].key);
}
}
return keys;
}
HashMap.prototype.values = function() {
var values = new Array();
for (var hashKey in this.buckets) {
var bucket = this.buckets[hashKey];
for (var i = 0; i < bucket.length; ++i) {
values.push(bucket[i].value);
}
}
return values;
}
Note: key objects must "implement" the hashCode() and equals() methods.
The InvalidCastException you are getting is due to SCOPE_IDENTITY being a Decimal(38,0).
You can return it as an int by casting it as follows:
string sql = @"
INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
SELECT CAST(SCOPE_IDENTITY() AS INT)";
int id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();
If you don't have DBA rights then you can use user_segments table:
select bytes/1024/1024 MB from user_segments where segment_name='Table_name'
Process Explorer can show total CPU time taken by a process, as well as a history graph per process.
Append a \r\n
to the string to put the text on a new line.
textBox1.Text += ("brown\r\n");
textBox1.Text += ("brwn");
This will produce the two entries on separate lines.
According to the RFC that introduced the operator, $a <=> $b
evaluates to:
$a == $b
$a < $b
$a > $b
which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b
will return
an integer less than, equal to, or greater than zero when
$a
is respectively less than, equal to, or greater than$b
Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort
(and the similar uasort
and uksort
).
usort
takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:
an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
The spaceship operator makes this succinct and convenient:
$things = [
[
'foo' => 5.5,
'bar' => 'abc'
],
[
'foo' => 7.7,
'bar' => 'xyz'
],
[
'foo' => 2.2,
'bar' => 'efg'
]
];
// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
return $a['foo'] <=> $b['foo'];
});
// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
return $b['bar'] <=> $a['bar'];
});
More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.
Here is a better and elegant solution for your problem statement.
int mynumbercheck = 1000;
// Your number to be checked
var myswitch = new Dictionary <Func<int,bool>, Action>
{
{ x => x < 10 , () => //Do this!... },
{ x => x < 100 , () => //Do this!... },
{ x => x < 1000 , () => //Do this!... },
{ x => x < 10000 , () => //Do this!... } ,
{ x => x < 100000 , () => //Do this!... },
{ x => x < 1000000 , () => //Do this!... }
};
Now to call our conditional switch
myswitch.First(sw => sw.Key(mynumbercheck)).Value();
I recommend to use Pretty Printer Library. In that you can print any struct very easily.
Install Library
or
go get github.com/kr/pretty
Now do like this in your code
package main
import (
fmt
github.com/kr/pretty
)
func main(){
type Project struct {
Id int64 `json:"project_id"`
Title string `json:"title"`
Name string `json:"name"`
Data Data `json:"data"`
Commits Commits `json:"commits"`
}
fmt.Printf("%# v", pretty.Formatter(Project)) //It will print all struct details
fmt.Printf("%# v", pretty.Formatter(Project.Id)) //It will print component one by one.
}
Also you can get difference between component through this library and so more. You can also have a look on library Docs here.
You can use a redirect to that action :
redirect_to your_controller_action_url
More on : Rails Guide
To just render the new action :
redirect_to your_controller_action_url and return
Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"
As I could understand the question is not about how pass a string with control symbols using json
but how to store and restore json in file where you can split a string with editor control symbols.
If you want to store multiline string in a file then your file will not store the valid json
object. But if you use your json
files in your program only, then you can store the data as you wanted and remove all newlines from file manually each time you load it to your program and then pass to json parser.
Or, alternatively, which would be better, you can have your json
data source files where you edit a sting as you want and then remove all new lines with some utility to the valid json
file which your program will use.
You need to use the various Bootstrap 4 centering methods...
text-center
for inline elements.justify-content-center
for flexbox elements (ie; form-inline
)https://codeply.com/go/Am5LvvjTxC
Also, to offset the column, the col-sm-*
must be contained within a .row
, and the .row
must be in a container...
<section id="cover">
<div id="cover-caption">
<div id="container" class="container">
<div class="row">
<div class="col-sm-10 offset-sm-1 text-center">
<h1 class="display-3">Welcome to Bootstrap 4</h1>
<div class="info-form">
<form action="" class="form-inline justify-content-center">
<div class="form-group">
<label class="sr-only">Name</label>
<input type="text" class="form-control" placeholder="Jane Doe">
</div>
<div class="form-group">
<label class="sr-only">Email</label>
<input type="text" class="form-control" placeholder="[email protected]">
</div>
<button type="submit" class="btn btn-success ">okay, go!</button>
</form>
</div>
<br>
<a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
</div>
</div>
</div>
</div>
</section>
You can try "request.get_full_path()"
Once after we build the jar will have the resource files under BOOT-INF/classes or target/classes folder, which is in classpath, use the below method and pass the file under the src/main/resources as method call getAbsolutePath("certs/uat_staging_private.ppk"), even we can place this method in Utility class and the calling Thread instance will be taken to load the ClassLoader to get the resource from class path.
public String getAbsolutePath(String fileName) throws IOException {
return Thread.currentThread().getContextClassLoader().getResource(fileName).getFile();
}
we can add the below tag to tag in pom.xml to include these resource files to build target/classes folder
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.ppk</include>
</includes>
</resource>
</resources>
For this case you could use interfaces from default library (java 1.8):
java.util.function.BiConsumer
java.util.function.BiFunction
There is a small (not the best) example of default method in interface:
default BiFunction<File, String, String> getFolderFileReader() {
return (directory, fileName) -> {
try {
return FileUtils.readFile(directory, fileName);
} catch (IOException e) {
LOG.error("Unable to read file {} in {}.", fileName, directory.getAbsolutePath(), e);
}
return "";
};
}}
ALTER TABLE your_table
ADD PRIMARY KEY (Drugid);
It will order first, then get the first 20. A database will also process anything in the WHERE
clause before ORDER BY
.
Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")
Or, in a more structured way...
Sub openwb()
Dim sPath As String, sFile As String
Dim wb As Workbook
sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"
Set wb = Workbooks.Open(sFile)
End Sub
The safest way to do it is to fully specify the columns both for insertion and extraction. There's no guarantee (to the application) that either of these will be the order you think they may be.
insert into dues_storage (f1, f2, f3, cd)
select f1, f2, f3, current_date() from dues where id = 5;
If you're worried about having to change many multiple PHP pages that do this (as you seem to indicate in the comment to another answer), this is ripe for a stored procedure. That way, all your PHP pages simply call the stored procedure with (for example) just the ID to copy and it controls the actual copy process. That way, there's only one place where you need to maintain the code, and, in my opinion, the DBMS is the right place to do it.
server {
server_name xyz.com;
root /home/ubuntu/project_folder/;
client_max_body_size 10M;
access_log /var/log/nginx/project.access.log;
error_log /var/log/nginx/project.error.log;
location /static {
index index.html;
}
location /media {
alias /home/ubuntu/project/media/;
}
}
Server block to live the static page on nginx.
Resurrecting another topic, but this may come in handy for some.
With a little bit of inspiration from https://pyformat.info you can build a method to get a Table of Content [TOC] style printout.
# Define parameters
Location = '10-10-10-10'
Revision = 1
District = 'Tower'
MyDate = 'May 16, 2012'
MyUser = 'LOD'
MyTime = '10:15'
# This is just one way to arrange the data
data = [
['Location: '+Location, 'Revision:'+str(Revision)],
['District: '+District, 'Date: '+MyDate],
['User: '+MyUser,'Time: '+MyTime]
]
# The 'Table of Content' [TOC] style print function
def print_table_line(key,val,space_char,val_loc):
# key: This would be the TOC item equivalent
# val: This would be the TOC page number equivalent
# space_char: This is the spacing character between key and val (often a dot for a TOC), must be >= 5
# val_loc: This is the location in the string where the first character of val would be located
val_loc = max(5,val_loc)
if (val_loc <= len(key)):
# if val_loc is within the space of key, truncate key and
cut_str = '{:.'+str(val_loc-4)+'}'
key = cut_str.format(key)+'...'+space_char
space_str = '{:'+space_char+'>'+str(val_loc-len(key)+len(str(val)))+'}'
print(key+space_str.format(str(val)))
# Examples
for d in data:
print_table_line(d[0],d[1],' ',30)
print('\n')
for d in data:
print_table_line(d[0],d[1],'_',25)
print('\n')
for d in data:
print_table_line(d[0],d[1],' ',20)
The resulting output is as follows:
Location: 10-10-10-10 Revision:1
District: Tower Date: May 16, 2012
User: LOD Time: 10:15
Location: 10-10-10-10____Revision:1
District: Tower__________Date: May 16, 2012
User: LOD________________Time: 10:15
Location: 10-10-... Revision:1
District: Tower Date: May 16, 2012
User: LOD Time: 10:15
Use eval:
x="ls | wc"
eval "$x"
y=$(eval "$x")
echo "$y"
There's actually quite a bit of useful information added to debug allocations. This table is more complete:
http://www.nobugs.org/developer/win32/debug_crt_heap.html#table
Address Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments 0x00320FD8 -40 0x01090009 0x01090009 0x01090009 0x0109005A Win32 heap info 0x00320FDC -36 0x01090009 0x00180700 0x01090009 0x00180400 Win32 heap info 0x00320FE0 -32 0xBAADF00D 0x00320798 0xDDDDDDDD 0x00320448 Ptr to next CRT heap block (allocated earlier in time) 0x00320FE4 -28 0xBAADF00D 0x00000000 0xDDDDDDDD 0x00320448 Ptr to prev CRT heap block (allocated later in time) 0x00320FE8 -24 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Filename of malloc() call 0x00320FEC -20 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Line number of malloc() call 0x00320FF0 -16 0xBAADF00D 0x00000008 0xDDDDDDDD 0xFEEEFEEE Number of bytes to malloc() 0x00320FF4 -12 0xBAADF00D 0x00000001 0xDDDDDDDD 0xFEEEFEEE Type (0=Freed, 1=Normal, 2=CRT use, etc) 0x00320FF8 -8 0xBAADF00D 0x00000031 0xDDDDDDDD 0xFEEEFEEE Request #, increases from 0 0x00320FFC -4 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x00321000 +0 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321004 +4 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321008 +8 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x0032100C +12 0xBAADF00D 0xBAADF00D 0xDDDDDDDD 0xFEEEFEEE Win32 heap allocations are rounded up to 16 bytes 0x00321010 +16 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321014 +20 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321018 +24 0x00000010 0x00000010 0x00000010 0xFEEEFEEE Win32 heap bookkeeping 0x0032101C +28 0x00000000 0x00000000 0x00000000 0xFEEEFEEE Win32 heap bookkeeping 0x00321020 +32 0x00090051 0x00090051 0x00090051 0xFEEEFEEE Win32 heap bookkeeping 0x00321024 +36 0xFEEE0400 0xFEEE0400 0xFEEE0400 0xFEEEFEEE Win32 heap bookkeeping 0x00321028 +40 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping 0x0032102C +44 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping
Primitive data type
The primitive data type is a basic type provided by a programming language as a basic building block. So it's predefined data types. A primitive type has always a value. It storing simple value.
It specifies the size and type of variable values, so the size of a primitive type depends on the data type and it has no additional methods.
And these are reserved keywords in the language. So we can't use these names as variable, class or method name. A primitive type starts with a lowercase letter. When declaring the primitive types we don't need to allocate memory. (memory is allocated and released by JRE-Java Runtime Environment in Java)
+================+=========+===================================================================================+
| Primitive type | Size | Description |
+================+=========+===================================================================================+
| byte | 1 byte | Stores whole numbers from -128 to 127 |
+----------------+---------+-----------------------------------------------------------------------------------+
| short | 2 bytes | Stores whole numbers from -32,768 to 32,767 |
+----------------+---------+-----------------------------------------------------------------------------------+
| int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
+----------------+---------+-----------------------------------------------------------------------------------+
| long | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
+----------------+---------+-----------------------------------------------------------------------------------+
| float | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits |
+----------------+---------+-----------------------------------------------------------------------------------+
| double | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits |
+----------------+---------+-----------------------------------------------------------------------------------+
| char | 2 bytes | Stores a single character/letter or ASCII values |
+----------------+---------+-----------------------------------------------------------------------------------+
| boolean | 1 bit | Stores true or false values |
+----------------+---------+-----------------------------------------------------------------------------------+
Reference data type
Reference data type refers to objects. Most of these types are not defined by programming language(except for String, arrays in JAVA). Reference types of value can be null. It storing an address of the object it refers to. Reference or non-primitive data types have all the same size. and reference types can be used to call methods to perform certain operations.
when declaring the reference type need to allocate memory. In Java, we used new
keyword to allocate memory, or alternatively, call a factory method.
Example:
List< String > strings = new ArrayList<>() ; // Calling `new` to instantiate an object and thereby allocate memory.
Point point = Point(1,2) ; // Calling a factory method.
$parent doesn't work if there are multiple parents. instead of that we can define a parent index variable in init and use it
<div data-ng-init="parentIndex = $index" ng-repeat="f in foos">
<div>
<div data-ng-init="childIndex = $index" ng-repeat="b in foos.bars">
<a ng-click="addSomething(parentIndex)">Add Something</a>
</div>
</div>
</div>
You can use JPQL as well as JPA Criteria API for any kind of DTO projection(Mapping only selected columns to a DTO class) . Look at below code snippets showing how to selectively select various columns instead of selecting all columns . These example also show how to select various columns from joining multiple columns . I hope this helps .
JPQL code :
String dtoProjection = "new com.katariasoft.technologies.jpaHibernate.college.data.dto.InstructorDto"
+ "(i.id, i.name, i.fatherName, i.address, id.proofNo, "
+ " v.vehicleNumber, v.vechicleType, s.name, s.fatherName, "
+ " si.name, sv.vehicleNumber , svd.name) ";
List<InstructorDto> instructors = queryExecutor.fetchListForJpqlQuery(
"select " + dtoProjection + " from Instructor i " + " join i.idProof id " + " join i.vehicles v "
+ " join i.students s " + " join s.instructors si " + " join s.vehicles sv "
+ " join sv.documents svd " + " where i.id > :id and svd.name in (:names) "
+ " order by i.id , id.proofNo , v.vehicleNumber , si.name , sv.vehicleNumber , svd.name ",
CollectionUtils.mapOf("id", 2, "names", Arrays.asList("1", "2")), InstructorDto.class);
if (Objects.nonNull(instructors))
instructors.forEach(i -> i.setName("Latest Update"));
DataPrinters.listDataPrinter.accept(instructors);
JPA Criteria API code :
@Test
public void fetchFullDataWithCriteria() {
CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
CriteriaQuery<InstructorDto> cq = cb.createQuery(InstructorDto.class);
// prepare from expressions
Root<Instructor> root = cq.from(Instructor.class);
Join<Instructor, IdProof> insIdProofJoin = root.join(Instructor_.idProof);
Join<Instructor, Vehicle> insVehicleJoin = root.join(Instructor_.vehicles);
Join<Instructor, Student> insStudentJoin = root.join(Instructor_.students);
Join<Student, Instructor> studentInsJoin = insStudentJoin.join(Student_.instructors);
Join<Student, Vehicle> studentVehicleJoin = insStudentJoin.join(Student_.vehicles);
Join<Vehicle, Document> vehicleDocumentJoin = studentVehicleJoin.join(Vehicle_.documents);
// prepare select expressions.
CompoundSelection<InstructorDto> selection = cb.construct(InstructorDto.class, root.get(Instructor_.id),
root.get(Instructor_.name), root.get(Instructor_.fatherName), root.get(Instructor_.address),
insIdProofJoin.get(IdProof_.proofNo), insVehicleJoin.get(Vehicle_.vehicleNumber),
insVehicleJoin.get(Vehicle_.vechicleType), insStudentJoin.get(Student_.name),
insStudentJoin.get(Student_.fatherName), studentInsJoin.get(Instructor_.name),
studentVehicleJoin.get(Vehicle_.vehicleNumber), vehicleDocumentJoin.get(Document_.name));
// prepare where expressions.
Predicate instructorIdGreaterThan = cb.greaterThan(root.get(Instructor_.id), 2);
Predicate documentNameIn = cb.in(vehicleDocumentJoin.get(Document_.name)).value("1").value("2");
Predicate where = cb.and(instructorIdGreaterThan, documentNameIn);
// prepare orderBy expressions.
List<Order> orderBy = Arrays.asList(cb.asc(root.get(Instructor_.id)),
cb.asc(insIdProofJoin.get(IdProof_.proofNo)), cb.asc(insVehicleJoin.get(Vehicle_.vehicleNumber)),
cb.asc(studentInsJoin.get(Instructor_.name)), cb.asc(studentVehicleJoin.get(Vehicle_.vehicleNumber)),
cb.asc(vehicleDocumentJoin.get(Document_.name)));
// prepare query
cq.select(selection).where(where).orderBy(orderBy);
DataPrinters.listDataPrinter.accept(queryExecutor.fetchListForCriteriaQuery(cq));
}