NSMutableParagraphStyle *paragraphStyle = NSMutableParagraphStyle.new;
paragraphStyle.alignment = NSTextAlignmentCenter;
NSAttributedString *attributedString =
[NSAttributedString.alloc initWithString:@"someText"
attributes:
@{NSParagraphStyleAttributeName:paragraphStyle}];
Swift 4.2
let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center
let attributedString = NSAttributedString(string: "someText", attributes: [NSAttributedString.Key.paragraphStyle : paragraphStyle])
Using of NSHTMLTextDocumentType is slow and it is hard to control styles. I suggest you to try my library which is called Atributika. It has its own very fast HTML parser. Also you can have any tag names and define any style for them.
Example:
let str = "<strong>Hello</strong> World!".style(tags:
Style("strong").font(.boldSystemFont(ofSize: 15))).attributedString
label.attributedText = str
You can find it here https://github.com/psharanda/Atributika
As of September 2016 (according to the GitHub repository documentation of the extension) you can just execute a command from within Visual Studio Code that will let you select the interpreter from an automatically generated list of known interpreters (including the one in your project's virtual environment).
How can I use this feature?
- Select the command
Python: Select Workspace Interpreter
(*) from the command palette (F1).
- Upon selecting the above command a list of discovered interpreters will be displayed in a
quick pick
list.
- Selecting an interpreter from this list will update the settings.json file automatically.
(*) This command has been updated to Python: Select Interpreter
in the latest release of Visual Studio Code (thanks @nngeek).
Also, notice that your selected interpreter will be shown at the left side of the statusbar, e.g., Python 3.6 64-bit. This is a button you can click to trigger the Select Interpreter feature.
You can use Hudson Groovy builder to do this.
First Job in pipeline
Second job in pipeline
Still missing this simple version:
SELECT * FROM myTable WHERE `col1` + 0 = `col1`
(addition should be faster as multiplication)
Or slowest version for further playing:
SELECT *,
CASE WHEN `col1` + 0 = `col1` THEN 1 ELSE 0 END AS `IS_NUMERIC`
FROM `myTable`
HAVING `IS_NUMERIC` = 1
I disagree with the popular answer, that having public implies that there are other options and so it shouldn't be there. The fact is that now with Java 9 and beyond there ARE other options.
I think instead Java should enforce/require 'public' to be specified. Why? Because the absence of a modifier means 'package' access everywhere else, and having this as a special case is what leads to the confusion. If you simply made it a compile error with a clear message (e.g. "Package access is not allowed in an interface.") we would get rid of the apparent ambiguity that having the option to leave out 'public' introduces.
Note the current wording at: https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4
"A method in the body of an interface may be declared public or private (§6.6). If no access modifier is given, the method is implicitly public. It is permitted, but discouraged as a matter of style, to redundantly specify the public modifier for a method declaration in an interface."
See that 'private' IS allowed now. I think that last sentence should have been removed from the JLS. It is unfortunate that the "implicitly public" behaviour was ever allowed as it will now likely remain for backward compatibilty and lead to the confusion that the absence of the access modifier means 'public' in interfaces and 'package' elsewhere.
I've completed the code that @Berezh has shared.
public class TreeNode<T> : IEnumerable<TreeNode<T>>
{
public T Data { get; set; }
public TreeNode<T> Parent { get; set; }
public ICollection<TreeNode<T>> Children { get; set; }
public TreeNode(T data)
{
this.Data = data;
this.Children = new LinkedList<TreeNode<T>>();
}
public TreeNode<T> AddChild(T child)
{
TreeNode<T> childNode = new TreeNode<T>(child) { Parent = this };
this.Children.Add(childNode);
return childNode;
}
public IEnumerator<TreeNode<T>> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}
}
public class TreeNodeEnum<T> : IEnumerator<TreeNode<T>>
{
int position = -1;
public List<TreeNode<T>> Nodes { get; set; }
public TreeNode<T> Current
{
get
{
try
{
return Nodes[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public TreeNodeEnum(List<TreeNode<T>> nodes)
{
Nodes = nodes;
}
public void Dispose()
{
}
public bool MoveNext()
{
position++;
return (position < Nodes.Count);
}
public void Reset()
{
position = -1;
}
}
Based on my tests (Win7 64bit, 6GB RAM, Java6), NIO transferFrom is fast only with small files and becomes very slow on larger files. NIO databuffer flip always outperforms standard IO.
Copying 1000x2MB
Copying 100x20mb
Copying 1x1000mb
The transferTo() method works on chunks of a file; wasn't intended as a high-level file copy method: How to copy a large file in Windows XP?
Depending on the size and number of files being copied, you could copy the destination directory over the source first with "yes to all", then do the original copy you were doing, also with "yes to all" set. That should give you the same results.
Instead of CharSet.forName, using com.google.common.base.Charsets from Google's Guava (http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets) is is slightly nicer:
InputStream is = new ByteArrayInputStream( myString.getBytes(Charsets.UTF_8) );
Which CharSet you use depends entirely on what you're going to do with the InputStream, of course.
try {
var data = {foo: "bar"};
res.json(JSON.stringify(data));
}
catch (e) {
res.status(500).json(JSON.stringify(e));
}
A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:
So we need three divs:
First let us define the CSS:
#hider
{
position:absolute;
top: 0%;
left: 0%;
width:1600px;
height:2000px;
margin-top: -800px; /*set to a negative number 1/2 of your height*/
margin-left: -500px; /*set to a negative number 1/2 of your width*/
/*
z- index must be lower than pop up box
*/
z-index: 99;
background-color:Black;
//for transparency
opacity:0.6;
}
#popup_box
{
position:absolute;
top: 50%;
left: 50%;
width:10em;
height:10em;
margin-top: -5em; /*set to a negative number 1/2 of your height*/
margin-left: -5em; /*set to a negative number 1/2 of your width*/
border: 1px solid #ccc;
border: 2px solid black;
z-index:100;
}
It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
Here comes the java Script:
$(document).ready(function () {
//hide hider and popup_box
$("#hider").hide();
$("#popup_box").hide();
//on click show the hider div and the message
$("#showpopup").click(function () {
$("#hider").fadeIn("slow");
$('#popup_box').fadeIn("slow");
});
//on click hide the message and the
$("#buttonClose").click(function () {
$("#hider").fadeOut("slow");
$('#popup_box').fadeOut("slow");
});
});
And finally the HTML:
<div id="hider"></div>
<div id="popup_box">
Message<br />
<a id="buttonClose">Close</a>
</div>
<div id="content">
Page's main content.<br />
<a id="showpopup">ClickMe</a>
</div>
I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.
Also had this problem occurring on the web application surface. Eventually found out that the same error message comes from the SQL update statement in the specific table.
Finally then figured out that the column definition in the relating history table(s) did not map the original table column length of nvarchar
types in some specific cases.
here's how:
import pygame
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=90
height=90
filled=0
pygame.draw.rect(screen, [red, blue, green], [left, top, width, height], filled)
pygame.display.flip()
running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
pygame.quit()
To get better results and robustness against differents types of matrices, you can do this in addition to the first answer, that copy the data :
cv::Mat source = getYourSource();
// Setup a rectangle to define your region of interest
cv::Rect myROI(10, 10, 100, 100);
// Crop the full image to that image contained by the rectangle myROI
// Note that this doesn't copy the data
cv::Mat croppedRef(source, myROI);
cv::Mat cropped;
// Copy the data into new matrix
croppedRef.copyTo(cropped);
You separate the values you want to return by commas:
def get_name():
# you code
return first_name, last_name
The commas indicate it's a tuple, so you could wrap your values by parentheses:
return (first_name, last_name)
Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas
name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly
The following should work nicely.
$(function() {
// Way 1
function doosomething()
{
//Doo something
}
// Way 2, equivalent to Way 1
var doosomething = function() {
// Doo something
}
$("div.class").click(doosomething);
$("div.secondclass").click(doosomething);
});
Basically, you are declaring your function in the same scope as your are using it (JavaScript uses Closures to determine scope).
Now, since functions in JavaScript behave like any other object, you can simply assign doosomething
as the function to call on click by using .click(doosomething);
Your function will not execute until you call it using doosomething()
(doosomething
without the ()
refers to the function but doesn't call it) or another function calls in (in this case, the click
handler).
Here's a function that doesn't require any packages to be installed. You give it a Date
object (or a character
that it can convert into a Date
), and it adds n
months to that date without changing the day of the month (unless the month you land on doesn't have enough days in it, in which case it defaults to the last day of the returned month). Just in case it doesn't make sense reading it, there are some examples below.
addMonth <- function(date, n = 1){
if (n == 0){return(date)}
if (n %% 1 != 0){stop("Input Error: argument 'n' must be an integer.")}
# Check to make sure we have a standard Date format
if (class(date) == "character"){date = as.Date(date)}
# Turn the year, month, and day into numbers so we can play with them
y = as.numeric(substr(as.character(date),1,4))
m = as.numeric(substr(as.character(date),6,7))
d = as.numeric(substr(as.character(date),9,10))
# Run through the computation
i = 0
# Adding months
if (n > 0){
while (i < n){
m = m + 1
if (m == 13){
m = 1
y = y + 1
}
i = i + 1
}
}
# Subtracting months
else if (n < 0){
while (i > n){
m = m - 1
if (m == 0){
m = 12
y = y - 1
}
i = i - 1
}
}
# If past 28th day in base month, make adjustments for February
if (d > 28 & m == 2){
# If it's a leap year, return the 29th day
if ((y %% 4 == 0 & y %% 100 != 0) | y %% 400 == 0){d = 29}
# Otherwise, return the 28th day
else{d = 28}
}
# If 31st day in base month but only 30 days in end month, return 30th day
else if (d == 31){if (m %in% c(1, 3, 5, 7, 8, 10, 12) == FALSE){d = 30}}
# Turn year, month, and day into strings and put them together to make a Date
y = as.character(y)
# If month is single digit, add a leading 0, otherwise leave it alone
if (m < 10){m = paste('0', as.character(m), sep = '')}
else{m = as.character(m)}
# If day is single digit, add a leading 0, otherwise leave it alone
if (d < 10){d = paste('0', as.character(d), sep = '')}
else{d = as.character(d)}
# Put them together and convert return the result as a Date
return(as.Date(paste(y,'-',m,'-',d, sep = '')))
}
> addMonth('2014-01-31', n = 1)
[1] "2014-02-28" # February, non-leap year
> addMonth('2014-01-31', n = 5)
[1] "2014-06-30" # June only has 30 days, so day of month dropped to 30
> addMonth('2014-01-31', n = 24)
[1] "2016-01-31" # Increments years when n is a multiple of 12
> addMonth('2014-01-31', n = 25)
[1] "2016-02-29" # February, leap year
> addMonth('2014-01-31', n = -1)
[1] "2013-12-31"
> addMonth('2014-01-31', n = -7)
[1] "2013-06-30"
> addMonth('2014-01-31', n = -12)
[1] "2013-01-31"
> addMonth('2014-01-31', n = -23)
[1] "2012-02-29"
// set
$_SESSION['test'] = 1;
// destroy
unset($_SESSION['test']);
As you surmise, it is to do with the connection string being in app.config of the class library.
Copy the entry from the class app.config to the container's app.config
or web.config
file
as in javascript:
mydata.match(/'([^']+)'/)[1]
the actual regexp is: /'([^']+)'/
if you use the non greedy modifier (as per another post) it's like this:
mydata.match(/'(.*?)'/)[1]
it is cleaner.
In .NET 5.0 and later you can use the Convert.ToHexString()
method.
using System;
using System.Text;
string value = "Hello world";
byte[] bytes = Encoding.UTF8.GetBytes(value);
string hexString = Convert.ToHexString(bytes);
Console.WriteLine($"String value: \"{value}\"");
Console.WriteLine($" Hex value: \"{hexString}\"");
Running the above example code, you would get the following output:
String value: "Hello world"
Hex value: "48656C6C6F20776F726C64"
The heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects.
Eden Space: The pool from which memory is initially allocated for most objects.
Survivor Space: The pool containing objects that have survived the garbage collection of the Eden space.
Tenured Generation or Old Gen: The pool containing objects that have existed for some time in the survivor space.
Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous.
Permanent Generation: The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
Code Cache: The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.
javac (.exe on Windows) binary path must be added into global PATH env. variable.
javac MyProgram.java
or with java (.exe on Windows)
java MyProgram.jar
There are two examples illustrates difference
int a , b , c = 0 ;
a = ++c ;
b = c++ ;
printf (" %d %d %d " , a , b , c++);
a = 1
and value of c = 1
next statement assiagn value of c = 1
to b then increment c by 1 so
value of b = 1
and value of c = 2
in printf
statement we have c++
this mean that orginal value of c
which is 2 will printed then increment c by 1 so printf
statement
will print 1 1 2
and value of c now is 3
you can use http://pythontutor.com/c.html
int a , b , c = 0 ;
a = ++c ;
b = c++ ;
printf (" %d %d %d " , a , b , ++c);
printf
statement ++c
will increment value of c by 1 first then
assign new value 3 to c so printf
statement will print 1 1 3
You can use the slice method:
a = "foobar"
a.slice! "foo"
=> "foo"
a
=> "bar"
there is a non '!' version as well. More info can be seen in the documentation about other versions as well: http://www.ruby-doc.org/core/classes/String.html#method-i-slice-21
An excerpt from an apple technical note (Thanks to matthias-bauch)
Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.
If your tools were downloaded separately from Xcode, then they are located at
/Library/Developer/CommandLineTools
on your system. Delete the CommandLineTools folder to uninstall them.
you could easily delete using terminal:
Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.
The other answers didn't work for me. I found the answer in their documentation:
http://api.highcharts.com/highcharts#Series
Using this method (see JSFiddle example):
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
// the button action
$('#button').click(function() {
chart.series[0].setData([129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4] );
});
U can try java.util.Date
library like this way-
int no_of_day_to_add = 1;
Date today = new Date();
Date tomorrow = new Date( today.getYear(), today.getMonth(), today.getDate() + no_of_day_to_add );
Change value of no_of_day_to_add
as you want.
I have set value of no_of_day_to_add
to 1
because u wanted only one day to add.
More can be found in this documentation.
The FormClosed Event is an Event that fires when the form closes. It is not used to actually close the form. You'll need to remove anything you've added there.
All you should have to do is add the following line to your button's event handler:
this.Close();
# Hide grid lines
ax.grid(False)
# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
Note, you need matplotlib>=1.2 for set_zticks()
to work.
this is my alternative solution, instead of a List of Map, i'm using a Map of List. Tested on tables of 5000 elements, on a remote db, times are around 350ms for eiter method.
private Map<String, List<Object>> resultSetToArrayList(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
Map<String, List<Object>> map = new HashMap<>(columns);
for (int i = 1; i <= columns; ++i) {
map.put(md.getColumnName(i), new ArrayList<>());
}
while (rs.next()) {
for (int i = 1; i <= columns; ++i) {
map.get(md.getColumnName(i)).add(rs.getObject(i));
}
}
return map;
}
user: root
password: [blank]
XAMPP v3.2.2
scaleLabel : "<%= Number(value).toFixed(2).replace('.', ',') + ' $'%>"
My understanding is that interfaces are not that necessary in dynamic languages like Python. In Java (or C++ with its abstract base class) interfaces are means for ensuring that e.g. you're passing the right parameter, able to perform set of tasks.
E.g. if you have observer and observable, observable is interested in subscribing objects that supports IObserver interface, which in turn has notify
action. This is checked at compile time.
In Python, there is no such thing as compile time
and method lookups are performed at runtime. Moreover, one can override lookup with __getattr__() or __getattribute__() magic methods. In other words, you can pass, as observer, any object that can return callable on accessing notify
attribute.
This leads me to the conclusion, that interfaces in Python do exist - it's just their enforcement is postponed to the moment in which they are actually used
With SublimeText 3 on Windows, the problem is fixed by just closing the Sublime windows used for interactive commit edition.
try this one
<asp:DropDownList ID="ddList" runat="server">
<asp:ListItem Value="">--Select Month--</asp:ListItem>
<asp:ListItem Value="1">January</asp:ListItem>
<asp:ListItem Value="2">Feburary</asp:ListItem>
...
<asp:ListItem Value="12">December</asp:ListItem>
</asp:DropDownList>
Value should be empty for the default selected listitem, then it works fine
Try this:
1. Install Node.js from https://nodejs.org/
2. Place your JavaScript code into a .js file (e.g. someCode.js)
3. Open a cmd shell (or Terminal on Mac) and use Node's Read-Eval-Print-Loop (REPL) to execute someCode.js like this:
> node someCode.js
Hope this helps!
Literals that start with 0x
are hexadecimal integers. (base 16)
The number 0x6400
is 25600
.
6 * 16^3 + 4 * 16^2 = 25600
For an example including letters (also used in hexadecimal notation where A = 10, B = 11 ... F = 15)
The number 0x6BF0
is 27632
.
6 * 16^3 + 11 * 16^2 + 15 * 16^1 = 27632
24576 + 2816 + 240 = 27632
You can achieve spacing between columns using the col-xs-* classes,within in a col-xs-* div coded below. The spacing is consistent so that all of your columns line up correctly. To get even spacing and column size I would do the following:
<div class="container">
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
</div>
You can add delay by making small changes to your function ( async and await ).
const addNSecondsDelay = (n) => {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, n * 1000);
});
}
const asyncFunctionCall = async () {
console.log("stpe-1");
await addNSecondsDelay(5);
console.log("step-2 after 5 seconds delay");
}
asyncFunctionCall();
You don't escape quotes in regular expressions
this.Vals.replace(/["']/g, "")
If you want this information in your phone, then best is to use an app like 'APKit' that shows the full package name of each app in you phone. This information can then be used in your phone.
Another option is to use bash
parameter substitution.
$ foo="/home/parent/child/filename"
$ echo ${foo##*/}
filename
$ foo="/home/parent/child/child2/filename"
$ echo ${foo##*/}
filename
public dynamic ViewBag
{
get
{
if (_viewBag == null)
{
_viewBag = new DynamicViewData(() => ViewData);
}
return _viewBag;
}
}
I had similar issue. try this $('#myAnchor').get(0).click();
this works for me
You can use multiple font faces quite easily. Below is an example of how I used it in the past:
<!--[if (IE)]><!-->
<style type="text/css" media="screen">
@font-face {
font-family: "Century Schoolbook";
src: url(/fonts/century-schoolbook.eot);
}
@font-face {
font-family: "Chalkduster";
src: url(/fonts/chalkduster.eot);
}
</style>
<!--<![endif]-->
<!--[if !(IE)]><!-->
<style type="text/css" media="screen">
@font-face {
font-family: "Century Schoolbook";
src: url(/fonts/century-schoolbook.ttf);
}
@font-face {
font-family: "Chalkduster";
src: url(/fonts/chalkduster.ttf);
}
</style>
<!--<![endif]-->
It is worth noting that fonts can be funny across different Browsers. Font face on earlier browsers works, but you need to use eot files instead of ttf.
That is why I include my fonts in the head of the html file as I can then use conditional IE tags to use eot or ttf files accordingly.
If you need to convert ttf to eot for this purpose there is a brilliant website you can do this for free online, which can be found at http://ttf2eot.sebastiankippe.com/.
Hope that helps.
I think of Divide & Conquer
as an recursive approach and Dynamic Programming
as table filling.
For example, Merge Sort
is a Divide & Conquer
algorithm, as in each step, you split the array into two halves, recursively call Merge Sort
upon the two halves and then merge them.
Knapsack
is a Dynamic Programming
algorithm as you are filling a table representing optimal solutions to subproblems of the overall knapsack. Each entry in the table corresponds to the maximum value you can carry in a bag of weight w given items 1-j.
It's better to do this through Android Studio rather than the file browser as it updates all icon files with the correct resolution for each.
To do so go to menu File ? New ? Image Asset. This will open a new dialogue and then make sure Launcher Icons is selected (Which it is by default) and then browse to the directory of your icon (it doesn't have to be in the project resources) and then once selected make sure other settings are to your liking and hit done.
Now all resolutions are saved into their respective folders, and you don't have to worry about copying it yourself or using tools, etc.
Don't forget "Shape - none" for a transparent background.
Please don't edit my answer without asking.
We had a similar problem in a web application, and ended up by reading the filename from the HTML <input type="file">
, and setting that in the url-encoded form in a new HTML <input type="hidden">
. Of course we had to remove the path like "C:\fakepath\" that is returned by some browsers.
Of course this does not directly answer OPs question, but may be a solution for others.
Add one possible reason in practise:
In practise, Error may be thrown silently, e.g, you submit a timer task and in the timer task it throws Error, while in most cases, your program only catches Exception. Then the Timer main loop is ended without any information. A similar Error to NoClassDefFoundError is ExceptionInInitializerError, when your static initializer or the initializer for a static variable throws an exception.
I provide multiple solutions with descriptions in this answer. Feel free to ask questions if anything is unclear
PS: sadly someone merged this to the top answer without giving credit.
Quick and dirty solution:
Date.now() /1000 |0
Warning: it might break in 2038 and return negative numbers if you do the
|0
magic. UseMath.floor()
instead by that time
Math.floor()
solution:
Math.floor(Date.now() /1000);
Some nerdy alternative by Derek ???? taken from the comments below this answer:
new Date/1e3|0
Polyfill to get Date.now()
working:
To get it working in IE you could do this (Polyfill from MDN):
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
If you do not care about the year / day of week / daylight saving time you could strip it away and use this after 2038:
var now = (function () {
var year = new Date(new Date().getFullYear().toString()).getTime();
return function () {
return Date.now() - year
}
})();
Some output of how it will look:
new Date() Thu Oct 29 2015 08:46:30 GMT+0100 (Mitteleuropäische Zeit ) new Date(now()) Thu Oct 29 1970 09:46:30 GMT+0100 (Mitteleuropäische Zeit )
Of course it will break daylight saving time but depending on what you are building this might be useful to you if you need to do binary operations on timestamps after int32 will break in 2038.
This will also return negative values but only if the user of that PC you are running your code on is changing their PC's clock at least to 31th of december of the previous year.
If you just want to know the relative time from the point of when the code was run through first you could use something like this:
var relativeTime = (function () {
var start = Date.now();
return function () {
return Date.now() - start
}
})();
In case you are using jQuery you could use $.now()
as described in jQuery's Docs which makes the polyfill obsolete since $.now()
internally does the same thing: (new Date).getTime()
If you are just happy about jQuery's version consider upvoting this answer since I did not find it myself.
Now a tiny explaination of what |0
does:
By providing |
, you tell the interpreter to do a binary OR operation. Bit operations require absolute numbers which turns the decimal result from Date.now() / 1000
into an integer.
During that conversion, decimals are removed, resulting in the same result as using Math.floor()
but using less code.
Be warned though: it will convert a 64 bit double to a 32 bit integer. This will result in information loss when dealing with huge numbers. Timestamps will break after 2038 due to 32 bit integer overflow.
For further information about Date.now
follow this link: Date.now()
@ MDN
simple and best way to use date function
example
SELECT * FROM
data
WHERE date(datetime) = '2009-10-20'
OR
SELECT * FROM
data
WHERE date(datetime ) >= '2009-10-20' && date(datetime ) <= '2009-10-20'
Here's a way to do it in Swift (currently writing Swift 2.0 in XCode 7 beta 5).
From your UIView
subclass that you set as "Custom Class" in the Interface Builder create a method like this (my subclass is called RecordingFooterView):
class func loadFromNib() -> RecordingFooterView? {
let nib = UINib(nibName: "RecordingFooterView", bundle: nil)
let nibObjects = nib.instantiateWithOwner(nil, options: nil)
if nibObjects.count > 0 {
let topObject = nibObjects[0]
return topObject as? RecordingFooterView
}
return nil
}
Then you can just call it like this:
let recordingFooterView = RecordingFooterView.loadFromNib()
i have changed my old path: jdbc:odbc:thin:@localhost:1521:orcl
to new : jdbc:oracle:thin:@//localhost:1521/orcl
and it worked for me.....hurrah!! image
Have you tried libconfig; very JSON-like syntax. I prefer it over XML configuration files.
The complement of a regular language is also a regular language, but to construct it you have to build the DFA for the regular language, and make any valid state change into an error. See this for an example. What the page doesn't say is that it converted /(ac|bd)/
into /(a[^c]?|b[^d]?|[^ab])/
. The conversion from a DFA back to a regular expression is not trivial. It is easier if you can use the regular expression unchanged and change the semantics in code, like suggested before.
std::string some_str = SOME_VAL;
if ( some_str.size() > 0 && some_str[some_str.length()-1] == '\n' )
some_str.resize( some_str.length()-1 );
or (removes several newlines at the end)
some_str.resize( some_str.find_last_not_of(L"\n")+1 );
Under the general heading of 'editors always forget to document getting out…' to toggle go to another line and press the combination ctrl+shift+'N' to erase the current bookmark do the same on marked line…
Starting from Spring Boot version 1.2.0.RELEASE , there is a property you can add to your application.properties
to set a default date format to all of your classes spring.jackson.date-format
.
For your date format example, you would add this line to your properties file:
spring.jackson.date-format=yyyy-MM-dd
Posed question
Responding to the question 'what metric should be used for multi-class classification with imbalanced data': Macro-F1-measure. Macro Precision and Macro Recall can be also used, but they are not so easily interpretable as for binary classificaion, they are already incorporated into F-measure, and excess metrics complicate methods comparison, parameters tuning, and so on.
Micro averaging are sensitive to class imbalance: if your method, for example, works good for the most common labels and totally messes others, micro-averaged metrics show good results.
Weighting averaging isn't well suited for imbalanced data, because it weights by counts of labels. Moreover, it is too hardly interpretable and unpopular: for instance, there is no mention of such an averaging in the following very detailed survey I strongly recommend to look through:
Sokolova, Marina, and Guy Lapalme. "A systematic analysis of performance measures for classification tasks." Information Processing & Management 45.4 (2009): 427-437.
Application-specific question
However, returning to your task, I'd research 2 topics:
Commonly used metrics. As I can infer after looking through literature, there are 2 main evaluation metrics:
Yu, April, and Daryl Chang. "Multiclass Sentiment Prediction using Yelp Business."
(link) - note that the authors work with almost the same distribution of ratings, see Figure 5.
Pang, Bo, and Lillian Lee. "Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales." Proceedings of the 43rd Annual Meeting on Association for Computational Linguistics. Association for Computational Linguistics, 2005.
(link)
Lee, Moontae, and R. Grafe. "Multiclass sentiment analysis with restaurant reviews." Final Projects from CS N 224 (2010).
(link) - they explore both accuracy and MSE, considering the latter to be better
Pappas, Nikolaos, Rue Marconi, and Andrei Popescu-Belis. "Explaining the Stars: Weighted Multiple-Instance Learning for Aspect-Based Sentiment Analysis." Proceedings of the 2014 Conference on Empirical Methods In Natural Language Processing. No. EPFL-CONF-200899. 2014.
(link) - they utilize scikit-learn for evaluation and baseline approaches and state that their code is available; however, I can't find it, so if you need it, write a letter to the authors, the work is pretty new and seems to be written in Python.
Cost of different errors. If you care more about avoiding gross blunders, e.g. assinging 1-star to 5-star review or something like that, look at MSE; if difference matters, but not so much, try MAE, since it doesn't square diff; otherwise stay with Accuracy.
About approaches, not metrics
Try regression approaches, e.g. SVR, since they generally outperforms Multiclass classifiers like SVC or OVA SVM.
with a form, just set method
to "post"
<form action="blah.php" method="post">
<input type="text" name="data" value="mydata" />
<input type="submit" />
</form>
You can use xargs
which supports running many processes at a time. For your case it will be:
ls -1 /main/files | xargs -I {} -P 5 -n 1 rsync -avh /main/files/{} /main/filesTest/
I posted a solution using IBInspectable
, so you can change the max length value both in interface builder or programmatically. Check it out here
You may try this
select city
from station where SUBSTRING(city,1,1) in ('A','E','I','O','U') and
SUBSTRING(city,-1,1) in ('A','E','I','O','U');
If using Spring forms, you may need to reset the selected to your options label. You would set your form:select id value to an empty string resets your selection to the label as the default.
<form:select path="myBeanAttribute" id="my_select">
<form:option value="" label="--Select One--"/>
<form:options items="${mySelectionValueList}"/>
</form:select>
$("#reset").on("click", function () {
$("#my_select").val("");
});
in the case where there's a reset button. Otherwise
$("#my_select").val("");
How about this?
this.http.get(targetUrl,{responseType:ResponseContentType.Blob})
.catch((err)=>{return [do yourself]})
.subscribe((res:Response)=>{
var a = document.createElement("a");
a.href = URL.createObjectURL(res.blob());
a.download = fileName;
// start download
a.click();
})
I could do with it.
no need additional package.
$_SERVER['HTTP_REFERER']
will give you the referrer page's URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they're not obliged to set the http_referer as well. You're missing all _
, is that a typo?
npm list -g --depth=0
-g
option it only shows the current directory’s packages)But what if I don't know the indices of the items I want to remove?
I do not exactly understand why you do not like .remove but to get the first index corresponding to a value use .index(value):
ind=item_list.index('item')
then remove the corresponding value:
del item_list.pop[ind]
.index(value) gets the first occurrence of value, and .remove(value) removes the first occurrence of value
PHP 7 standard library provides the random_bytes($length)
function that generate cryptographically secure pseudo-random bytes.
Example:
$bytes = random_bytes(20);
var_dump(bin2hex($bytes));
The above example will output something similar to:
string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
More info: http://php.net/manual/en/function.random-bytes.php
PHP 5 (outdated)
I was just looking into how to solve this same problem, but I also want my function to create a token that can be used for password retrieval as well. This means that I need to limit the ability of the token to be guessed. Because uniqid
is based on the time, and according to php.net "the return value is little different from microtime()", uniqid
does not meet the criteria. PHP recommends using openssl_random_pseudo_bytes()
instead to generate cryptographically secure tokens.
A quick, short and to the point answer is:
bin2hex(openssl_random_pseudo_bytes($bytes))
which will generate a random string of alphanumeric characters of length = $bytes * 2. Unfortunately this only has an alphabet of [a-f][0-9]
, but it works.
function crypto_rand_secure($min, $max)
{
$range = $max - $min;
if ($range < 1) return $min; // not so random...
$log = ceil(log($range, 2));
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd > $range);
return $min + $rnd;
}
function getToken($length)
{
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
$max = strlen($codeAlphabet); // edited
for ($i=0; $i < $length; $i++) {
$token .= $codeAlphabet[crypto_rand_secure(0, $max-1)];
}
return $token;
}
crypto_rand_secure($min, $max)
works as a drop in replacement for rand()
or mt_rand
. It uses openssl_random_pseudo_bytes to help create a random number between $min and $max.
getToken($length)
creates an alphabet to use within the token and then creates a string of length $length
.
Source: http://us1.php.net/manual/en/function.openssl-random-pseudo-bytes.php#104322
Be careful,
jQuery.validator.addMethod("lettersonly", function(value, element)
{
return this.optional(element) || /^[a-z," "]+$/i.test(value);
}, "Letters and spaces only please");
[a-z, " "] by adding the comma and quotation marks, you are allowing spaces, commas and quotation marks into the input box.
For spaces + text, just do this:
jQuery.validator.addMethod("lettersonly", function(value, element)
{
return this.optional(element) || /^[a-z ]+$/i.test(value);
}, "Letters and spaces only please");
[a-z ] this allows spaces aswell as text only.
............................................................................
also the message "Letters and spaces only please" is not required, if you already have a message in messages:
messages:{
firstname:{
required: "Enter your first name",
minlength: jQuery.format("Enter at least (2) characters"),
maxlength:jQuery.format("First name too long more than (80) characters"),
lettersonly:jQuery.format("letters only mate")
},
Adam
Thank you guys for the help,
When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:
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).
None of these other answers worked for me. Here's what I had to do to run a procedure in SQL Developer 3.2.20.10:
SET serveroutput on;
DECLARE
testvar varchar(100);
BEGIN
testvar := 'dude';
schema.MY_PROC(testvar);
dbms_output.enable;
dbms_output.put_line(testvar);
END;
And then you'd have to go check the table for whatever your proc was supposed to do with that passed-in variable -- the output will just confirm that the variable received the value (and theoretically, passed it to the proc).
NOTE (differences with mine vs. others):
:
prior to the variable name.package.
or .packages.
between the schema name and the procedure name&
in the variable's value.print
anywherevar
to declare the variableAll of these problems left me scratching my head for the longest and these answers that have these egregious errors out to be taken out and tarred and feathered.
All you need is to Stop the ASP.NET Development Server and run the project again
To answer the question as asked (without repeating unduly what appears in other answers)
Lexers and parsers are not very different, as suggested by the accepted answer. Both are based on simple language formalisms: regular languages for lexers and, almost always, context-free (CF) languages for parsers. They both are associated with fairly simple computational models, the finite state automaton and the push-down stack automaton. Regular languages are a special case of context-free languages, so that lexers could be produced with the somewhat more complex CF technology. But it is not a good idea for at least two reasons.
A fundamental point in programming is that a system component should be buit with the most appropriate technology, so that it is easy to produce, to understand and to maintain. The technology should not be overkill (using techniques much more complex and costly than needed), nor should it be at the limit of its power, thus requiring technical contortions to achieve the desired goal.
That is why "It seems fashionable to hate regular expressions". Though they can do a lot, they sometimes require very unreadable coding to achieve it, not to mention the fact that various extensions and restrictions in implementation somewhat reduce their theoretical simplicity. Lexers do not usually do that, and are usually a simple, efficient, and appropriate technology to parse token. Using CF parsers for token would be overkill, though it is possible.
Another reason not to use CF formalism for lexers is that it might then be tempting to use the full CF power. But that might raise sructural problems regarding the reading of programs.
Fundamentally, most of the structure of program text, from which meaning is extracted, is a tree structure. It expresses how the parse sentence (program) is generated from syntax rules. Semantics is derived by compositional techniques (homomorphism for the mathematically oriented) from the way syntax rules are composed to build the parse tree. Hence the tree structure is essential. The fact that tokens are identified with a regular set based lexer does not change the situation, because CF composed with regular still gives CF (I am speaking very loosely about regular transducers, that transform a stream of characters into a stream of token).
However, CF composed with CF (via CF transducers ... sorry for the math), does not necessarily give CF, and might makes things more general, but less tractable in practice. So CF is not the appropriate tool for lexers, even though it can be used.
One of the major differences between regular and CF is that regular languages (and transducers) compose very well with almost any formalism in various ways, while CF languages (and transducers) do not, not even with themselves (with a few exceptions).
(Note that regular transducers may have others uses, such as formalization of some syntax error handling techniques.)
BNF is just a specific syntax for presenting CF grammars.
EBNF is a syntactic sugar for BNF, using the facilities of regular notation to give terser version of BNF grammars. It can always be transformed into an equivalent pure BNF.
However, the regular notation is often used in EBNF only to emphasize these parts of the syntax that correspond to the structure of lexical elements, and should be recognized with the lexer, while the rest with be rather presented in straight BNF. But it is not an absolute rule.
To summarize, the simpler structure of token is better analyzed with the simpler technology of regular languages, while the tree oriented structure of the language (of program syntax) is better handled by CF grammars.
I would suggest also looking at AHR's answer.
But this leaves a question open: Why trees?
Trees are a good basis for specifying syntax because
they give a simple structure to the text
there are very convenient for associating semantics with the text on the basis of that structure, with a mathematically well understood technology (compositionality via homomorphisms), as indicated above. It is a fundamental algebraic tool to define the semantics of mathematical formalisms.
Hence it is a good intermediate representation, as shown by the success of Abstract Syntax Trees (AST). Note that AST are often different from parse tree because the parsing technology used by many professionals (Such as LL or LR) applies only to a subset of CF grammars, thus forcing grammatical distorsions which are later corrected in AST. This can be avoided with more general parsing technology (based on dynamic programming) that accepts any CF grammar.
Statement about the fact that programming languages are context-sensitive (CS) rather than CF are arbitrary and disputable.
The problem is that the separation of syntax and semantics is arbitrary. Checking declarations or type agreement may be seen as either part of syntax, or part of semantics. The same would be true of gender and number agreement in natural languages. But there are natural languages where plural agreement depends on the actual semantic meaning of words, so that it does not fit well with syntax.
Many definitions of programming languages in denotational semantics place declarations and type checking in the semantics. So stating as done by Ira Baxter that CF parsers are being hacked to get a context sensitivity required by syntax is at best an arbitrary view of the situation. It may be organized as a hack in some compilers, but it does not have to be.
Also it is not just that CS parsers (in the sense used in other answers here) are hard to build, and less efficient. They are are also inadequate to express perspicuously the kinf of context-sensitivity that might be needed. And they do not naturally produce a syntactic structure (such as parse-trees) that is convenient to derive the semantics of the program, i.e. to generate the compiled code.
In Java7+ you can do this in static methods/fields:
MethodHandles.lookup().lookupClass()
Summary
In context of deep learning the logits layer means the layer that feeds in to softmax (or other such normalization). The output of the softmax are the probabilities for the classification task and its input is logits layer. The logits layer typically produces values from -infinity to +infinity and the softmax layer transforms it to values from 0 to 1.
Historical Context
Where does this term comes from? In 1930s and 40s, several people were trying to adapt linear regression to the problem of predicting probabilities. However linear regression produces output from -infinity to +infinity while for probabilities our desired output is 0 to 1. One way to do this is by somehow mapping the probabilities 0 to 1 to -infinity to +infinity and then use linear regression as usual. One such mapping is cumulative normal distribution that was used by Chester Ittner Bliss in 1934 and he called this "probit" model, short for "probability unit". However this function is computationally expensive while lacking some of the desirable properties for multi-class classification. In 1944 Joseph Berkson used the function log(p/(1-p))
to do this mapping and called it logit, short for "logistic unit". The term logistic regression derived from this as well.
The Confusion
Unfortunately the term logits is abused in deep learning. From pure mathematical perspective logit is a function that performs above mapping. In deep learning people started calling the layer "logits layer" that feeds in to logit function. Then people started calling the output values of this layer "logit" creating the confusion with logit the function.
TensorFlow Code
Unfortunately TensorFlow code further adds in to confusion by names like tf.nn.softmax_cross_entropy_with_logits
. What does logits mean here? It just means the input of the function is supposed to be the output of last neuron layer as described above. The _with_logits
suffix is redundant, confusing and pointless. Functions should be named without regards to such very specific contexts because they are simply mathematical operations that can be performed on values derived from many other domains. In fact TensorFlow has another similar function sparse_softmax_cross_entropy
where they fortunately forgot to add _with_logits
suffix creating inconsistency and adding in to confusion. PyTorch on the other hand simply names its function without these kind of suffixes.
Reference
The Logit/Probit lecture slides is one of the best resource to understand logit. I have also updated Wikipedia article with some of above information.
It is always dependent on where is your html file that refers to the path of the static resource (in this case the image).
Example A:
src
|__assests
|__images
|__myimage.png
|__yourmodule
|__yourpage.html
As you can see, yourpage.html is one folder away from the root (src folder), for this reason it needs one amount of ../ to go back to the root then you can walk to the image from root:
<img class="img-responsive" src="../assests/images/myimage.png">
Example B:
src
|__assests
|__images
|__myimage.png
|__yourmodule
|__yoursubmodule
|__yourpage.html
Here you have to go u in the tree by 2 folders:
<img class="img-responsive" src="../../assests/images/myimage.png">
While it is true that an object cannot be "empty/null" in C++, in C++17, we got std::optional
to express that intent.
Example use:
std::optional<int> v1; // "empty" int
std::optional<int> v2(3); // Not empty, "contains a 3"
You can then check if the optional
contains a value with
v1.has_value(); // false
or
if(v2) {
// You get here if v2 is not empty
}
A plain int
(or any type), however, can never be "null" or "empty" (by your definition of those words) in any useful sense. Think of std::optional
as a container in this regard.
If you don't have a C++17 compliant compiler at hand, you can use boost.optional instead. Some pre-C++17 compilers also offer std::experimental::optional
, which will behave at least close to the actual std::optional
afaik. Check your compiler's manual for details.
Here's a quick way to do it, won't require anything besides sys
.. though functionality is limited:
flag = "--flag" in sys.argv[1:]
[1:]
is in case if the full file name is --flag
In my case, it simply because the disk is full. Just clear some disk space and restart and everything is fine.
Based on answer to a related question.
You may use SNMP to get the memory and CPU usage of a process in a particular device on the network :)
Requirements:
snmp
installed and runningsnmp
should be configured to accept requests from where you will run the script below (it may be configured in file snmpd.conf)Notes:
HOST-RESOURCES-MIB::hrSWRunPerfCPU is the number of centi-seconds of the total system's CPU resources consumed by this process. Note that on a multi-processor system, this value may increment by more than one centi-second in one centi-second of real (wall clock) time.
HOST-RESOURCES-MIB::hrSWRunPerfMem is the total amount of real system memory allocated to this process.
**
Process monitoring script:
**
echo "IP: "
read ip
echo "specfiy pid: "
read pid
echo "interval in seconds:"
read interval
while [ 1 ]
do
date
snmpget -v2c -c public $ip HOST-RESOURCES-MIB::hrSWRunPerfCPU.$pid
snmpget -v2c -c public $ip HOST-RESOURCES-MIB::hrSWRunPerfMem.$pid
sleep $interval;
done
I used to do the following to create header/footer views lazily:
[NSNull null]
The below function will help you get your desired output
<?PHP
function removePrepositions($text){
$propositions=array('/\bfor\b/i','/\bthe\b/i');
if( count($propositions) > 0 ) {
foreach($propositions as $exceptionPhrase) {
$text = preg_replace($exceptionPhrase, '', trim($text));
}
$retval = trim($text);
}
return $retval;
}
?>
Looks like you have an extra parenthesis.
The following portion is parsed as an assignment so the interpreter/compiler will look for a semi-colon or attempt to insert one if certain conditions are met.
foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
})
i'd do it this way (but i'd probably make names an unmodifiable set instead of an array):
import java.util.Arrays;
enum State {
NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITING,TERMINATED;
public static final String[] names=new String[values().length];
static {
State[] values=values();
for(int i=0;i<values.length;i++)
names[i]=values[i].name();
}
}
public class So13783295 {
public static void main(String[] args) {
System.out.println(Arrays.asList(State.names));
}
}
The simplest way is css transform:
.navbar-brand {
transform: translateX(-50%);
left: 50%;
position: absolute;
}
DEMO: http://codepen.io/candid/pen/dGPZvR
This way also works with dynamically sized background images for the logo and allows us to utilize the text-hide class:
CSS:
.navbar-brand {
background: url(http://disputebills.com/site/uploads/2015/10/dispute.png) center / contain no-repeat;
transform: translateX(-50%);
left: 50%;
position: absolute;
width: 200px; /* no height needed ... image will resize automagically */
}
HTML:
<a class="navbar-brand text-hide" href="http://disputebills.com">Brand Text
</a>
We can also use flexbox though. However, using this method we'd have to move navbar-brand
outside of navbar-header
. This way is great though because we can now have image and text side by side:
.brand-centered {
display: flex;
justify-content: center;
position: absolute;
width: 100%;
left: 0;
top: 0;
}
.navbar-brand {
display: flex;
align-items: center;
}
Demo: http://codepen.io/candid/pen/yeLZax
To only achieve these results on mobile simply wrap the above css inside a media query:
@media (max-width: 768px) {
}
"abcd4yyyy" | grep 4 -c
gives the count as 1
Selected answer does not offer a viable solution.
OP's practice seems irregular. A shared/common file normally lives under partials
, a standard boilerplate directory. You should then add partials
directory to your config import paths in order to resolve partials anywhere in your code.
When I encountered this issue for the first time, I figured SASS probably gives you a global variable similar to Node's __dirname
, which keeps an absolute path to current working directory (cwd
). Unfortunately, it does not and the reason why is because interpolation on an @import
directive isn't possible, hence you cannot do a dynamic import path.
According to SASS docs.
You need to set :load_paths
in your Sass config. Since OP uses Compass, I'll follow that with accordance to documentation here.
You can go with the CLI solution as purposed, but why? it's much more convenient to add it to config.rb
. It'd make sense to use CLI for overriding config.rb
(E.g., different build scenarios).
So, assuming your config.rb
is under project root, simply add the following line:
add_import_path 'sub_directory_a'
And now @import 'common';
will work just fine anywhere.
While this answers OP, there's more.
You are likely to run into cases where you want to import a CSS file in an embedded manner, that is, not via the vanilla @import
directive CSS provides out of the box, but an actual merge of a CSS file content with your SASS. There's another question, which is answered inconclusively (the solution does not work cross-environment). The solution then, is to use this SASS extension.
Once installed, add the following line to your config: require 'sass-css-importer'
and then, somewhere in your code: @import 'CSS:myCssFile';
Notice the extension must be omitted for this to work.
However, we will run into the same issue when trying to import a CSS file from a non-default path and add_import_path
does not respect CSS files. So to solve that, you need to add, yet another line in your config, which is naturally similar:
add_import_path Sass::CssImporter::Importer.new('sub_directory_a')
Now everything will work nicely.
P.S.,
I noticed sass-css-importer
documentation indicates a CSS:
prefix is required in addition to omitting the .css
extension. I found out it works regardless. Someone started an issue, which remained unanswered thus far.
I just wanted to add a solution for Mac users since this is the top article that comes up for searches related to this issue. If you have macOS 10.13 or later you can make use of APFS Space Sharing.
Disk Utility
Partition
Add Volume
-- no need to Partition as we are adding an APFS volume which shares space within the current partition/container)Add
cd /Volumes/<your_volume_name>
sdk
It is clear that most people who haven't used SQL Server Enterprise Manager don't understand the question (i.e. Justin Cave).
I came upon this post when I wanted to know the same thing.
Using SQL Server, when you are editing your data through the MS SQL Server GUI Tools, you can use a KEYBOARD SHORTCUT to insert a NULL rather than having just an EMPTY CELL, as they aren't the same thing. An empty cell can have a space in it, rather than being NULL, even if it is technically empty. The difference is when you intentionally WANT to put a NULL in a cell rather than a SPACE or to empty it and NOT using a SQL statement to do so.
So, the question really is, how do I put a NULL value in the cell INSTEAD of a space to empty the cell?
I think the answer is, that the way the Oracle Developer GUI works, is as Laniel indicated above, And THAT should be marked as the answer to this question.
Oracle Developer seems to default to NULL when you empty a cell the way the op is describing it.
Additionally, you can force Oracle Developer to change how your null cells look by changing the color of the background color to further demonstrate when a cell holds a null:
Tools->Preferences->Advanced->Display Null Using Background Color
or even the VALUE it shows when it's null:
Tools->Preferences->Advanced->Display Null Value As
Hope that helps in your transition.
This should do it:
^/\b([a-z0-9]+)\b(?<!ignoreme|ignoreme2|ignoreme3)
You can add as much ignored words as you like, here is a simple PHP implementation:
$ignoredWords = array('ignoreme', 'ignoreme2', 'ignoreme...');
preg_match('~^/\b([a-z0-9]+)\b(?<!' . implode('|', array_map('preg_quote', $ignoredWords)) . ')~i', $string);
You have to call close()
on the GZIPOutputStream
before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush()
probably won't help ... though calling finish()
instead of close()
should work. Look at the javadocs.)
Here's the correct code (in Java);
package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZipTest {
public static void main(String[] args) throws
FileNotFoundException, IOException {
String name = "/tmp/test";
GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
gz.write(10);
gz.close(); // Remove this to reproduce the reported bug
System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
}
}
(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)
The first solution does not work for any UTF-8 alphabet. (It will cut text such as ??????). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.
function removeSpecials(str) {
var lower = str.toLowerCase();
var upper = str.toUpperCase();
var res = "";
for(var i=0; i<lower.length; ++i) {
if(lower[i] != upper[i] || lower[i].trim() === '')
res += str[i];
}
return res;
}
Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.
Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø
== Tromso
).
req
is an object containing information about the HTTP request that raised the event. In response to req
, you use res
to send back the desired HTTP response.
Those parameters can be named anything. You could change that code to this if it's more clear:
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
Edit:
Say you have this method:
app.get('/people.json', function(request, response) { });
The request will be an object with properties like these (just to name a few):
request.url
, which will be "/people.json"
when this particular action is triggeredrequest.method
, which will be "GET"
in this case, hence the app.get()
call.request.headers
, containing items like request.headers.accept
, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.request.query
(e.g. /people.json?foo=bar
would result in request.query.foo
containing the string "bar"
).To respond to that request, you use the response object to build your response. To expand on the people.json
example:
app.get('/people.json', function(request, response) {
// We want to set the content-type header so that the browser understands
// the content of the response.
response.contentType('application/json');
// Normally, the data is fetched from a database, but we can cheat:
var people = [
{ name: 'Dave', location: 'Atlanta' },
{ name: 'Santa Claus', location: 'North Pole' },
{ name: 'Man in the Moon', location: 'The Moon' }
];
// Since the request is for a JSON representation of the people, we
// should JSON serialize them. The built-in JSON.stringify() function
// does that.
var peopleJSON = JSON.stringify(people);
// Now, we can use the response object's send method to push that string
// of people JSON back to the browser in response to this request:
response.send(peopleJSON);
});
Secondary data files are optional, are user-defined, and store user data. Secondary files can be used to spread data across multiple disks by putting each file on a different disk drive. Additionally, if a database exceeds the maximum size for a single Windows file, you can use secondary data files so the database can continue to grow.
Source: MSDN: Understanding Files and Filegroups
The recommended file name extension for secondary data files is .ndf
, but this is not enforced.
Here is my answer:
var options = ["1", "2", "3", "4", "5"];
for(m = 0 ; m <= options.length-1; m++){
var opt= document.createElement("OPTION");
opt.text = options[m];
opt.value = (m+1);
if(options[m] == "5"){
opt.selected = true;}
document.getElementById("selectNum").options.add(opt);}
you need to add it like
insert into table1(date1) values('12-mar-2013');
public static void writeStringAsFile(final String fileContents, String fileName) {
Context context = App.instance.getApplicationContext();
try {
FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
out.write(fileContents);
out.close();
} catch (IOException e) {
Logger.logError(TAG, e);
}
}
public static String readFileAsString(String fileName) {
Context context = App.instance.getApplicationContext();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) stringBuilder.append(line);
} catch (FileNotFoundException e) {
Logger.logError(TAG, e);
} catch (IOException e) {
Logger.logError(TAG, e);
}
return stringBuilder.toString();
}
There is a workaround by capturing clicks on document.body
and then checking event target.
document.body.addEventListener( 'click', function ( event ) {
if( event.srcElement.id == 'btnSubmit' ) {
someFunc();
};
} );
That's what I come up with:
- name: Get directory listing
find:
path: "{{ directory }}"
file_type: any
hidden: yes
register: directory_content_result
- name: Remove directory content
file:
path: "{{ item.path }}"
state: absent
with_items: "{{ directory_content_result.files }}"
loop_control:
label: "{{ item.path }}"
First, we're getting directory listing with find
, setting
file_type
to any
, so we wouldn't miss nested directories and linkshidden
to yes
, so we don't skip hidden filesrecurse
to yes
, since it is not only unnecessary, but may increase execution time. Then, we go through that list with file
module. It's output is a bit verbose, so loop_control.label
will help us with limiting output (found this advice here).
But I found previous solution to be somewhat slow, since it iterates through the content, so I went with:
- name: Get directory stats
stat:
path: "{{ directory }}"
register: directory_stat
- name: Delete directory
file:
path: "{{ directory }}"
state: absent
- name: Create directory
file:
path: "{{ directory }}"
state: directory
owner: "{{ directory_stat.stat.pw_name }}"
group: "{{ directory_stat.stat.gr_name }}"
mode: "{{ directory_stat.stat.mode }}"
stat
That was enough for me, but you can add attributes
as well, if you want.
On an object, you can achieve this with setattr
>>> class A(object): pass
>>> a=A()
>>> setattr(a, "hello1", 5)
>>> a.hello1
5
Here is an example that works on Chrome 5.0.375.125.
The page B (iframe content):
<html>
<head></head>
<body>
<script>
top.postMessage('hello', 'A');
</script>
</body>
</html>
Note the use of top.postMessage
or parent.postMessage
not window.postMessage
here
The page A:
<html>
<head></head>
<body>
<iframe src="B"></iframe>
<script>
window.addEventListener( "message",
function (e) {
if(e.origin !== 'B'){ return; }
alert(e.data);
},
false);
</script>
</body>
</html>
A and B must be something like http://domain.com
EDIT:
From another question, it looks the domains(A and B here) must have a /
for the postMessage
to work properly.
I have written a C++ class which can be used to set the foreground and background color of output. This sample program serves as an example of printing This ->word<- is red.
and formatting it so that the foreground color of word
is red.
#include "colormod.h" // namespace Color
#include <iostream>
using namespace std;
int main() {
Color::Modifier red(Color::FG_RED);
Color::Modifier def(Color::FG_DEFAULT);
cout << "This ->" << red << "word" << def << "<- is red." << endl;
}
#include <ostream>
namespace Color {
enum Code {
FG_RED = 31,
FG_GREEN = 32,
FG_BLUE = 34,
FG_DEFAULT = 39,
BG_RED = 41,
BG_GREEN = 42,
BG_BLUE = 44,
BG_DEFAULT = 49
};
class Modifier {
Code code;
public:
Modifier(Code pCode) : code(pCode) {}
friend std::ostream&
operator<<(std::ostream& os, const Modifier& mod) {
return os << "\033[" << mod.code << "m";
}
};
}
You may want to add additional features to the class. It is, for example, possible to add the color magenta and even styles like boldface. To do this, just an another entry to the Code
enumeration. This is a good reference.
An important note for sending Files with Fetch API
One needs to omit content-type
header for the Fetch request. Then the browser will automatically add the Content type
header including the Form Boundary which looks like
Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD
Form boundary is the delimiter for the form data
Easiest for MAC. Get ip address of your wifi network via ipconfig getifaddr en0
. Then write that ip to your DEV settings -> Debug server host & port for device
adding :8081
example. 192.21.22.143:8081
. Then reload. That's it
store all your data initially
function PhoneListCtrl($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data.splice(0, 5);
$scope.allPhones = data;
});
$scope.orderProp = 'age';
$scope.howMany = 5;
//then here watch the howMany variable on the scope and update the phones array accordingly
$scope.$watch("howMany", function(newValue, oldValue){
$scope.phones = $scope.allPhones.splice(0,newValue)
});
}
EDIT had accidentally put the watch outside the controller it should have been inside.
There is a fairly complete recording demo available at: http://webaudiodemos.appspot.com/AudioRecorder/index.html
It allows you to record audio in the browser, then gives you the option to export and download what you've recorded.
You can view the source of that page to find links to the javascript, but to summarize, there's a Recorder
object that contains an exportWAV
method, and a forceDownload
method.
I am using Visual Studio 2012. After installing the Visual Studio 2013 web express, when I want to run or open any project in Visual Studio 2012 it shows me the following error:
"no exports were found that match the constraint contract name".
I also tried the above solution for clearing the ComponentModelCache, but I did not find the folder. I solves my problem just by: Repair Visual Studio 2012
For the Express versions of the software, the folder you need is in a slightly different place(s): For Express 2012 for Web it is C:\Users\XXXXXXXX\AppData\Local\Microsoft\VWDExpress
- not in the Visual Studio folder.
I wanted to share with you my solution to export a database with Microsoft SQL Server Management Studio.
To Export your database
DECLARE @BackupFile NVARCHAR(255);
SET @BackupFile = 'c:\database-backup_2020.07.22.bak';
PRINT @BackupFile;
BACKUP DATABASE [%databaseName%] TO DISK = @BackupFile;
Don't forget to replace %databaseName%
with the name of the database you want to export.
Note that this method gives a lighter file than from the menu.
To import this file from SQL Server Management Studio. Don't forget to delete your database beforehand.
Enjoy! :) :)
I think the correct syntax is:
cmd /k "cd c:\<folder name>"
This is the first example in the manual page for mysql_query
:
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
If you wish to use something other than die
, then I'd suggest trigger_error
.
Minor variation on Geoff's answer.
New Data in Array:
Sub AddDataRow(tableName As String, NewData As Variant)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = Range(tableName).Parent
Set table = sheet.ListObjects.Item(tableName)
'First check if the last row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
table.ListRows.Add
End If
End If
'Iterate through the last row and populate it with the entries from values()
Set lastRow = table.ListRows(table.ListRows.Count).Range
For col = 1 To lastRow.Columns.Count
If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
Next col
End Sub
New Data in Horizontal Range:
Sub AddDataRow(tableName As String, NewData As Range)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = Range(tableName).Parent
Set table = sheet.ListObjects.Item(tableName)
'First check if the last table row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
table.ListRows.Add
End If
End If
'Copy NewData to new table record
Set lastRow = table.ListRows(table.ListRows.Count).Range
lastRow.Value = NewData.Value
End Sub
I had same kind of problem in Netbeans.
I updated the image location in the project and when I executed the jsp file, the image was not loaded in the page.
Then I clean and Built the project in Netbeans. Then it worked fine.
Though you need to check the image actually exists or not using the image URL in the browser.
Even after adding -DPYTHON_INCLUDE_DIR
and -DPYTHON_LIBRARY
as suggested above, I was still facing the error Could NOT find PythonInterp
. What solved it was adding -DPYTHON_EXECUTABLE:FILEPATH=
to cmake
as suggested in https://github.com/pybind/pybind11/issues/99#issuecomment-182071479:
cmake .. \
-DPYTHON_INCLUDE_DIR=$(python -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \
-DPYTHON_LIBRARY=$(python -c "import distutils.sysconfig as sysconfig; print(sysconfig.get_config_var('LIBDIR'))") \
-DPYTHON_EXECUTABLE:FILEPATH=`which python`
For what it is worth, mine was fixed after I went to target->Build Phases->Link Binary With Libraries, deleted the libstdc++.tbd reference, then added a reference to libstdc++.6.0.9.tbd.
If anybody else had a problem with best answer's solution (including disabling foreign keys), here is another solution from me:
-- CLEAN DB
USE [DB_NAME]
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec SP_EXECUTESQL @Sql
FETCH NEXT
FROM @Cursor INTO @Sql
END
CLOSE @Cursor DEALLOCATE @Cursor
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO
EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL'
I really do not see any way to really get to the number of values in an enumeration in C++. Any of the before mention solution work as long as you do not define the value of your enumerations if you define you value that you might run into situations where you either create arrays too big or too small
enum example{ test1 = -2, test2 = -1, test3 = 0, test4 = 1, test5 = 2 }
in this about examples the result would create a array of 3 items when you need an array of 5 items
enum example2{ test1 , test2 , test3 , test4 , test5 = 301 }
in this about examples the result would create a array of 301 items when you need an array of 5 items
The best way to solve this problem in the general case would be to iterate through your enumerations but that is not in the standard yet as far as I know
As an extra thought, if is needed to pass the column name unquoted to the custom function, perhaps match.call()
could be useful as well in this case, as an alternative to deparse(substitute())
:
df <- data.frame(A = 1:10, B = 2:11)
fun <- function(x, column){
arg <- match.call()
max(x[[arg$column]])
}
fun(df, A)
#> [1] 10
fun(df, B)
#> [1] 11
If there is a typo in the column name, then would be safer to stop with an error:
fun <- function(x, column) max(x[[match.call()$column]])
fun(df, typo)
#> Warning in max(x[[match.call()$column]]): no non-missing arguments to max;
#> returning -Inf
#> [1] -Inf
# Stop with error in case of typo
fun <- function(x, column){
arg <- match.call()
if (is.null(x[[arg$column]])) stop("Wrong column name")
max(x[[arg$column]])
}
fun(df, typo)
#> Error in fun(df, typo): Wrong column name
fun(df, A)
#> [1] 10
Created on 2019-01-11 by the reprex package (v0.2.1)
I do not think I would use this approach since there is extra typing and complexity than just passing the quoted column name as pointed in the above answers, but well, is an approach.
This query here will list the total size that a table takes up - clustered index, heap and all nonclustered indices:
SELECT
s.Name AS SchemaName,
t.NAME AS TableName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM
sys.tables t
INNER JOIN
sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
WHERE
t.NAME NOT LIKE 'dt%' -- filter out system tables for diagramming
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
s.Name, t.Name
If you want to separate table space from index space, you need to use AND i.index_id IN (0,1)
for the table space (index_id = 0
is the heap space, index_id = 1
is the size of the clustered index = data pages) and AND i.index_id > 1
for the index-only space
If none of the answers worked for you. You might be in the wrong "Window". I was in "Package explorer" and switching to "Project Explorer" showed me the folders.
It's the only construct in C that you can use to #define
a multistatement operation, put a semicolon after, and still use within an if
statement. An example might help:
#define FOO(x) foo(x); bar(x)
if (condition)
FOO(x);
else // syntax error here
...;
Even using braces doesn't help:
#define FOO(x) { foo(x); bar(x); }
Using this in an if
statement would require that you omit the semicolon, which is counterintuitive:
if (condition)
FOO(x)
else
...
If you define FOO like this:
#define FOO(x) do { foo(x); bar(x); } while (0)
then the following is syntactically correct:
if (condition)
FOO(x);
else
....
Add LinearLayout
before EditText
in your XML.
<LinearLayout
android:focusable="true"
android:focusableInTouchMode="true"
android:clickable="true"
android:layout_width="0px"
android:layout_height="0px" />
Or you can do this same thing by adding these lines to view before your 'EditText'.
<Button
android:id="@+id/btnSearch"
android:layout_width="50dp"
android:layout_height="50dp"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center"
android:text="Quick Search"
android:textColor="#fff"
android:textSize="13sp"
android:textStyle="bold" />
<EditText
android:id="@+id/edtSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:gravity="left"
android:hint="Name"
android:maxLines="1"
android:singleLine="true"
android:textColorHint="@color/blue"
android:textSize="13sp"
android:textStyle="bold" />
You need to set the password for root@localhost
to be blank. There are two ways:
The MySQL SET PASSWORD
command:
SET PASSWORD FOR root@localhost=PASSWORD('');
Using the command-line mysqladmin
tool:
mysqladmin -u root -pCURRENTPASSWORD password ''
All other answers already give almost everything... Just a little addition.
If you want some more IDE-like debugger (non-CLI) and are not afraid of using Vim as editor, I suggest Vim Ruby Debugger plugin for it.
Its documentation is pretty straightforward, so follow the link and see. In short, it allows you to set breakpoint at current line in editor, view local variables in nifty window on pause, step over/into — almost all usual debugger features.
For me it was pretty enjoyable to use this vim debugger for debugging a Rails app, although rich logger abilities of Rails almost eliminates the need for it.
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)
Using the path /inout-tracker
without a trailing /
doesn't fetch index.php
. Instead the server will issue a 302
redirect to the version with the trailing /
.
Doing a 302 will typically cause clients to convert a POST to a GET request.
You can quote the entire path as in windows or you can escape the spaces like in:
/foo\ folder\ with\ space/foo.sh -help
Both ways will work!
The right way to do this is with the spy on property, it will allow you to simulate a property on an object with an specific value.
const spy = spyOnProperty(myObj, 'valueA').and.returnValue(1);
expect(myObj.valueA).toBe(1);
expect(spy).toHaveBeenCalled();
I had moved my log4j.properties into the resources folder and it worked fine for me !
Is there a reason that you can't do this via Javascript? My advice would be to target the selectors with a universal rule (.foo
) and then parse back over to get the last foo with Javascript and set any additional styling you'll need.
Or as suggested by Stein, just add two classes if you can:
<div class="foo"></div>
<div class="foo last"></div>
.foo {}
.foo.last {}
You parse the field from the database as usual.
Then let's say you put it in a variable called $title
, you just
<html>
<head>
<title>Ultan.me - <?php echo htmlspecialchars($title);?></title>
</head>
EDIT:
I see your problem. You have to set $title
BEFORE using it. That is, you should query the database before <title>...
I don't know the PDO syntax for it, but this seems pretty straight-forward:
$result = mysql_query("SHOW TABLES LIKE 'myTable'");
$tableExists = mysql_num_rows($result) > 0;
Even this works.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/dim_orange_btn_pressed" />
<item android:state_focused="true" android:drawable="@color/dim_orange_btn_pressed" />
<item android:drawable="@android:color/white" />
</selector>
I added the android:drawable
attribute to each item, and their values are colors.
By the way, why do they say that color
is one of the attributes of selector
? They don't write that android:drawable
is required.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:color="hex_color"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"] />
</selector>
If you could show the actual page, we, possibly, could help you better.
If you want to trigger the button only after the iframe is loaded, you might want to check if it has been loaded or use the iframe.onload:
<iframe .... onload='buttonWhatever(); '></iframe>
<script type="text/javascript">
function buttonWhatever() {
$("#<%=Button1.ClientID%>").click(function (event) {
$('#<%=TextBox1.ClientID%>').change(function () {
$('#various3').attr('href', $(this).val());
});
$("#<%=Button2.ClientID%>").click();
});
function showStickySuccessToast() {
$().toastmessage('showToast', {
text: 'Finished Processing!',
sticky: false,
position: 'middle-center',
type: 'success',
closeText: '',
close: function () { }
});
}
}
</script>
zip -r "$destFileName.zip" "$srcFileName" -x "*/\__MACOSX" -x "*/\.*"
-x "*/\__MACOSX"
: ignore __MACOSX as you mention.-x "*/\.*"
: ignore any hidden file, such as .DS_Store .Also, you can build Automator Service to make it easily to use in Finder. Check link below to see detail if you need.
The color of the buttons and other text can also be changed via theme:
values-21/styles.xml
<style name="AppTheme" parent="...">
...
<item name="android:timePickerDialogTheme">@style/AlertDialogCustom</item>
<item name="android:datePickerDialogTheme">@style/AlertDialogCustom</item>
<item name="android:alertDialogTheme">@style/AlertDialogCustom</item>
</style>
<style name="AlertDialogCustom" parent="android:Theme.Material.Light.Dialog.Alert">
<item name="android:colorPrimary">#00397F</item>
<item name="android:colorAccent">#0AAEEF</item>
</style>
The result:
I was fighting with this a whole day asking my users to run debug versions of the software. Because it looked like it didn't run the first line. Just a crash without information.
Then I realized that the error was inside the form's InitializeComponent.
The way to get an exception was to remove this line (or comment it out):
System.Diagnostics.DebuggerStepThrough()
Once you get rid of the line, you'll get a normal exception.
In OOP, you can't cast an instance of a parent class into a child class. You can only cast a child instance into a parent that it inherits from.
Check the Manifest file and make sure the package name is correct
package="com.packagename.your"
In JavaScript (via jQuery):
$(function() {_x000D_
$("body").click(function(e) {_x000D_
if (e.target.id == "myDiv" || $(e.target).parents("#myDiv").length) {_x000D_
alert("Inside div");_x000D_
} else {_x000D_
alert("Outside div");_x000D_
}_x000D_
});_x000D_
})
_x000D_
#myDiv {_x000D_
background: #ff0000;_x000D_
width: 25vw;_x000D_
height: 25vh;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myDiv"></div>
_x000D_
SELECT * FROM items WHERE `items.xml` LIKE '%123456%'
The %
operator in LIKE
means "anything can be here".
I have written a generic caching func()
which will cache any variable easily and very readable format.
Caching function:
function calculateSomethingMaybe(args){
return args;
}
function caching(fn){
const cache = {};
return function(){
const string = arguments[0];
if(!cache[string]){
const result = fn.apply(this, arguments);
cache[string] = result;
return result;
}
return cache[string];
}
}
const letsCache = caching(calculateSomethingMaybe);
console.log(letsCache('a book'), letsCache('a pen'), letsCache('a book'));
For me it work fine
&:not(:last-child){
text-transform: uppercase;
}
There is a circumstance where you're required to declare it final --otherwise it will result in compile error--, namely passing them through into anonymous classes. Basic example:
public FileFilter createFileExtensionFilter(final String extension) {
FileFilter fileFilter = new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(extension);
}
};
// What would happen when it's allowed to change extension here?
// extension = "foo";
return fileFilter;
}
Removing the final
modifier would result in compile error, because it isn't guaranteed anymore that the value is a runtime constant. Changing the value from outside the anonymous class would namely cause the anonymous class instance to behave different after the moment of creation.
There are several ways of doing this. This is an answer that I write hoping that all the basics of Internet Explorer automation will be found when browsing for the keywords "scraping data from website", but remember that nothing's worth as your own research (if you don't want to stick to pre-written codes that you're not able to customize).
Please note that this is one way, that I don't prefer in terms of performance (since it depends on the browser speed) but that is good to understand the rationale behind Internet automation.
1) If I need to browse the web, I need a browser! So I create an Internet Explorer browser:
Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")
2) I ask the browser to browse the target webpage. Through the use of the property ".Visible", I decide if I want to see the browser doing its job or not. When building the code is nice to have Visible = True
, but when the code is working for scraping data is nice not to see it everytime so Visible = False
.
With appIE
.Navigate "http://uk.investing.com/rates-bonds/financial-futures"
.Visible = True
End With
3) The webpage will need some time to load. So, I will wait meanwhile it's busy...
Do While appIE.Busy
DoEvents
Loop
4) Well, now the page is loaded. Let's say that I want to scrape the change of the US30Y T-Bond: What I will do is just clicking F12 on Internet Explorer to see the webpage's code, and hence using the pointer (in red circle) I will click on the element that I want to scrape to see how can I reach my purpose.
5) What I should do is straight-forward. First of all, I will get by the ID property the tr
element which is containing the value:
Set allRowOfData = appIE.document.getElementById("pair_8907")
Here I will get a collection of td
elements (specifically, tr
is a row of data, and the td
are its cells. We are looking for the 8th, so I will write:
Dim myValue As String: myValue = allRowOfData.Cells(7).innerHTML
Why did I write 7 instead of 8? Because the collections of cells starts from 0, so the index of the 8th element is 7 (8-1). Shortly analysing this line of code:
.Cells()
makes me access the td
elements;innerHTML
is the property of the cell containing the value we look for. Once we have our value, which is now stored into the myValue
variable, we can just close the IE browser and releasing the memory by setting it to Nothing:
appIE.Quit
Set appIE = Nothing
Well, now you have your value and you can do whatever you want with it: put it into a cell (Range("A1").Value = myValue
), or into a label of a form (Me.label1.Text = myValue
).
I'd just like to point you out that this is not how StackOverflow works: here you post questions about specific coding problems, but you should make your own search first. The reason why I'm answering a question which is not showing too much research effort is just that I see it asked several times and, back to the time when I learned how to do this, I remember that I would have liked having some better support to get started with. So I hope that this answer, which is just a "study input" and not at all the best/most complete solution, can be a support for next user having your same problem. Because I have learned how to program thanks to this community, and I like to think that you and other beginners might use my input to discover the beautiful world of programming.
Enjoy your practice ;)
Encountered a similar error, this how I resolved it:
Access Project explorer view on Netbeans IDE 8.2. Proceed to your project under Dependencies hover the cursor over the log4j-over-slf4j.jar to view the which which dependencies have indirectly imported as shown below.
Right click an import jar file and select Exclude Dependency
4. Initiate maven clean install and run your project. Good luck!
There are several things wrong with this as you can see in the other posts, but the reason you're getting that error is because you name your form getElementById. So document.getElementById now points to your form instead of the default method that javascript provides. See my fiddle for a working demo https://jsfiddle.net/jemartin80/nhjehwqk/.
function checkValues()
{
var isFormValid, form_fname;
isFormValid = true;
form_fname = document.getElementById("fname");
if (form_fname.value === "")
{
isFormValid = false;
}
isFormValid || alert("I am indicating that there is something wrong with your input.")
return isFormValid;
}
pyinstaller --clean --onefile --icon=default.ico Registry.py
It works for Me
I was facing a similar issue when processing a huge csv file (6 million rows). I had three issues:
df = pd.read_csv(csv_file,sep=';', encoding = 'ISO-8859-1',
names=['permission','owner_name','group_name','size','ctime','mtime','atime','filename','full_filename'],
dtype={'permission':str,'owner_name':str,'group_name':str,'size':str,'ctime':object,'mtime':object,'atime':object,'filename':str,'full_filename':str,'first_date':object,'last_date':object})
try:
df['file_format'] = [Path(f).suffix[1:] for f in df.filename.tolist()]
except:
df['file_format'] = ''
I would style a link to look like a button, because that way there is a no-js fallback.
So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.
Original example:
$(document).ready(function() {_x000D_
$(".jumper").on("click", function( e ) {_x000D_
_x000D_
e.preventDefault();_x000D_
_x000D_
$("body, html").animate({ _x000D_
scrollTop: $( $(this).attr('href') ).offset().top _x000D_
}, 600);_x000D_
_x000D_
});_x000D_
});
_x000D_
#long {_x000D_
height: 500px;_x000D_
background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
New example with actual button styles for the links, just to prove a point.
Everything is essentially the same, except that I changed the class .jumper
to .button
and I added css styling to make the links look like buttons.
After making no changes to a production server we began receiving this error. After trying several different things and thinking that perhaps there were DNS issues, restarting IIS fixed the issue (restarting only the site did not fix the issue). It likely won't work for everyone but if we tried that first it would have saved a lot of time.
This is happening because there is no package cache in the image, you need to run:
apt-get -qq update
before installing packages, and if your command is in a Dockerfile, you'll then need:
apt-get -qq -y install curl
After that install ZSH and GIT Core:
apt-get install zsh
apt-get install git-core
Getting zsh
to work in ubuntu is weird since sh
does not understand the source command. So, you do this to install zsh
:
wget https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | zsh
and then you change your shell to zsh:
chsh -s `which zsh`
and then restart:
sudo shutdown -r 0
This problem is explained in depth in this issue.
This worked for me on OSX.
# allow variable to opened as files
from io import StringIO
# library to map other strange (accented) characters back into UTF-8
from unidecode import unidecode
# cleanse input file with Windows formating to plain UTF-8 string
with open(filename, 'rb') as fID:
uncleansedBytes = fID.read()
# decode the file using the correct encoding scheme
# (probably this old windows one)
uncleansedText = uncleansedBytes.decode('Windows-1252')
# replace carriage-returns with new-lines
cleansedText = uncleansedText.replace('\r', '\n')
# map any other non UTF-8 characters into UTF-8
asciiText = unidecode(cleansedText)
# read each line of the csv file and store as an array of dicts,
# use first line as field names for each dict.
reader = csv.DictReader(StringIO(cleansedText))
for line_entry in reader:
# do something with your read data
If you're testing for all zeros to avoid a warning on another numpy function then wrapping the line in a try, except block will save having to do the test for zeros before the operation you're interested in i.e.
try: # removes output noise for empty slice
mean = np.mean(array)
except:
mean = 0
The underscore usually means a C module (i.e. DLL), and Python can't find it. Did you build python yourself? If so, you need to include SSL support.
Just in case if this helps anybody.
Python version: 3.7.7 platform: Ubuntu 18.04.4 LTS
This came with default python version 3.6.9, however I had installed my own 3.7.7 version python on it (installed building it from source)
tkinter was not working even when the help('module')
shows tkinter in the list.
The following steps worked for me:
sudo apt-get install tk-dev.
rebuild the python: 1. Navigate to your python folder and run the checks:
cd Python-3.7.7
sudo ./configure --enable-optimizations
sudo make -j 8
--- here 8 are the number of processors, check yours using nproc
command.Installing using:
sudo make altinstall
Don't use sudo make install, it will overwrite default 3.6.9 version, which might be messy later.
python3.7 -m tkinter
A windows box will pop up, your tkinter is ready now.
Following on @Fowl's answer, you can improve it with a timeout to only appear for 10 seconds using the following:
mshta "javascript:var sh=new ActiveXObject( 'WScript.Shell' ); sh.Popup( 'Message!', 10, 'Title!', 64 );close()"
See here for more details.
While quicksort is often a better choice than merge sort, there are definitely times when merge sort is thereotically a better choice. The most obvious time is when it's extremely important that your algorithm run faster than O(n^2). Quicksort is usually faster than this, but given the theoretical worst possible input, it could run in O(n^2), which is worse than the worst possible merge sort.
Quicksort is also more complicated than mergesort, especially if you want to write a really solid implementation, and so if you're aiming for simplicity and maintainability, merge sort becomes a promising alternative with very little performance loss.
On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.
BTW: The correct way to do this is to use TryGetValue
obj item;
if(!dict.TryGetValue(name, out item))
return null;
return item;
This accesses the dictionary only once instead of twice.
If you really want to just return null
if the key doesn't exist, the above code can be simplified further:
obj item;
dict.TryGetValue(name, out item);
return item;
This works, because TryGetValue
sets item
to null
if no key with name
exists.
From the video curse Building .NET Console Applications in C# by Jason Roberts at http://www.pluralsight.com
We could do following to have multiple running process
static void Main(string[] args)
{
Console.CancelKeyPress += (sender, e) =>
{
Console.WriteLine("Exiting...");
Environment.Exit(0);
};
Console.WriteLine("Press ESC to Exit");
var taskKeys = new Task(ReadKeys);
var taskProcessFiles = new Task(ProcessFiles);
taskKeys.Start();
taskProcessFiles.Start();
var tasks = new[] { taskKeys };
Task.WaitAll(tasks);
}
private static void ProcessFiles()
{
var files = Enumerable.Range(1, 100).Select(n => "File" + n + ".txt");
var taskBusy = new Task(BusyIndicator);
taskBusy.Start();
foreach (var file in files)
{
Thread.Sleep(1000);
Console.WriteLine("Procesing file {0}", file);
}
}
private static void BusyIndicator()
{
var busy = new ConsoleBusyIndicator();
busy.UpdateProgress();
}
private static void ReadKeys()
{
ConsoleKeyInfo key = new ConsoleKeyInfo();
while (!Console.KeyAvailable && key.Key != ConsoleKey.Escape)
{
key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.UpArrow:
Console.WriteLine("UpArrow was pressed");
break;
case ConsoleKey.DownArrow:
Console.WriteLine("DownArrow was pressed");
break;
case ConsoleKey.RightArrow:
Console.WriteLine("RightArrow was pressed");
break;
case ConsoleKey.LeftArrow:
Console.WriteLine("LeftArrow was pressed");
break;
case ConsoleKey.Escape:
break;
default:
if (Console.CapsLock && Console.NumberLock)
{
Console.WriteLine(key.KeyChar);
}
break;
}
}
}
}
internal class ConsoleBusyIndicator
{
int _currentBusySymbol;
public char[] BusySymbols { get; set; }
public ConsoleBusyIndicator()
{
BusySymbols = new[] { '|', '/', '-', '\\' };
}
public void UpdateProgress()
{
while (true)
{
Thread.Sleep(100);
var originalX = Console.CursorLeft;
var originalY = Console.CursorTop;
Console.Write(BusySymbols[_currentBusySymbol]);
_currentBusySymbol++;
if (_currentBusySymbol == BusySymbols.Length)
{
_currentBusySymbol = 0;
}
Console.SetCursorPosition(originalX, originalY);
}
}
It's possible that the HTML5 Doctype is causing you problems with those older browsers. It could also be down to something funky related to the HTML5 shiv.
You could try switching to one of the XHTML doctypes and changing your markup accordingly, at least temporarily. This might allow you to narrow the problem down.
Is your design breaking when those IEs switch to quirks mode? If it's your CSS causing things to display strangely, it might be worth working on the CSS so the site looks the same even when the browsers switch modes.
Let's say you want to build: u(n+1)=f(u(n)) with u(0)=u0
One solution is to define a simple recursive function:
u0 = ...
def f(x):
...
def u(n):
if n==0: return u0
return f(u(n-1))
Unfortunately, if you want to calculate high values of u, you will run into a stack overflow error.
Another solution is a simple loop:
def u(n):
ux = u0
for i in xrange(n):
ux=f(ux)
return ux
But if you want multiple values of u for different values of n, this is suboptimal. You could cache all values in an array, but you may run into an out of memory error. You may want to use generators instead:
def u(n):
ux = u0
for i in xrange(n):
ux=f(ux)
yield ux
for val in u(1000):
print val
There are many other options, but I guess these are the main ones.
In My case, I am running a local Django backend in IP 127.0.0.1:8000
with Expo start.
Just make sure you have the server in public domain
not hosted lcoally on your machine
Actually, when you do not want to use external sources (or cannot), I would recommend:
DEVICE=$(ls -l /sys/class/net | awk '$NF~/pci0/ { print $(NF-2); exit }')
IPADDR=$(ip -br address show dev $DEVICE | awk '{print substr($3,1,index($3,"/")-1);}')
The first line gets the name of the first network device on the PCI bus, the second one gives you its IP address.
BTW ps ... | grep ... | awk ...
stinks. awk does not need grep.
You can use the Enum::valueOf()
function as suggested by Gareth Davis & Brad Mace above, but make sure you handle the IllegalArgumentException
that would be thrown if the string used is not present in the enum.
Here is the complete xml with gradient, stoke & circular shape.
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<!-- You can use gradient with below attributes-->
<gradient
android:angle="90"
android:centerColor="#555994"
android:endColor="#b5b6d2"
android:startColor="#555994"
android:type="linear" />
<!-- You can omit below tag if you don't need stroke -->
<stroke android:color="#3b91d7" android:width="5dp"/>
<!-- Set the same value for both width and height to get a circular shape -->
<size android:width="200dp" android:height="200dp"/>
<!--if you need only a single color filled shape-->
<solid android:color="#e42828"/>
</shape>
Probably a duplicate of this post: A customized input text box in html/html5
input {_x000D_
border: 0;_x000D_
outline: 0;_x000D_
background: transparent;_x000D_
border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
UPDATED:
You can: create a constant:
private static final DateTimeFormatter DATE_FORMATTER_YYYY_MM_DD =
DateTimeFormat.forPattern("yyyy-MM-dd"); // or whatever pattern that you need.
This DateTimeFormat is importing from: (be careful with that)
import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter;
Parse the Date with:
DateTime.parse(dateTimeScheduled.toString(), DATE_FORMATTER_YYYY_MM_DD);
Before:
DateTime.parse("201711201515",DateTimeFormat.forPattern("yyyyMMddHHmm")).toString("yyyyMMdd");
if want datetime:
DateTime.parse("201711201515", DateTimeFormat.forPattern("yyyyMMddHHmm")).withTimeAtStartOfDay();
List comprehension will lead you to a solution.
But the right way to copy a object in python is using python module copy - Shallow and deep copy operations.
l=[1,2,3,0,0,1]
for i in range(0,len(l)):
if l[i]==0:
l.pop(i)
If instead of this,
import copy
l=[1,2,3,0,0,1]
duplicate_l = copy.copy(l)
for i in range(0,len(l)):
if l[i]==0:
m.remove(i)
l = m
Then, your own code would have worked. But for optimization, list comprehension is a good solution.
You can also use nvl(Column,0)
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
this is just a shot in the dark : when you call connect without a bind first, the system allocates your local port, and if you have multiple threads connecting and disconnecting it could possibly try to allocate a port already in use. the kernel source file inet_connection_sock.c hints at this condition. just as an experiment try doing a bind to a local port first, making sure each bind/connect uses a different local port number.
I started reading David Mertz's book today 'Text Processing in Python.' While he has a fairly terse description of Lambda's the examples in the first chapter combined with the explanation in Appendix A made them jump off the page for me (finally) and all of a sudden I understood their value. That is not to say his explanation will work for you and I am still at the discovery stage so I will not attempt to add to these responses other than the following: I am new to Python I am new to OOP Lambdas were a struggle for me Now that I read Mertz, I think I get them and I see them as very useful as I think they allow a cleaner approach to programming.
He reproduces the Zen of Python, one line of which is Simple is better than complex. As a non-OOP programmer reading code with lambdas (and until last week list comprehensions) I have thought-This is simple?. I finally realized today that actually these features make the code much more readable, and understandable than the alternative-which is invariably a loop of some sort. I also realized that like financial statements-Python was not designed for the novice user, rather it is designed for the user that wants to get educated. I can't believe how powerful this language is. When it dawned on me (finally) the purpose and value of lambdas I wanted to rip up about 30 programs and start over putting in lambdas where appropriate.
To checkout a branch which does not exist locally but is in the remote repo you could use this command:
git checkout -t -b master origin/master
var list = new List<string>();
var queryable = list.AsQueryable();
Add a reference to: System.Linq
You just need a loop that iterates the number of times given by n
and prints a space each time. This would do:
while (n--) {
std::cout << ' ';
}
Naïve datetime
versus aware datetime
Default datetime
objects are said to be "naïve": they keep time information without the time zone information. Think about naïve datetime
as a relative number (ie: +4
) without a clear origin (in fact your origin will be common throughout your system boundary).
In contrast, think about aware datetime
as absolute numbers (ie: 8
) with a common origin for the whole world.
Without timezone information you cannot convert the "naive" datetime towards any non-naive time representation (where does +4
targets if we don't know from where to start ?). This is why you can't have a datetime.datetime.toutctimestamp()
method. (cf: http://bugs.python.org/issue1457227)
To check if your datetime
dt
is naïve, check dt.tzinfo
, if None
, then it's naïve:
datetime.now() ## DANGER: returns naïve datetime pointing on local time
datetime(1970, 1, 1) ## returns naïve datetime pointing on user given time
I have naïve datetimes, what can I do ?
You must make an assumption depending on your particular context:
The question you must ask yourself is: was your datetime
on UTC ? or was it local time ?
If you were using UTC (you are out of trouble):
import calendar
def dt2ts(dt):
"""Converts a datetime object to UTC timestamp
naive datetime will be considered UTC.
"""
return calendar.timegm(dt.utctimetuple())
If you were NOT using UTC, welcome to hell.
You have to make your datetime
non-naïve prior to using the former
function, by giving them back their intended timezone.
You'll need the name of the timezone and the information about if DST was in effect when producing the target naïve datetime (the last info about DST is required for cornercases):
import pytz ## pip install pytz
mytz = pytz.timezone('Europe/Amsterdam') ## Set your timezone
dt = mytz.normalize(mytz.localize(dt, is_dst=True)) ## Set is_dst accordingly
Consequences of not providing is_dst
:
Not using is_dst
will generate incorrect time (and UTC timestamp)
if target datetime was produced while a backward DST was put in place
(for instance changing DST time by removing one hour).
Providing incorrect is_dst
will of course generate incorrect
time (and UTC timestamp) only on DST overlap or holes. And, when
providing
also incorrect time, occuring in "holes" (time that never existed due
to forward shifting DST), is_dst
will give an interpretation of
how to consider this bogus time, and this is the only case where
.normalize(..)
will actually do something here, as it'll then
translate it as an actual valid time (changing the datetime AND the
DST object if required). Note that .normalize()
is not required
for having a correct UTC timestamp at the end, but is probably
recommended if you dislike the idea of having bogus times in your
variables, especially if you re-use this variable elsewhere.
and AVOID USING THE FOLLOWING: (cf: Datetime Timezone conversion using pytz)
dt = dt.replace(tzinfo=timezone('Europe/Amsterdam')) ## BAD !!
Why? because .replace()
replaces blindly the tzinfo
without
taking into account the target time and will choose a bad DST object.
Whereas .localize()
uses the target time and your is_dst
hint
to select the right DST object.
OLD incorrect answer (thanks @J.F.Sebastien for bringing this up):
Hopefully, it is quite easy to guess the timezone (your local origin) when you create your naive datetime
object as it is related to the system configuration that you would hopefully NOT change between the naive datetime object creation and the moment when you want to get the UTC timestamp. This trick can be used to give an imperfect question.
By using time.mktime
we can create an utc_mktime
:
def utc_mktime(utc_tuple):
"""Returns number of seconds elapsed since epoch
Note that no timezone are taken into consideration.
utc tuple must be: (year, month, day, hour, minute, second)
"""
if len(utc_tuple) == 6:
utc_tuple += (0, 0, 0)
return time.mktime(utc_tuple) - time.mktime((1970, 1, 1, 0, 0, 0, 0, 0, 0))
def datetime_to_timestamp(dt):
"""Converts a datetime object to UTC timestamp"""
return int(utc_mktime(dt.timetuple()))
You must make sure that your datetime
object is created on the same timezone than the one that has created your datetime
.
This last solution is incorrect because it makes the assumption that the UTC offset from now is the same than the UTC offset from EPOCH. Which is not the case for a lot of timezones (in specific moment of the year for the Daylight Saving Time (DST) offsets).
It is quite easy. Assuming you have a field(dateposted) with the type "timestamp" in your database table already queried and you want to display it, have it formated and also have the AM/PM, all you need do is shown below.
<?php
echo date("F j, Y h:m:s A" ,strtotime($row_rshearing['dateposted']));
?>
Note: Your OUTPUT should look some what like this depending on the date posted
May 21, 2014 03:05:27 PM
You have to define public String toString()
method in your Student
class. For example:
public String toString() {
return "Student: " + studentName + ", " + studentNo;
}
textarea {
white-space: pre;
overflow-wrap: normal;
overflow-x: scroll;
}
white-space: nowrap
also works if you don't care about whitespace, but of course you don't want that if you're working with code (or indented paragraphs or any content where there might deliberately be multiple spaces) ... so i prefer pre
.
overflow-wrap: normal
(was word-wrap
in older browsers) is needed in case some parent has changed that setting; it can cause wrapping even if pre
is set.
also -- contrary to the currently accepted answer -- textareas do often wrap by default. pre-wrap
seems to be the default on my browser.
This is my solution using the wrapper, just removing border-collapse
might not be helpful always, because you might want to have borders.
.wrapper {_x000D_
overflow: auto;_x000D_
border-radius: 6px;_x000D_
border: 1px solid red;_x000D_
}_x000D_
_x000D_
table {_x000D_
border-spacing: 0;_x000D_
border-collapse: collapse;_x000D_
border-style: hidden;_x000D_
_x000D_
width:100%;_x000D_
max-width: 100%;_x000D_
}_x000D_
_x000D_
th, td {_x000D_
padding: 10px;_x000D_
border: 1px solid #CCCCCC;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Column 1</th>_x000D_
<th>Column 2</th>_x000D_
<th>Column 3</th>_x000D_
</tr>_x000D_
</thead>_x000D_
_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Foo Bar boo</td>_x000D_
<td>Lipsum</td>_x000D_
<td>Beehuum Doh</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Dolor sit</td>_x000D_
<td>ahmad</td>_x000D_
<td>Polymorphism</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Kerbalium</td>_x000D_
<td>Caton, gookame kyak</td>_x000D_
<td>Corona Premium Beer</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table> _x000D_
</div>
_x000D_
This article helped: https://css-tricks.com/table-borders-inside/
I just installed angular cli and it solved my issue, simply run:
npm install -g @angular/cli
After all of the steps listed here failed for me I got it working by running VS2015 as administrator.
Implement the Serializable
interface when you want to be able to convert an instance of a class into a series of bytes or when you think that a Serializable
object might reference an instance of your class.
Serializable
classes are useful when you want to persist instances of them or send them over a wire.
Instances of Serializable
classes can be easily transmitted. Serialization does have some security consequences, however. Read Joshua Bloch's Effective Java.
sed
is the stream editor, in that you can use |
(pipe) to send standard streams (STDIN and STDOUT specifically) through sed
and alter them programmatically on the fly, making it a handy tool in the Unix philosophy tradition; but can edit files directly, too, using the -i
parameter mentioned below.
Consider the following:
sed -i -e 's/few/asd/g' hello.txt
s/
is used to substitute the found expression few
with asd
:
The few, the brave.
The asd, the brave.
/g
stands for "global", meaning to do this for the whole line. If you leave off the /g
(with s/few/asd/
, there always needs to be three slashes no matter what) and few
appears twice on the same line, only the first few
is changed to asd
:
The few men, the few women, the brave.
The asd men, the few women, the brave.
This is useful in some circumstances, like altering special characters at the beginnings of lines (for instance, replacing the greater-than symbols some people use to quote previous material in email threads with a horizontal tab while leaving a quoted algebraic inequality later in the line untouched), but in your example where you specify that anywhere few
occurs it should be replaced, make sure you have that /g
.
The following two options (flags) are combined into one, -ie
:
-i
option is used to edit in place on the file hello.txt
.
-e
option indicates the expression/command to run, in this case s/
.
Note: It's important that you use -i -e
to search/replace. If you do -ie
, you create a backup of every file with the letter 'e' appended.
This site helped me: https://gist.github.com/ocean90/1268328 (Note that on that site the left and right are reversed as of the date of this post... but they work as expected). They are corrected in the code below.
<!DOCTYPE html>
<html>
<head>
<title>Box Shadow</title>
<style>
.box {
height: 150px;
width: 300px;
margin: 20px;
border: 1px solid #ccc;
}
.top {
box-shadow: 0 -5px 5px -5px #333;
}
.right {
box-shadow: 5px 0 5px -5px #333;
}
.bottom {
box-shadow: 0 5px 5px -5px #333;
}
.left {
box-shadow: -5px 0 5px -5px #333;
}
.all {
box-shadow: 0 0 5px #333;
}
</style>
</head>
<body>
<div class="box top"></div>
<div class="box right"></div>
<div class="box bottom"></div>
<div class="box left"></div>
<div class="box all"></div>
</body>
</html>
array = [1,2,3,4,5]
def square(array):
result = map(lambda x: x * x,array)
return list(result)
print(square(array))
I know it's an old question but maybe someone can use this solution:
int size = 0; // Fill all bits with zero (0)
size = ~size; // Negate all bits, thus all bits are set to one (1)
So far we have -1 as result 'till size is a signed int.
size = (unsigned int)size >> 1; // Shift the bits of size one position to the right.
As Standard says, bits that are shifted in are 1 if variable is signed and negative and 0 if variable would be unsigned or signed and positive.
As size is signed and negative we would shift in sign bit which is 1, which is not helping much, so we cast to unsigned int, forcing to shift in 0 instead, setting the sign bit to 0 while letting all other bits remain 1.
cout << size << endl; // Prints out size which is now set to maximum positive value.
We could also use a mask and xor but then we had to know the exact bitsize of the variable. With shifting in bits front, we don't have to know at any time how many bits the int has on machine or compiler nor need we include extra libraries.
you should use fmod(a,b)
While abs(x%y) < abs(y) is true
mathematically, for floats
it may not be true numerically due to roundoff
.
For example, and assuming a platform on which a Python float
is an IEEE 754
double-precision number, in order that -1e-100 % 1e100
have the same sign as 1e100
, the computed result is -1e-100 + 1e100
, which is numerically exactly equal to 1e100
.
Function fmod()
in the math module returns a result whose sign matches the sign of the first argument instead, and so returns -1e-100
in this case. Which approach is more appropriate depends on the application.
where x = a%b
is used for integer modulo
Use Expand-Archive
cmdlet with one of parameter set:
Expand-Archive -LiteralPath C:\source\file.Zip -DestinationPath C:\destination
Expand-Archive -Path file.Zip -DestinationPath C:\destination
I have no idea why the other answers didn't work for me (error 500) but this works
@GetMapping("")
public String getAll() {
List<Entity> entityList = entityManager.findAll();
List<JSONObject> entities = new ArrayList<JSONObject>();
for (Entity n : entityList) {
JSONObject Entity = new JSONObject();
entity.put("id", n.getId());
entity.put("address", n.getAddress());
entities.add(entity);
}
return entities.toString();
}
You can compile Kotlin to bytecode, then use a Java disassembler.
The decompiling may be done inside IntelliJ Idea, or using FernFlower https://github.com/fesh0r/fernflower (thanks @Jire)
There was no automated tool as I checked a couple months ago (and no plans for one AFAIK)
I would recommend replace()
rather than attach()
/detach()
in your tab handling.
Or, switch to ViewPager
. Here is a sample project showing a ViewPager
, with tabs, hosting 10 maps.
You can't change or alter the actual :hover
selector through Javascript. You can, however, use mouseenter
to change the style, and revert back on mouseleave
(thanks, @Bryan).
I have the below code for mouse hover and mouse click and it works:
//For Mouse Hover
.thumbnail:hover span{ /*CSS for enlarged image*/
visibility: visible;
text-align:center;
vertical-align:middle;
height: 70%;
width: 80%;
top:auto;
left: 10%;
}
and this code hides the image when you click on it:
.thumbnail:active span {
visibility: hidden;
}
To complete @Anurag Uniyal 's answer, here is a method that will recursively follow relationships:
from sqlalchemy.inspection import inspect
def to_dict(obj, with_relationships=True):
d = {}
for column in obj.__table__.columns:
if with_relationships and len(column.foreign_keys) > 0:
# Skip foreign keys
continue
d[column.name] = getattr(obj, column.name)
if with_relationships:
for relationship in inspect(type(obj)).relationships:
val = getattr(obj, relationship.key)
d[relationship.key] = to_dict(val) if val else None
return d
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
first_name = Column(TEXT)
address_id = Column(Integer, ForeignKey('addresses.id')
address = relationship('Address')
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
city = Column(TEXT)
user = User(first_name='Nathan', address=Address(city='Lyon'))
# Add and commit user to session to create ids
to_dict(user)
# {'id': 1, 'first_name': 'Nathan', 'address': {'city': 'Lyon'}}
to_dict(user, with_relationship=False)
# {'id': 1, 'first_name': 'Nathan', 'address_id': 1}
You can use
adapter.clear()
that will remove all item of your first adapter then you could either set another adapter or reuse the adapter and add the items to the old adapter. If you use
adapter.add()
to add data to your list you don't need to call notifyDataSetChanged
If you have an array such as
var people = [
{ "name": "bob", "dinner": "pizza" },
{ "name": "john", "dinner": "sushi" },
{ "name": "larry", "dinner": "hummus" }
];
You can use the filter
method of an Array object:
people.filter(function (person) { return person.dinner == "sushi" });
// => [{ "name": "john", "dinner": "sushi" }]
In newer JavaScript implementations you can use a function expression:
people.filter(p => p.dinner == "sushi")
// => [{ "name": "john", "dinner": "sushi" }]
You can search for people who have "dinner": "sushi"
using a map
people.map(function (person) {
if (person.dinner == "sushi") {
return person
} else {
return null
}
}); // => [null, { "name": "john", "dinner": "sushi" }, null]
or a reduce
people.reduce(function (sushiPeople, person) {
if (person.dinner == "sushi") {
return sushiPeople.concat(person);
} else {
return sushiPeople
}
}, []); // => [{ "name": "john", "dinner": "sushi" }]
I'm sure you are able to generalize this to arbitrary keys and values!