I done in this way
from keras.models import Sequential
from keras_contrib.losses import import crf_loss
from keras_contrib.metrics import crf_viterbi_accuracy
# To save model
model.save('my_model_01.hdf5')
# To load the model
custom_objects={'CRF': CRF,'crf_loss': crf_loss,'crf_viterbi_accuracy':crf_viterbi_accuracy}
# To load a persisted model that uses the CRF layer
model1 = load_model("/home/abc/my_model_01.hdf5", custom_objects = custom_objects)
Okay, it was easy:
npm install webpack-dev-server -g
What confused me that I did not need that at first, probably things changed with a new version.
I was also using the official image (FROM postgres
)
and I was able to change the config by executing the following commands.
The first thing is to locate the PostgreSQL config file. This can be done by executing this command in your running database.
SHOW config_file;
I my case it returns /data/postgres/postgresql.conf
.
The next step is to find out what is the hash of your running PostgreSQL docker container.
docker ps -a
This should return a list of all the running containers. In my case it looks like this.
...
0ba35e5427d9 postgres "docker-entrypoint.s…" ....
...
Now you have to switch to the bash inside your container by executing:
docker exec -it 0ba35e5427d9 /bin/bash
Inside the container check if the config is at the correct path and display it.
cat /data/postgres/postgresql.conf
I wanted to change the max connections from 100 to 1000 and the shared buffer from 128MB to 3GB. With the sed command I can do a search and replace with the corresponding variables ins the config.
sed -i -e"s/^max_connections = 100.*$/max_connections = 1000/" /data/postgres/postgresql.conf
sed -i -e"s/^shared_buffers = 128MB.*$/shared_buffers = 3GB/" /data/postgres/postgresql.conf
The last thing we have to do is to restart the database within the container. Find out which version you of PostGres you are using.
cd /usr/lib/postgresql/
ls
In my case its 12
So you can now restart the database by executing the following command with the correct version in place.
su - postgres -c "PGDATA=$PGDATA /usr/lib/postgresql/12/bin/pg_ctl -w restart"
The main reason for the error is the process is not stopped. to resolve it start task manager go to services and see if you are still able to see your service than go to the process of that service and end process. Than the issue will be solved completely.
I had this problem with Django.
Fix it by explicitly setting your hostname to "localhost".
In my case, I had another MySQL version installed and running. I found this by going into the mysql_error.log file. I fix this by going to services and stopping the running MySQL version and setting up to a manual, and starting the mysql needed.
My solution
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+"/your_app_folder/"+"your_picture_saved_name"+".png")), "image/*");
context.startActivity(intent);
Please use this.. it is simplest.
\p{Punct} Punctuation: One of !"#$%&'()*+,-./:;<=>?@[]^_`{|}~
https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
StringBuilder builder = new StringBuilder(checkstring);
String regex = "\\p{Punct}"; //Special character : `~!@#$%^&*()-_+=\|}{]["';:/?.,><
//change your all special characters to ""
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(builder.toString());
checkstring=matcher.replaceAll("");
Just addition to @zirinisp answer.
Create a file, name it UIWindowExtension.swift
and paste the following snippet:
import UIKit
public extension UIWindow {
public var visibleViewController: UIViewController? {
return UIWindow.getVisibleViewControllerFrom(self.rootViewController)
}
public static func getVisibleViewControllerFrom(vc: UIViewController?) -> UIViewController? {
if let nc = vc as? UINavigationController {
return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController)
} else if let tc = vc as? UITabBarController {
return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController)
} else {
if let pvc = vc?.presentedViewController {
return UIWindow.getVisibleViewControllerFrom(pvc)
} else {
return vc
}
}
}
}
func getTopViewController() -> UIViewController? {
let appDelegate = UIApplication.sharedApplication().delegate
if let window = appDelegate!.window {
return window?.visibleViewController
}
return nil
}
Use it anywhere as:
if let topVC = getTopViewController() {
}
Thanks to @zirinisp.
This should do it for you ^wp.*php$
Matches
wp-comments-post.php
wp.something.php
wp.php
Doesn't match
something-wp.php
wp.php.txt
I came across the same issue. My aim is to test PHP scripts with Oracle on Windows 7 Home and without thinking installed IIS7 express and as an afterthought considered Apache as a simpler approach. I will explore IIS express's capabilities seperately.
The challenge was after installing IIS7 express the Apache installation was playing second fiddle to IIS express and bringing up the Microsoft Homepage.
I resolved the port 80 issue by :-
I'm on debian, I found something quite natural to do :
apt-get install docker-compose
and it did the job (not tested on centos)
Try > workdirectory/filename.txt
This would:
You can consider it equivalent to:
rm -f workdirectory/filename.txt; touch workdirectory/filename.txt
Also, if all you are trying to do is break up the main.go file into multiple files, then just name the other files "package main" as long as you only define the main function in one of those files, you are good to go.
One more thing, triggering GC Collect explicitly may NOT improve your program's performance. It is quite possible to make it worse.
The .NET GC is well designed and tuned to be adaptive, which means it can adjust GC0/1/2 threshold according to the "habit" of your program memory usage. So, it will be adapted to your program after some time running. Once you invoke GC.Collect explicitly, the thresholds will be reset! And the .NET has to spent time to adapt to your program's "habit" again.
My suggestion is always trust .NET GC. Any memory problem surfaces, check ".NET Memory" performance counter and diagnose my own code.
You could use the object data type:
>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)
Here is the short answer:
$ ls -ld directory
Here's what it does:
-d, --directory
list directory entries instead of contents, and do not dereference symbolic links
You might be interested in manpages. That's where all people in here get their nice answers from.
refer to online man pages
Another solution you can use is SQL Developer.
With it, you have the ability to import from a csv file (other delimited files are available).
Just open the table view, then:
You have the option to have SQL Developer do the inserts for you, create an sql insert script, or create the data for a SQL Loader script (have not tried this option myself).
Of course all that is moot if you can only use the command line, but if you are able to test it with SQL Developer locally, you can always deploy the generated insert scripts (for example).
Just adding another option to the 2 already very good answers.
As mentioned in the question, there is the clip
css property, although it does require that the element being clipped is position: absolute;
(which is a shame):
.container {_x000D_
position: relative;_x000D_
}_x000D_
#clip {_x000D_
position: absolute;_x000D_
clip: rect(0, 100px, 200px, 0);_x000D_
/* clip: shape(top, right, bottom, left); NB 'rect' is the only available option */_x000D_
}
_x000D_
<div class="container">_x000D_
<img src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="clip" src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>
_x000D_
JS Fiddle demo, for experimentation.
To supplement the original answer – somewhat belatedly – I'm editing to show the use of clip-path
, which has replaced the now-deprecated clip
property.
The clip-path
property allows a range of options (more-so than the original clip
), of:
inset
— rectangular/cuboid shapes, defined with four values as 'distance-from' (top right bottom left)
.circle
— circle(diameter at x-coordinate y-coordinate)
.ellipse
— ellipse(x-axis-length y-axis-length at x-coordinate y-coordinate)
.polygon
— defined by a series of x
/y
coordinates in relation to the element's origin of the top-left corner. As the path is closed automatically the realistic minimum number of points for a polygon should be three, any fewer (two) is a line or (one) is a point: polygon(x-coordinate1 y-coordinate1, x-coordinate2 y-coordinate2, x-coordinate3 y-coordinate3, [etc...])
.url
— this can be either a local URL (using a CSS id-selector) or the URL of an external file (using a file-path) to identify an SVG, though I've not experimented with either (as yet), so I can offer no insight as to their benefit or caveat.div.container {_x000D_
display: inline-block;_x000D_
}_x000D_
#rectangular {_x000D_
-webkit-clip-path: inset(30px 10px 30px 10px);_x000D_
clip-path: inset(30px 10px 30px 10px);_x000D_
}_x000D_
#circle {_x000D_
-webkit-clip-path: circle(75px at 50% 50%);_x000D_
clip-path: circle(75px at 50% 50%)_x000D_
}_x000D_
#ellipse {_x000D_
-webkit-clip-path: ellipse(75px 50px at 50% 50%);_x000D_
clip-path: ellipse(75px 50px at 50% 50%);_x000D_
}_x000D_
#polygon {_x000D_
-webkit-clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
}
_x000D_
<div class="container">_x000D_
<img id="control" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="rectangular" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="circle" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="ellipse" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
<img id="polygon" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>
_x000D_
JS Fiddle demo, for experimentation.
References:
clip
clip-path
(MDN).clip-path
(W3C).The way your code works is pretty close to the "canonical" way to write it. I'd throw an AssertionError
within the catch, though. It signals that that line should never be reached.
catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
There is one more thing you should be aware of - MIME.
If you need to use a MIME type and it isn't supported by default, you can register your own handlers in config/initializers/mime_types.rb:
Mime::Type.register "text/markdown", :markdown
grep -a will force grep to search and output from a file that grep thinks is binary. grep -a re test.log
This is implementation dependent:
Standard 23.1.2.8:
The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.
Maybe you could try this -- this is standard conforming:
for (auto it = numbers.begin(); it != numbers.end(); ) {
if (*it % 2 == 0) {
numbers.erase(it++);
}
else {
++it;
}
}
Note that it++ is postfix, hence it passes the old position to erase, but first jumps to a newer one due to the operator.
2015.10.27 update:
C++11 has resolved the defect. iterator erase (const_iterator position);
return an iterator to the element that follows the last element removed (or set::end
, if the last element was removed). So C++11 style is:
for (auto it = numbers.begin(); it != numbers.end(); ) {
if (*it % 2 == 0) {
it = numbers.erase(it);
}
else {
++it;
}
}
I my case, I had to switch from API 21 to API 19, clean and build and everything was fine again. I am using a Mac and apparently API 21 is not fully supported on Yosemite.
For those using bootstrap 4 beta you can add max-width on your navbar link to have control on the size of your logo with img-fluid class on the image element.
<a class="navbar-brand" href="#" style="max-width: 30%;">
<img src="images/logo.png" class="img-fluid">
</a>
If all you want to do is run your Python Script on a windows computer that has the Python Interpreter installed, converting the extension of your saved script from '.py' to '.pyw' should do the trick.
But if you're using py2exe to convert your script into a standalone application that would run on any windows machine, you will need to make the following changes to your 'setup.py' file.
The following example is of a simple python-GUI made using Tkinter:
from distutils.core import setup
import py2exe
setup (console = ['tkinter_example.pyw'],
options = { 'py2exe' : {'packages':['Tkinter']}})
Change "console" in the code above to "windows"..
from distutils.core import setup
import py2exe
setup (windows = ['tkinter_example.pyw'],
options = { 'py2exe' : {'packages':['Tkinter']}})
This will only open the Tkinter generated GUI and no console window.
You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows:
startInfo.Verb = "runas";
This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command.
This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you'll need to run your entire host process with elevated permissions by Create and Embed an Application Manifest (UAC) to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.
Edit: I see you just edited your question to state that "runas" didn't work for you. That's really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.
Just Try this Sample code:-
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Test {
/**
* Main Method
*/
public static void main(String[] args) {
System.out.println(getDate(82233213123L, "dd/MM/yyyy hh:mm:ss.SSS"));
}
/**
* Return date in specified format.
* @param milliSeconds Date in milliseconds
* @param dateFormat Date format
* @return String representing date in specified format
*/
public static String getDate(long milliSeconds, String dateFormat)
{
// Create a DateFormatter object for displaying date in specified format.
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
}
I hope this help...
Mu. No correct way exists, not even one that's consistent across browsers.
This is a problem that comes from the HTTP specification (section 15.6):
Existing HTTP clients and user agents typically retain authentication information indefinitely. HTTP/1.1. does not provide a method for a server to direct clients to discard these cached credentials.
On the other hand, section 10.4.2 says:
If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information.
In other words, you may be able to show the login box again (as @Karsten says), but the browser doesn't have to honor your request - so don't depend on this (mis)feature too much.
You just need to wrap object in ()
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
If you have to generate global variables in production code (which should be avoided) always declare them explicitly:
window.globalVar = "This is global!";
While it is possible to define a global variable by just omitting var
(assuming there is no local variable of the same name), doing so generates an implicit global, which is a bad thing to do and would generate an error in strict mode.
This works, as long as you remove the height attribute from the table.
<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
<tr><td height='9px' bgcolor="#990000">Upper</td></tr>
<tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>
A quick Update, for the text "Today", the right names are:
todayText: 'Huidige', todayStatus: 'Bekijk de huidige maand',
Even if it is an old thread, maybe some is interested.
If it is an option to you to use the same method inside the same class and archive different return types, use generics: Oracle Lesson Generics
Simple example for generic value holder class:
class GenericValue<T> {
private T myValue;
public GenericValue(T myValue) { this.myValue = myValue; }
public T getVal() { return myValue; }
}
And use it like this:
public class ExampleGenericValue {
public static void main(String[] args) {
GenericValue<Integer> intVal = new GenericValue<Integer>(10);
GenericValue<String> strVal = new GenericValue<String>("go on ...");
System.out.format("I: %d\nS: %s\n", intVal.getVal(), strVal.getVal());
}
}
... will result in the following output:
I: 10
S: go on ...
To install Openjdk 11 in Ubuntu, the following commands worked well.
sudo add-apt-repository ppa:openjdk-r/ppa
sudo apt-get update
sudo apt install openjdk-11-jdk
Here's a way to help large web projects verify that the number of deployed files matches the number of files built into an MSI (or merge module). I've just run the custom MSBuild task against our main application (still in development) and it picked up quite a few missing files, mostly images, but a few javascript files had slipped through to!
This approach (peeking into File table of MSI by hooking into AfterBuild target of WiX project) could work for other application types where you have access to a complete list of expected files.
Use this:
bytes.NewBuffer(byteArray).String()
Remove removeProperty
var el=document.getElementById("id");
el.style.removeProperty('display')
console.log("display removed"+el.style["display"])
console.log("color "+el.style["color"])
_x000D_
<div id="id" style="display:block;color:red">s</div>
_x000D_
You can add .vim
files to be executed whenever vim switches to a particular filetype.
For example, I have a file ~/.vim/after/ftplugin/html.vim
with this contents:
setlocal shiftwidth=2
setlocal tabstop=2
Which causes vim to use tabs with a width of 2 characters for indenting (the noexpandtab
option is set globally elsewhere in my configuration).
This is described here: http://vimdoc.sourceforge.net/htmldoc/usr_05.html#05.4, scroll down to the section on filetype plugins.
The problem doesn't seem to be with the variable but rather with the declaration of ACTInterface. Is ACTInterface declared as internal by any chance?
You want to get the computed width. Try: .offsetWidth
(I.e: this.offsetWidth='50px'
or var w=this.offsetWidth
)
You might also like this answer on SO.
You can prepare your data and pass it to the real column
utility.
Let's assume you have printed data to file /tmp/filename.txt with the tab as a delimeter. Then you can columnize it like this:
import subprocess
result = subprocess.run("cat /tmp/filename.txt | column -N \"col_1,col_2,col_3\" -t -s'\t' -R 2,3", shell=True, stdout=subprocess.PIPE)
print(result.stdout.decode("utf-8"))
As you can see, you can use features of column utility, such as right aligning.
You can add values to the HttpWebRequest.Headers collection.
According to MSDN, it should be supported in windows phone: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers%28v=vs.95%29.aspx
easy!
if option == str(1):
numberA = int(raw_input("enter first number. "))
numberB= int(raw_input("enter second number. "))
print " "
print addition(numberA, numberB)
etc etc etc
Simply apply aggregation function, Sum on your column
df.groupby('steps').sum().show()
Follow the Documentation http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html
Check out this link also https://www.analyticsvidhya.com/blog/2016/10/spark-dataframe-and-operations/
function getRange(a,b)_x000D_
{_x000D_
ar = new Array();_x000D_
var y = a - b > 0 ? a - b : b - a;_x000D_
for (i=1;i<y;i++)_x000D_
{_x000D_
ar.push(i+b);_x000D_
}_x000D_
return ar;_x000D_
}
_x000D_
Below is an adaptation of previous code for using under PyQt5 and Matplotlib 2.0. There are a number of small changes: structure of PyQt submodules, other submodule from matplotlib, deprecated method has been replaced...
import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import random
class Window(QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = plt.figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
self.button = QPushButton('Plot')
self.button.clicked.connect(self.plot)
# set the layout
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
def plot(self):
''' plot some random stuff '''
# random data
data = [random.random() for i in range(10)]
# instead of ax.hold(False)
self.figure.clear()
# create an axis
ax = self.figure.add_subplot(111)
# discards the old graph
# ax.hold(False) # deprecated, see above
# plot data
ax.plot(data, '*-')
# refresh canvas
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
Use this line:) String result = strCurBal.replaceAll("[(" what ever u need to remove ")]", "");_x000D_
_x000D_
String strCurBal = "(+)3428";_x000D_
Log.e("Agilanbu before omit ", strCurBal);_x000D_
String result = strCurBal.replaceAll("[()]", ""); // () removing special characters from string_x000D_
Log.e("Agilanbu after omit ", result);_x000D_
_x000D_
o/p :_x000D_
Agilanbu before omit : (+)3428_x000D_
Agilanbu after omit : +3428_x000D_
_x000D_
String finalVal = result.replaceAll("[+]", ""); // + removing special characters from string_x000D_
Log.e("Agilanbu finalVal ", finalVal);_x000D_
o/p_x000D_
Agilanbu finalVal : 3428_x000D_
_x000D_
String finalVal1 = result.replaceAll("[+]", "-"); // insert | append | replace the special characters from string_x000D_
Log.e("Agilanbu finalVal ", finalVal1);_x000D_
o/p_x000D_
Agilanbu finalVal : -3428 // replacing the + symbol to -
_x000D_
You can convert the value to a date using a formula like this, next to the cell:
=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))
Where A1 is the field you need to convert.
Alternatively, you could use this code in VBA:
Sub ConvertYYYYMMDDToDate()
Dim c As Range
For Each c In Selection.Cells
c.Value = DateSerial(Left(c.Value, 4), Mid(c.Value, 5, 2), Right(c.Value, 2))
'Following line added only to enforce the format.
c.NumberFormat = "mm/dd/yyyy"
Next
End Sub
Just highlight any cells you want fixed and run the code.
Note as RJohnson mentioned in the comments, this code will error if one of your selected cells is empty. You can add a condition on c.value to skip the update if it is blank.
try to empty your innerHtml everytime. just like this:
Element.innerHtml="";
_x000D_
In newer versions of PHP, "extension_dir" is not initially enabled.
You can track by $index
if your data source has duplicate identifiers
e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]
You can't iterate this collection while using 'id' as identifier (duplicate id:1).
WON'T WORK:
<element ng-repeat="item.id as item.name for item in dataSource">
// something with item ...
</element>
but you can, if using track by $index
:
<element ng-repeat="item in dataSource track by $index">
// something with item ...
</element>
Use Nodename over tagName :
nodeName contains all functionalities of tagName, plus a few more. Therefore nodeName is always the better choice.
see DOM Core
Swift 4.1
Add a func to viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
In the setup()
function add:
func setup() {
navigationController?.navigationBar.prefersLargeTitles = true
navigationController?.navigationBar.barStyle = .blackOpaque
navigationItem.title = "YOUR_TITLE_HERE"
navigationController?.navigationBar.barTintColor = .black
let attributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
navigationController?.navigationBar.largeTitleTextAttributes = attributes
}
A more explicit example, built on Damien's code (calls a test resource at http://httpbin.org/). For python3. Note that if the server redirects to another URL, uri
in add_password
has to contain the new root URL (it's possible to pass a list of URLs, also).
import ssl
import urllib.parse
import urllib.request
def get_resource(uri, user, passwd=False):
"""
Get the content of the SSL page.
"""
uri = 'https://httpbin.org/basic-auth/user/passwd'
user = 'user'
passwd = 'passwd'
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, uri, user, passwd)
auth_handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
opener = urllib.request.build_opener(auth_handler, urllib.request.HTTPSHandler(context=context))
urllib.request.install_opener(opener)
return urllib.request.urlopen(uri).read()
a whole div links to another page when clicked without javascript and with valid code, is this possible?
Pedantic answer: No.
As you've already put on another comment, it's invalid to nest a div
inside an a
tag.
However, there's nothing preventing you from making your a
tag behave very similarly to a div
, with the exception that you cannot nest other block tags inside it. If it suits your markup, set display:block
on your a
tag and size / float it however you like.
If you renege on your question's premise that you need to avoid javascript, as others have pointed our you can use the onClick event handler. jQuery is a popular choice for making this easy and maintainable.
Update:
In HTML5, placing a <div>
inside an <a>
is valid.
See http://dev.w3.org/html5/markup/a.html#a-changes (thanks Damien)
Your error might be because of the merge branch.
Just follow this:
step 1 : git pull origin master
(in case if you get any message then ignore it)
step 2 : git add .
step 3 : git commit -m 'your commit message'
step 4 : git push origin master
1. Using the x509 module
openssl x509 ...
...
2 Using the ca module
openssl ca ...
...
You are missing the prelude to those commands.
This is a two-step process. First you set up your CA, and then you sign an end entity certificate (a.k.a server or user). Both of the two commands elide the two steps into one. And both assume you have a an OpenSSL configuration file already setup for both CAs and Server (end entity) certificates.
First, create a basic configuration file:
$ touch openssl-ca.cnf
Then, add the following to it:
HOME = .
RANDFILE = $ENV::HOME/.rnd
####################################################################
[ ca ]
default_ca = CA_default # The default ca section
[ CA_default ]
default_days = 1000 # How long to certify for
default_crl_days = 30 # How long before next CRL
default_md = sha256 # Use public key default MD
preserve = no # Keep passed DN ordering
x509_extensions = ca_extensions # The extensions to add to the cert
email_in_dn = no # Don't concat the email in the DN
copy_extensions = copy # Required to copy SANs from CSR to cert
####################################################################
[ req ]
default_bits = 4096
default_keyfile = cakey.pem
distinguished_name = ca_distinguished_name
x509_extensions = ca_extensions
string_mask = utf8only
####################################################################
[ ca_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = US
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = Maryland
localityName = Locality Name (eg, city)
localityName_default = Baltimore
organizationName = Organization Name (eg, company)
organizationName_default = Test CA, Limited
organizationalUnitName = Organizational Unit (eg, division)
organizationalUnitName_default = Server Research Department
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_default = Test CA
emailAddress = Email Address
emailAddress_default = [email protected]
####################################################################
[ ca_extensions ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always, issuer
basicConstraints = critical, CA:true
keyUsage = keyCertSign, cRLSign
The fields above are taken from a more complex openssl.cnf
(you can find it in /usr/lib/openssl.cnf
), but I think they are the essentials for creating the CA certificate and private key.
Tweak the fields above to suit your taste. The defaults save you the time from entering the same information while experimenting with configuration file and command options.
I omitted the CRL-relevant stuff, but your CA operations should have them. See openssl.cnf
and the related crl_ext
section.
Then, execute the following. The -nodes
omits the password or passphrase so you can examine the certificate. It's a really bad idea to omit the password or passphrase.
$ openssl req -x509 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM
After the command executes, cacert.pem
will be your certificate for CA operations, and cakey.pem
will be the private key. Recall the private key does not have a password or passphrase.
You can dump the certificate with the following.
$ openssl x509 -in cacert.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 11485830970703032316 (0x9f65de69ceef2ffc)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
Validity
Not Before: Jan 24 14:24:11 2014 GMT
Not After : Feb 23 14:24:11 2014 GMT
Subject: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (4096 bit)
Modulus:
00:b1:7f:29:be:78:02:b8:56:54:2d:2c:ec:ff:6d:
...
39:f9:1e:52:cb:8e:bf:8b:9e:a6:93:e1:22:09:8b:
59:05:9f
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
4A:9A:F3:10:9E:D7:CF:54:79:DE:46:75:7A:B0:D0:C1:0F:CF:C1:8A
X509v3 Authority Key Identifier:
keyid:4A:9A:F3:10:9E:D7:CF:54:79:DE:46:75:7A:B0:D0:C1:0F:CF:C1:8A
X509v3 Basic Constraints: critical
CA:TRUE
X509v3 Key Usage:
Certificate Sign, CRL Sign
Signature Algorithm: sha256WithRSAEncryption
4a:6f:1f:ac:fd:fb:1e:a4:6d:08:eb:f5:af:f6:1e:48:a5:c7:
...
cd:c6:ac:30:f9:15:83:41:c1:d1:20:fa:85:e7:4f:35:8f:b5:
38:ff:fd:55:68:2c:3e:37
And test its purpose with the following (don't worry about the Any Purpose: Yes
; see "critical,CA:FALSE" but "Any Purpose CA : Yes").
$ openssl x509 -purpose -in cacert.pem -inform PEM
Certificate purposes:
SSL client : No
SSL client CA : Yes
SSL server : No
SSL server CA : Yes
Netscape SSL server : No
Netscape SSL server CA : Yes
S/MIME signing : No
S/MIME signing CA : Yes
S/MIME encryption : No
S/MIME encryption CA : Yes
CRL signing : Yes
CRL signing CA : Yes
Any Purpose : Yes
Any Purpose CA : Yes
OCSP helper : Yes
OCSP helper CA : Yes
Time Stamp signing : No
Time Stamp signing CA : Yes
-----BEGIN CERTIFICATE-----
MIIFpTCCA42gAwIBAgIJAJ9l3mnO7y/8MA0GCSqGSIb3DQEBCwUAMGExCzAJBgNV
...
aQUtFrV4hpmJUaQZ7ySr/RjCb4KYkQpTkOtKJOU1Ic3GrDD5FYNBwdEg+oXnTzWP
tTj//VVoLD43
-----END CERTIFICATE-----
For part two, I'm going to create another configuration file that's easily digestible. First, touch
the openssl-server.cnf
(you can make one of these for user certificates also).
$ touch openssl-server.cnf
Then open it, and add the following.
HOME = .
RANDFILE = $ENV::HOME/.rnd
####################################################################
[ req ]
default_bits = 2048
default_keyfile = serverkey.pem
distinguished_name = server_distinguished_name
req_extensions = server_req_extensions
string_mask = utf8only
####################################################################
[ server_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = US
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = MD
localityName = Locality Name (eg, city)
localityName_default = Baltimore
organizationName = Organization Name (eg, company)
organizationName_default = Test Server, Limited
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_default = Test Server
emailAddress = Email Address
emailAddress_default = [email protected]
####################################################################
[ server_req_extensions ]
subjectKeyIdentifier = hash
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment
subjectAltName = @alternate_names
nsComment = "OpenSSL Generated Certificate"
####################################################################
[ alternate_names ]
DNS.1 = example.com
DNS.2 = www.example.com
DNS.3 = mail.example.com
DNS.4 = ftp.example.com
If you are developing and need to use your workstation as a server, then you may need to do the following for Chrome. Otherwise Chrome may complain a Common Name is invalid (ERR_CERT_COMMON_NAME_INVALID
). I'm not sure what the relationship is between an IP address in the SAN and a CN in this instance.
# IPv4 localhost
IP.1 = 127.0.0.1
# IPv6 localhost
IP.2 = ::1
Then, create the server certificate request. Be sure to omit -x509
*. Adding -x509
will create a certificate, and not a request.
$ openssl req -config openssl-server.cnf -newkey rsa:2048 -sha256 -nodes -out servercert.csr -outform PEM
After this command executes, you will have a request in servercert.csr
and a private key in serverkey.pem
.
And you can inspect it again.
$ openssl req -text -noout -verify -in servercert.csr
Certificate:
verify OK
Certificate Request:
Version: 0 (0x0)
Subject: C=US, ST=MD, L=Baltimore, CN=Test Server/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:
00:ce:3d:58:7f:a0:59:92:aa:7c:a0:82:dc:c9:6d:
...
f9:5e:0c:ba:84:eb:27:0d:d9:e7:22:5d:fe:e5:51:
86:e1
Exponent: 65537 (0x10001)
Attributes:
Requested Extensions:
X509v3 Subject Key Identifier:
1F:09:EF:79:9A:73:36:C1:80:52:60:2D:03:53:C7:B6:BD:63:3B:61
X509v3 Basic Constraints:
CA:FALSE
X509v3 Key Usage:
Digital Signature, Key Encipherment
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Netscape Comment:
OpenSSL Generated Certificate
Signature Algorithm: sha256WithRSAEncryption
6d:e8:d3:85:b3:88:d4:1a:80:9e:67:0d:37:46:db:4d:9a:81:
...
76:6a:22:0a:41:45:1f:e2:d6:e4:8f:a1:ca:de:e5:69:98:88:
a9:63:d0:a7
Next, you have to sign it with your CA.
You are almost ready to sign the server's certificate by your CA. The CA's openssl-ca.cnf
needs two more sections before issuing the command.
First, open openssl-ca.cnf
and add the following two sections.
####################################################################
[ signing_policy ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
####################################################################
[ signing_req ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment
Second, add the following to the [ CA_default ]
section of openssl-ca.cnf
. I left them out earlier, because they can complicate things (they were unused at the time). Now you'll see how they are used, so hopefully they will make sense.
base_dir = .
certificate = $base_dir/cacert.pem # The CA certifcate
private_key = $base_dir/cakey.pem # The CA private key
new_certs_dir = $base_dir # Location for new certs after signing
database = $base_dir/index.txt # Database index file
serial = $base_dir/serial.txt # The current serial number
unique_subject = no # Set to 'no' to allow creation of
# several certificates with same subject.
Third, touch index.txt
and serial.txt
:
$ touch index.txt
$ echo '01' > serial.txt
Then, perform the following:
$ openssl ca -config openssl-ca.cnf -policy signing_policy -extensions signing_req -out servercert.pem -infiles servercert.csr
You should see similar to the following:
Using configuration from openssl-ca.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName :PRINTABLE:'US'
stateOrProvinceName :ASN.1 12:'MD'
localityName :ASN.1 12:'Baltimore'
commonName :ASN.1 12:'Test CA'
emailAddress :IA5STRING:'[email protected]'
Certificate is to be certified until Oct 20 16:12:39 2016 GMT (1000 days)
Sign the certificate? [y/n]:Y
1 out of 1 certificate requests certified, commit? [y/n]Y
Write out database with 1 new entries
Data Base Updated
After the command executes, you will have a freshly minted server certificate in servercert.pem
. The private key was created earlier and is available in serverkey.pem
.
Finally, you can inspect your freshly minted certificate with the following:
$ openssl x509 -in servercert.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 9 (0x9)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
Validity
Not Before: Jan 24 19:07:36 2014 GMT
Not After : Oct 20 19:07:36 2016 GMT
Subject: C=US, ST=MD, L=Baltimore, CN=Test Server
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:
00:ce:3d:58:7f:a0:59:92:aa:7c:a0:82:dc:c9:6d:
...
f9:5e:0c:ba:84:eb:27:0d:d9:e7:22:5d:fe:e5:51:
86:e1
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
1F:09:EF:79:9A:73:36:C1:80:52:60:2D:03:53:C7:B6:BD:63:3B:61
X509v3 Authority Key Identifier:
keyid:42:15:F2:CA:9C:B1:BB:F5:4C:2C:66:27:DA:6D:2E:5F:BA:0F:C5:9E
X509v3 Basic Constraints:
CA:FALSE
X509v3 Key Usage:
Digital Signature, Key Encipherment
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Netscape Comment:
OpenSSL Generated Certificate
Signature Algorithm: sha256WithRSAEncryption
b1:40:f6:34:f4:38:c8:57:d4:b6:08:f7:e2:71:12:6b:0e:4a:
...
45:71:06:a9:86:b6:0f:6d:8d:e1:c5:97:8d:fd:59:43:e9:3c:
56:a5:eb:c8:7e:9f:6b:7a
Earlier, you added the following to CA_default
: copy_extensions = copy
. This copies extension provided by the person making the request.
If you omit copy_extensions = copy
, then your server certificate will lack the Subject Alternate Names (SANs) like www.example.com
and mail.example.com
.
If you use copy_extensions = copy
, but don't look over the request, then the requester might be able to trick you into signing something like a subordinate root (rather than a server or user certificate). Which means he/she will be able to mint certificates that chain back to your trusted root. Be sure to verify the request with openssl req -verify
before signing.
If you omit unique_subject
or set it to yes
, then you will only be allowed to create one certificate under the subject's distinguished name.
unique_subject = yes # Set to 'no' to allow creation of
# several ctificates with same subject.
Trying to create a second certificate while experimenting will result in the following when signing your server's certificate with the CA's private key:
Sign the certificate? [y/n]:Y
failed to update database
TXT_DB error number 2
So unique_subject = no
is perfect for testing.
If you want to ensure the Organizational Name is consistent between self-signed CAs, Subordinate CA and End-Entity certificates, then add the following to your CA configuration files:
[ policy_match ]
organizationName = match
If you want to allow the Organizational Name to change, then use:
[ policy_match ]
organizationName = supplied
There are other rules concerning the handling of DNS names in X.509/PKIX certificates. Refer to these documents for the rules:
RFC 6797 and RFC 7469 are listed, because they are more restrictive than the other RFCs and CA/B documents. RFC's 6797 and 7469 do not allow an IP address, either.
You can tweak the Registry if you want to make changes only to your own system. If you have IE10 and lots of web sites you visit don't render properly in IE10, then you can tweak your registry to force IE to open in IE9 mode.
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
Create a DWORD as iexplore.exe
and give value 9999
. Restart your IE and it will open in IE9 mode :)
Thanks to my colleague Sreejith D :)
On 5.1 I could only get this to work.
<a href="{{ URL::previous() }}" class="btn btn-default">Back</a>
Check out snakecase from Ruby Facets
The following cases are handled, as seen below:
"SnakeCase".snakecase #=> "snake_case"
"Snake-Case".snakecase #=> "snake_case"
"Snake Case".snakecase #=> "snake_case"
"Snake - Case".snakecase #=> "snake_case"
From: https://github.com/rubyworks/facets/blob/master/lib/core/facets/string/snakecase.rb
class String
# Underscore a string such that camelcase, dashes and spaces are
# replaced by underscores. This is the reverse of {#camelcase},
# albeit not an exact inverse.
#
# "SnakeCase".snakecase #=> "snake_case"
# "Snake-Case".snakecase #=> "snake_case"
# "Snake Case".snakecase #=> "snake_case"
# "Snake - Case".snakecase #=> "snake_case"
#
# Note, this method no longer converts `::` to `/`, in that case
# use the {#pathize} method instead.
def snakecase
#gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr('-', '_').
gsub(/\s/, '_').
gsub(/__+/, '_').
downcase
end
#
alias_method :underscore, :snakecase
# TODO: Add *separators to #snakecase, like camelcase.
end
This is actually pretty simple
Wrap up your vagrant machine
vagrant package --base [machine name as it shows in virtual box] --output /Users/myuser/Documents/Workspace/my.box
copy the box to your remote
init the box on your remote machine by running
vagrant init [machine name as it shows in virtual box] /Users/myuser/Documents/Workspace/my.box
Run vagrant up
You can do it via ODBC. The steps to do it:
input()
by default takes the input in form of strings.
if (0<= vote <=24):
vote takes a string input (suppose 4
,5
,etc) and becomes uncomparable.
The correct way is: vote = int(input("Enter your message")
will convert the input to integer (4
to 4 or 5
to 5 depending on the input)
I use this alert
function myFunction() {_x000D_
$('#passwordsNoMatchRegister').fadeIn(1000);_x000D_
setTimeout(function() { _x000D_
$('#passwordsNoMatchRegister').fadeOut(1000); _x000D_
}, 5000);_x000D_
}
_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<button onclick="myFunction()">Try it</button> _x000D_
_x000D_
_x000D_
<div class="alert alert-danger" id="passwordsNoMatchRegister" style="display:none;">_x000D_
<strong>Error!</strong> Looks like the passwords you entered don't match!_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
It`s definitely better to use COMPOSITE UNIQUE KEY, as @GranadaCoder offered, a little bit tricky example though:
ALTER IGNORE TABLE table_name ADD UNIQUES INDEX idx_name(some_id, another_id, one_more_id);
If you do not care about repetitive form elements with the same name, then you can do:
var data = $("form.login").serializeArray();
var formData = _.object(_.pluck(data, 'name'), _.pluck(data, 'value'));
I am using Underscore.js here.
Seems to work
$(".selector").change(function() {
var $value = $(this).val();
var $title = $(this).children('option[value='+$value+']').html();
$('#bacon').val($title);
});
Just check with your firebug. And don't put css on hidden input.
To use await
, its executing context needs to be async
in nature
As it said, you need to define the nature of your executing context
where you are willing to await
a task before anything.
Just put async
before the fn
declaration in which your async
task will execute.
var start = async function(a, b) {
// Your async task will execute with await
await foo()
console.log('I will execute after foo get either resolved/rejected')
}
Explanation:
In your question, you are importing a method
which is asynchronous
in nature and will execute in parallel. But where you are trying to execute that async
method is inside a different execution context
which you need to define async
to use await
.
var helper = require('./helper.js');
var start = async function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
Wondering what's going under the hood
await
consumes promise/future / task-returning methods/functions and async
marks a method/function as capable of using await.
Also if you are familiar with promises
, await
is actually doing the same process of promise/resolve. Creating a chain of promise and executes you next task in resolve
callback.
For more info you can refer to MDN DOCS.
Unnamed namespaces are a utility to make an identifier translation unit local. They behave as if you would choose a unique name per translation unit for a namespace:
namespace unique { /* empty */ }
using namespace unique;
namespace unique { /* namespace body. stuff in here */ }
The extra step using the empty body is important, so you can already refer within the namespace body to identifiers like ::name
that are defined in that namespace, since the using directive already took place.
This means you can have free functions called (for example) help
that can exist in multiple translation units, and they won't clash at link time. The effect is almost identical to using the static
keyword used in C which you can put in in the declaration of identifiers. Unnamed namespaces are a superior alternative, being able to even make a type translation unit local.
namespace { int a1; }
static int a2;
Both a
's are translation unit local and won't clash at link time. But the difference is that the a1
in the anonymous namespace gets a unique name.
Read the excellent article at comeau-computing Why is an unnamed namespace used instead of static? (Archive.org mirror).
Edit
Okay, complete re-write. It's been a while, I've learned a bit and the comments have helped.
Node.prototype.hasClass = function (className) {
if (this.classList) {
return this.classList.contains(className);
} else {
return (-1 < this.className.indexOf(className));
}
};
Node.prototype.addClass = function (className) {
if (this.classList) {
this.classList.add(className);
} else if (!this.hasClass(className)) {
var classes = this.className.split(" ");
classes.push(className);
this.className = classes.join(" ");
}
return this;
};
Node.prototype.removeClass = function (className) {
if (this.classList) {
this.classList.remove(className);
} else {
var classes = this.className.split(" ");
classes.splice(classes.indexOf(className), 1);
this.className = classes.join(" ");
}
return this;
};
// Some browsers don't have a native trim() function
if(!String.prototype.trim) {
Object.defineProperty(String.prototype,'trim', {
value: function() {
return this.replace(/^\s+|\s+$/g,'');
},
writable:false,
enumerable:false,
configurable:false
});
}
// addClass()
// first checks if the class name already exists, if not, it adds the class.
Object.defineProperty(Node.prototype,'addClass', {
value: function(c) {
if(this.className.indexOf(c)<0) {
this.className=this.className+=' '+c;
}
return this;
},
writable:false,
enumerable:false,
configurable:false
});
// removeClass()
// removes the class and cleans up the className value by changing double
// spacing to single spacing and trimming any leading or trailing spaces
Object.defineProperty(Node.prototype,'removeClass', {
value: function(c) {
this.className=this.className.replace(c,'').replace(' ',' ').trim();
return this;
},
writable:false,
enumerable:false,
configurable:false
});
Now you can call myElement.removeClass('myClass')
or chain it: myElement.removeClass("oldClass").addClass("newClass");
^https?://
You might have to escape the forward slashes though, depending on context.
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
For Java 8:
You can use inbuilt java.time.format.DateTimeFormatter
to reduce any chance of typos,
like
DateTimeFormatter formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
ISO_ZONED_DATE_TIME represents 2011-12-03T10:15:30+01:00[Europe/Paris]
is one of the bundled standard DateTime formats provided by Oracle link
>>> [[int(i) for i in line.strip().split(',')] for line in open('input.txt').readlines()]
[[995957, 16833579], [995959, 16777241], [995960, 16829368], [995961, 50431654]]
super late entry but GAAP is a good rule of thumb..
If your application needs to handle money values up to a trillion then this should work: 13,2 If you need to comply with GAAP (Generally Accepted Accounting Principles) then use: 13,4
Usually you should sum your money values at 13,4 before rounding of the output to 13,2.
exactly I used this
private void updateSetTopState(int index) {
View v = listview.getChildAt(index -
listview.getFirstVisiblePosition()+listview.getHeaderViewsCount());
if(v == null)
return;
TextView aa = (TextView) v.findViewById(R.id.aa);
aa.setVisibility(View.VISIBLE);
}
NoneType
is simply the type of the None
singleton:
>>> type(None)
<type 'NoneType'>
From the latter link above:
None
The sole value of the type
NoneType
.None
is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments toNone
are illegal and raise aSyntaxError
.
In your case, it looks like one of the items you are trying to concatenate is None
, hence your error.
Most people know by now that System.Reflection.Assembly.LoadWithPartialName
is deprecated, but it turns out that Add-Type -AssemblyName Microsoft.VisualBasic
does not behave much better than LoadWithPartialName
:
Rather than make any attempt to parse your request in the context of your system, [Add-Type] looks at a static, internal table to translate the "partial name" to a "full name".
If your "partial name" doesn't appear in their table, your script will fail.
If you have multiple versions of the assembly installed on your computer, there is no intelligent algorithm to choose between them. You are going to get whichever one appears in their table, probably the older, outdated one.
If the versions you have installed are all newer than the obsolete one in the table, your script will fail.
Add-Type has no intelligent parser of "partial names" like
.LoadWithPartialNames
.
What Microsoft's .Net teams says you're actually supposed to do is something like this:
Add-Type -AssemblyName 'Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
Or, if you know the path, something like this:
Add-Type -Path 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualBasic\v4.0_10.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualBasic.dll'
That long name given for the assembly is known as the strong name, which is both unique to the version and the assembly, and is also sometimes known as the full name.
But this leaves a couple questions unanswered:
How do I determine the strong name of what's actually being loaded on my system with a given partial name?
[System.Reflection.Assembly]::LoadWithPartialName($TypeName).Location;
[System.Reflection.Assembly]::LoadWithPartialName($TypeName).FullName;
These should also work:
Add-Type -AssemblyName $TypeName -PassThru | Select-Object -ExpandProperty Assembly | Select-Object -ExpandProperty FullName -Unique
If I want my script to always use a specific version of a .dll but I can't be certain of where it's installed, how do I determine what the strong name is from the .dll?
[System.Reflection.AssemblyName]::GetAssemblyName($Path).FullName;
Or:
Add-Type $Path -PassThru | Select-Object -ExpandProperty Assembly | Select-Object -ExpandProperty FullName -Unique
If I know the strong name, how do I determine the .dll path?
[Reflection.Assembly]::Load('Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a').Location;
And, on a similar vein, if I know the type name of what I'm using, how do I know what assembly it's coming from?
[Reflection.Assembly]::GetAssembly([Type]).Location
[Reflection.Assembly]::GetAssembly([Type]).FullName
How do I see what assemblies are available?
I suggest the GAC PowerShell module. Get-GacAssembly -Name 'Microsoft.SqlServer.Smo*' | Select Name, Version, FullName
works pretty well.
Add-Type
uses?This is a bit more complex. I can describe how to access it for any version of PowerShell with a .Net reflector (see the update below for PowerShell Core 6.0).
First, figure out which library Add-Type
comes from:
Get-Command -Name Add-Type | Select-Object -Property DLL
Open the resulting DLL with your reflector. I've used ILSpy for this because it's FLOSS, but any C# reflector should work. Open that library, and look in Microsoft.Powershell.Commands.Utility
. Under Microsoft.Powershell.Commands
, there should be AddTypeCommand
.
In the code listing for that, there is a private class, InitializeStrongNameDictionary()
. That lists the dictionary that maps the short names to the strong names. There's almost 750 entries in the library I've looked at.
Update: Now that PowerShell Core 6.0 is open source. For that version, you can skip the above steps and see the code directly online in their GitHub repository. I can't guarantee that that code matches any other version of PowerShell, however.
Update 2: Powershell 7+ does not appear to have the hash table lookup any longer. Instead they use a LoadAssemblyHelper()
method which the comments call "the closest approximation possible" to LoadWithPartialName. Basically, they do this:
loadedAssembly = Assembly.Load(new AssemblyName(assemblyName));
Now, the comments also say "users can just say Add-Type -AssemblyName Forms
(instead of System.Windows.Forms)". However, that's not what I see in Powershell v7.0.3 on Windows 10 2004.
# Returns an error
Add-Type -AssemblyName Forms
# Returns an error
[System.Reflection.Assembly]::Load([System.Reflection.AssemblyName]::new('Forms'))
# Works fine
Add-Type -AssemblyName System.Windows.Forms
# Works fine
[System.Reflection.Assembly]::Load([System.Reflection.AssemblyName]::new('System.Windows.Forms'))
So the comments appear to be a bit of a mystery.
I don't know exactly what the logic is in Assembly.Load(AssemblyName)
when there is no version or public key token specified. I would expect that this has many of the same problems that LoadWithPartialName does like potentially loading the wrong version of the assembly if you have multiple installed.
working solution with flex-box
for posterity:
main points:
wrapper {
width: 80;
height: 80;
overflow: hidden;
align-items: center;
justify-content: center;
}
image {
width: min-content;
height: min-content;
}
Try out this will solve ur problem ....
EditText etxt = (EditText)findviewbyid(R.id.etxt);
String str_value = etxt.getText().toString();
A bit late but hopefully useful.
Why not try some of the third party tools that can be integrated into SSMS.
I’ve worked with ApexSQL Search (100% free) with good success for both schema and data search and there is also SSMS tools pack that has this feature (not free for SQL 2012 but quite affordable).
Stored procedure above is really great; it’s just that this is way more convenient in my opinion. Also, it would require some slight modifications if you want to search for datetime columns or GUID columns and such…
From a web page this cannot work since IE restricts the use of that object.
REST
I understand the main idea of REST is extremely simple. We have used web browsers for years and we have seen how easy, flexible, performing, etc web sites are. HTML sites use hyperlinks and forms as the primary means of user interaction. Their main goal is to allow us, clients, to know only those links that we can use in the current state. And REST simply says 'why not use the same principles to drive computer rather than human clients through our application?' Combine this with the power of the WWW infrastructure and you'll get a killer tool for building great distributed applications.
Another possible explanation is for mathematically thinking people. Each application is basically a state machine with business logic actions being state transitions. The idea of REST is to map each transition onto some request to a resource and provide clients with links representing transitions available in the current state. Thus it models the state machine via representations and links. This is why it's called REpresentational State Transfer.
It's quite surprising that all answers seem to focus either on message format, or on HTTP verbs usage. In fact, the message format doesn't matter at all, REST can use any one provided that the service developer documents it. HTTP verbs only make a service a CRUD service, but not yet RESTful. What really turns a service into a REST service are hyperlinks (aka hypermedia controls) embedded into server responses together with data, and their amount must be enough for any client to choose the next action from those links.
Unfortunately, it's rather difficult to find correct info on REST on the Web, except for the Roy Fielding's thesis. (He's the one who derived REST). I would recommend the 'REST in Practice' book as it gives a comprehensive step-by-step tutorial on how to evolve from SOAP to REST.
SOAP
This is one of the possible forms of RPC (remote procedure call) architecture style. In essence, it's just a technology that allows clients call methods of server via service boundaries (network, processes, etc) as if they were calling local methods. Of course, it actually differs from calling local methods in speed, reliability and so on, but the idea is that simple.
Compared
The details like transport protocols, message formats, xsd, wsdl, etc. don't matter when comparing any form of RPC to REST. The main difference is that an RPC service reinvents bicycle by designing it's own application protocol in the RPC API with the semantics that only it knows. Therefore, all clients have to understand this protocol prior to using the service, and no generic infrastructure like caches can be built because of proprietary semantics of all requests. Furthermore, RPC APIs do not suggest what actions are allowed in the current state, this has to be derived from additional documentation. REST on the other hand implies using uniform interfaces to allow various clients to have some understanding of API semantics, and hypermedia controls (links) to highlight available options in each state. Thus, it allows for caching responses to scale services and making correct API usage easily discoverable without additional documentation.
In a way, SOAP (as any other RPC) is an attempt to tunnel through a service boundary treating the connecting media as a black box capable of transmitting messages only. REST is a decision to acknowledge that the Web is a huge distributed information system, to accept the world as is and learn to master it instead of fighting against it.
SOAP seems to be great for internal network APIs, when you control both the server and the clients, and while the interactions are not too complex. It's more natural for developers to use it. However, for a public API that is used by many independent parties, is complex and big, REST should fit better. But this last comparison is very fuzzy.
Update
My experience has unexpectedly shown REST development to be more difficult than SOAP. At least for .NET. While there are great frameworks like ASP.NET Web API, there's no tooling that would automatically generate client-side proxy. Nothing like 'Add Web Service Reference' or 'Add WCF Service Reference'. One has to write all serialization and service querying code by hand. And man, that's lots of boilerplate code. I think REST development needs something similar to WSDL and tooling implementation for each development platform. In fact, there seems to be a good ground: WADL or WSDL 2.0, but neither of the standards seems to be well-supported.
Update (Jan 2016)
Turns out there is now a wide variety of tools for REST API definition. My personal preference is currently RAML.
How Web Services work
Well, this is a too broad question, because it depends on the architecture and technology used in the specific web service. But in general, a web service is simply some application in the Web that can accept requests from clients and return responses. It's exposed to the Web, thus it's a web service, and it's typically available 24/7, that's why it's a service. Of course, it solves some problem (otherwise why would someone ever use a web service) for its clients.
If you NPM those modules you can serve them using static redirect.
First install the packages:
npm install jquery
npm install bootstrap
Then on the server.js:
var express = require('express');
var app = express();
// prepare server
app.use('/api', api); // redirect API calls
app.use('/', express.static(__dirname + '/www')); // redirect root
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap
Then, finally, at the .html:
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
I would not serve pages directly from the folder where your server.js file is (which is usually the same as node_modules) as proposed by timetowonder, that way people can access your server.js file.
Of course you can simply download and copy & paste on your folder, but with NPM you can simply update when needed... easier, I think.
With unsigned numbers of type unsigned int
or larger, in the absence of type conversions, a-b
is defined as yielding the unsigned number which, when added to b
, will yield a
. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).
Note that unsigned numbers smaller than unsigned int
may get promoted to type int
before the subtraction, the behavior of a-b
will depend upon the size of int
.
$('#ID / .Class').css('background-color', '#FF6600');
By using jquery we can target the element's class or Id to apply css background or any other stylings
Use this to obtain only the filename.
Path.GetFileName(files[0]);
Everytime the size of the string is undetermined at compile time you have to allocate memory with malloc (or some equiviallent method). In your case you know the size of your strings at compile time (sizeof("something") and sizeof("something else")).
use below code
Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));
Please check the directory or the folder in which you're installing your new package. This happened to me as well, My whole project was in a subdirectory and I was trying to install in the main directory. After checking the whole thing I found out that I had to install in the subdirectory where my project files and package.json files are located and it's done. Hope this helps...
you can use like this situation:
for example, you have a page: http://www.example.com/page.php
then in that page.php, insert this code:
if (!empty($_GET['doaction']) && $_GET['doaction'] == blabla ){
echo '<script>alert("hello");</script>';
}
then, whenever you visit this url: http://www.example.com/page.php?doaction=blabla
then the alert will be automatically called.
The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().
But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).
The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.
You should not delete the data in box by pressing "delete", i think thats the problem , because excel will still detected the box as "" <- still have value, u should delete by right click the box and click delete.
I'm not entirely sure what you mean by "current milliseconds" but I'll assume it's the number of milliseconds since the "epoch," namely midnight, January 1, 1970 UTC.
If you want to find the number of milliseconds since the epoch right now, then use System.currentTimeMillis()
as Anubian Noob has pointed out. If so, there's no reason to use any of the new java.time APIs to do this.
However, maybe you already have a LocalDateTime
or similar object from somewhere and you want to convert it to milliseconds since the epoch. It's not possible to do that directly, since the LocalDateTime
family of objects has no notion of what time zone they're in. Thus time zone information needs to be supplied to find the time relative to the epoch, which is in UTC.
Suppose you have a LocalDateTime
like this:
LocalDateTime ldt = LocalDateTime.of(2014, 5, 29, 18, 41, 16);
You need to apply the time zone information, giving a ZonedDateTime
. I'm in the same time zone as Los Angeles, so I'd do something like this:
ZonedDateTime zdt = ldt.atZone(ZoneId.of("America/Los_Angeles"));
Of course, this makes assumptions about the time zone. And there are edge cases that can occur, for example, if the local time happens to name a time near the Daylight Saving Time (Summer Time) transition. Let's set these aside, but you should be aware that these cases exist.
Anyway, if you can get a valid ZonedDateTime
, you can convert this to the number of milliseconds since the epoch, like so:
long millis = zdt.toInstant().toEpochMilli();
Edit: CMake now has builtin support for this. See new answer.
You can also force the build of the dependent target in a secondary make process
See my answer on a related topic.
I am working MacOS 10.10. I have updated gcc to version 4.9 to make it work.
brew update brew install gcc brew reinstall r
if( strpos( $url, "#" ) === false ) echo "NO HASH !";
else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0
Or in "old" PHP you must pre-store the exploded to access the array:
$exploded_url = explode( "#", $url ); $exploded_url[1];
var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
forms[i].addEventListener( // add a "listener"
'submit', // for an on-submit "event"
function () { //add a submit pre-processing function:
var input_name = "fragment"; // name form will use to send the fragment
// Try search whether we already done this or not
// in current form, find every <input ... name="fragment" ...>
var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
if (hiddens.length < 1) { // if not there yet
//create an extra input element
var hidden = document.createElement("input");
//set it to hidden so it doesn't break view
hidden.setAttribute('type', 'hidden');
//set a name to get by it in PHP
hidden.setAttribute('name', input_name);
this.appendChild(hidden); //append it to the current form
} else {
var hidden = hiddens[0]; // use an existing one if already there
}
//set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
hidden.setAttribute('value', window.location.hash);
}
);
}
Depending on your form
's method
attribute you get this hash in PHP by:
$_GET['fragment']
or $_POST['fragment']
Possible returns: 1. ""
[empty string] (no hash) 2. whole hash INCLUDING the #
[hash] sign (because we've used the window.location.hash
in JavaScript which just works that way :) )
...(not while considering regular HTTP requests)...
...Hope this helped :)
sorry for reviving this thread, but thought my method was worth adding.
The list name in this example 'list'
list.sort()
print(list[-1])
That will print the highest value in the list easy as!
list.sort()
sorts the list by the value of the item in the ASCII table, so effectively sorts the list lowest to highest. I then just print the last value in the list (which will be the greatest number) by using print(list[-1])
.
Hope this helps!
I am an operating system that only allocates you memory in 10mb partitions.
Internal Fragmentation
Fulfilling this request has just led to 3mb of internal fragmentation.
External Fragmentation
Fulfilling this request has just led to external fragmentation
I wanted to add another option for those getting to this thread via Google. I needed to accomplish this, but wanted to retain my auto-increment value which truncate()
resets. I also didn't want to use DB::
anything because I wanted to operate directly off of the model object. So, I went with this:
Model::whereNotNull('id')->delete();
Obviously the column will have to actually exists, but in a standard, out-of-the-box Eloquent model, the id
column exists and is never null. I don't know if this is the best choice, but it works for my purposes.
The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).
For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.
The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.
Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".
In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".
To search for multiple matches in each file, we can sequence several Select-String calls:
Get-ChildItem C:\Logs |
where { $_ | Select-String -Pattern 'VendorEnquiry' } |
where { $_ | Select-String -Pattern 'Failed' } |
...
At each step, files that do not contain the current pattern will be filtered out, ensuring that the final list of files contains all of the search terms.
Rather than writing out each Select-String call manually, we can simplify this with a filter to match multiple patterns:
filter MultiSelect-String( [string[]]$Patterns ) {
# Check the current item against all patterns.
foreach( $Pattern in $Patterns ) {
# If one of the patterns does not match, skip the item.
$matched = @($_ | Select-String -Pattern $Pattern)
if( -not $matched ) {
return
}
}
# If all patterns matched, pass the item through.
$_
}
Get-ChildItem C:\Logs | MultiSelect-String 'VendorEnquiry','Failed',...
Now, to satisfy the "Logtime about 11:30 am" part of the example would require finding the log time corresponding to each failure entry. How to do this is highly dependent on the actual structure of the files, but testing for "about" is relatively simple:
function AboutTime( [DateTime]$time, [DateTime]$target, [TimeSpan]$epsilon ) {
$time -le ($target + $epsilon) -and $time -ge ($target - $epsilon)
}
PS> $epsilon = [TimeSpan]::FromMinutes(5)
PS> $target = [DateTime]'11:30am'
PS> AboutTime '11:00am' $target $epsilon
False
PS> AboutTime '11:28am' $target $epsilon
True
PS> AboutTime '11:35am' $target $epsilon
True
public static int findNthOccurrence(String phrase, String str, int n)
{
int val = 0, loc = -1;
for(int i = 0; i <= phrase.length()-str.length() && val < n; i++)
{
if(str.equals(phrase.substring(i,i+str.length())))
{
val++;
loc = i;
}
}
if(val == n)
return loc;
else
return -1;
}
The gradle daemon also creates a many large text files of every single build log. They are stored here:
~/.gradle/daemon/X.X/daemon-XXXX.out.log
"X.X" is the gradle version in use, like "4.4", and "XXXX" are just random numbers, like "1234".
The total size can grow to several hundred MB in just a few months. There is no way to disable the logging, and the files are not automatically deleted and they do not really need to be retained.
But you can create a small gradle task to automatically delete them, and free up lots of disk space:
Add this to your app/build.gradle
:
android {
buildTypes {
...
}
// Delete large build log files from ~/.gradle/daemon/X.X/daemon-XXX.out.log
// Source: https://discuss.gradle.org/t/gradle-daemon-produces-a-lot-of-logs/9905
def gradle = project.getGradle()
new File("${gradle.getGradleUserHomeDir().getAbsolutePath()}/daemon/${gradle.getGradleVersion()}").listFiles().each {
if (it.getName().endsWith('.out.log')) {
// println("Deleting gradle log file: $it") // Optional debug output
it.delete()
}
}
}
To see which files are being deleted, you can see the debug output in Android Studio -> View -> Tool Windows -> Build. Then press "Toggle View" button on that window to show the text output.
Note that a Gradle Sync or any Gradle Build will trigger the file deletions.
A better way would be to automatically move the files to the Trash/Recycle Bin, or at least copy them to a Trash folder first. But I don't know how to do that.
Check the declaration of your variable. It must be like that
public Nullable<int> x {get; set;}
public Nullable<int> y {get; set;}
public Nullable<int> z {get { return x*y;} }
I hope it is useful for you
Actually, this is subtler than it looks.
The code above would give the incorrect answer for a lower case character whose code point was above U+FFFF (such as U+1D4C3, MATHEMATICAL SCRIPT SMALL N). String.charAt would return a UTF-16 surrogate pair, which is not a character, but rather half the character, so to speak. So you have to use String.codePointAt, which returns an int above 0xFFFF (not a char). You would do:
Character.isUpperCase(s.codePointAt(0));
Don't feel bad overlooked this; almost all Java coders handle UTF-16 badly, because the terminology misleadingly makes you think that each "char" value represents a character. UTF-16 sucks, because it is almost fixed width but not quite. So non-fixed-width edge cases tend not to get tested. Until one day, some document comes in which contains a character like U+1D4C3, and your entire system blows up.
You could also implement rich comparison via __eq__
method for your Test
class and use in
operator.
Not sure if this is the best stand-alone way, but in case if you need to compare Test
instances based on value
somewhere else, this could be useful.
class Test:
def __init__(self, value):
self.value = value
def __eq__(self, other):
"""To implement 'in' operator"""
# Comparing with int (assuming "value" is int)
if isinstance(other, int):
return self.value == other
# Comparing with another Test object
elif isinstance(other, Test):
return self.value == other.value
import random
value = 5
test_list = [Test(random.randint(0,100)) for x in range(1000)]
if value in test_list:
print "i found it"
Accordingly to W3C checked input's attribute can be absent/ommited or have "checked" as its value. This does not invalidate other values because there's no restriction to the browser implementation to allow values like "true", "on", "yes" and so on. To guarantee that you'll write a cross-browser checkbox/radio use checked="checked", as recommended by W3C.
disabled, readonly and ismap input's attributes go on the same way.
EDITED
empty is not a valid value for checked, disabled, readonly and ismap input's attributes, as warned by @Quentin
Perhaps I'm misunderstanding the intent of your question, so correct me if I'm wrong, but can't you apply the culture settings globally once, and then not worry about customizing every write statement?
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
This regex validates dates between 01-01-2000 and 12-31-2099 with matching separators.
^(0[1-9]|1[012])([- /.])(0[1-9]|[12][0-9]|3[01])\2(19|20)\d\d$
to Set Variable:
item Assignment method using key:
import os
os.environ['DEBUSSY'] = '1' #Environ Variable must be string not Int
to get or to check whether its existed or not,
since os.environ is an instance you can try object way.
Method 1:
os.environ.get('DEBUSSY') # this is error free method if not will return None by default
will get '1'
as return value
Method 2:
os.environ['DEBUSSY'] # will throw an key error if not found!
Method 3:
'DEBUSSY' in os.environ # will return Boolean True/False
Method 4:
os.environ.has_key('DEBUSSY') #last 2 methods are Boolean Return so can use for conditional statements
You can do something like this:
// show loading image
$('#loader_img').show();
// main image loaded ?
$('#main_img').on('load', function(){
// hide/remove the loading image
$('#loader_img').hide();
});
You assign load
event to the image which fires when image has finished loading. Before that, you can show your loader image.
- Upto my knowledge, Heap space is occupied by instance variables only. If this is correct, then why this error occurred after running fine for sometime as space for instance variables are alloted at the time of object creation.
That means you are creating more objects in your application over a period of time continuously. New objects will be stored in heap memory and that's the reason for growth in heap memory.
Heap not only contains instance variables. It will store all non-primitive data types ( Objects). These objects life time may be short (method block) or long (till the object is referenced in your application)
- Is there any way to increase the heap space?
Yes. Have a look at this oracle article for more details.
There are two parameters for setting the heap size:
-Xms:, which sets the initial and minimum heap size
-Xmx:, which sets the maximum heap size
- What changes should I made to my program so that It will grab less heap space?
It depends on your application.
Set the maximum heap memory as per your application requirement
Don't cause memory leaks in your application
If you find memory leaks in your application, find the root cause with help of profiling tools like MAT, Visual VM , jconsole etc. Once you find the root cause, fix the leaks.
Important notes from oracle article
Cause: The detail message Java heap space indicates object could not be allocated in the Java heap. This error does not necessarily imply a memory leak.
Possible reasons:
On a different note, use better Garbage collection algorithms ( CMS or G1GC)
Have a look at this question for understanding G1GC
Just wrap the button label in an extra span and add class="align-middle"
to both (the icon and the label). This will center your icon with text vertical.
<button id="edit-listing-form-house_Continue"
class="btn btn-large btn-primary"
style=""
value=""
name="Continue"
type="submit">
<span class="align-middle">Continue</span>
<i class="icon-ok align-middle" style="font-size:40px;"></i>
You could do it this way:
<b ng-repeat="email in friend.email">{{email}}{{$last ? '' : ', '}}</b>
..But I like Philipp's answer :-)
To make it work you have to replace a run this line of code
serviceMetadata httpGetEnabled="true"/>
http instead of https
and security mode="None" />
We can concat Like this :
<h5 th:text ="${currentItem.first_name}+ ' ' + ${currentItem.last_name}"></h5>
On MISRA 98 rules, that is used on my company in C dev, break statement shall not be used...
Edit : Break is allowed in MISRA '04
Simple one
Reference - http://www.php.net/manual/en/function.date.php
<?php
echo 'First Date = ' . date('Y-m-01') . '<br />';
echo 'Last Date = ' . date('Y-m-t') . '<br />';
?>
add margin:-1px;
which reduces 1px
to each side. or if you need only for side you can do margin-left:-1px
etc.
You can do:
struct employee_s {
int id;
char* name;
} employee_default = {0, "none"};
typedef struct employee_s employee;
And then you just have to remember to do the default initialization when you declare a new employee variable:
employee foo = employee_default;
Alternatively, you can just always build your employee struct via a factory function.
You don't have to do anything really except prepare your phone to be able to run debug and usb apps :
http://developer.android.com/guide/developing/device.html
then simply launch your app from eclipse and your device will be used if you don't have a simulator running.
Saving to Hive is just a matter of using write()
method of your SQLContext:
df.write.saveAsTable(tableName)
From Spark 2.2: use DataSet instead DataFrame.
Having the same problem with unchecked checkboxes that will not be send on forms submit, I came out with a another solution than mirror the checkbox items.
Getting all unchecked checkboxes with
var checkboxQueryString;
$form.find ("input[type=\"checkbox\"]:not( \":checked\")" ).each(function( i, e ) {
checkboxQueryString += "&" + $( e ).attr( "name" ) + "=N"
});
I came here hoping to find a way to get the sum across all columns in a data table and run into issues implementing the above solutions. A way to add a column with the sum across all columns uses the cbind
function:
cbind(data, total = rowSums(data))
This method adds a total
column to the data and avoids the alignment issue yielded when trying to sum across ALL columns using the above solutions (see the post below for a discussion of this issue).
If anyone is following all the steps and having no success, make sure that you are using the correct user. I was attempting to use "ec2-user" but I needed to use "ubuntu."
I had the same problem - for me it was the SQL Server running out of memory. Freeing up some memory solved the issue
Database, dict of dicts, dictionary of list of dictionaries, named tuple (it's a subclass), sqlite, redundancy... I didn't believe my eyes. What else ?
"It might well be that dictionaries with tuples as keys are not the proper way to handle this situation."
"my gut feeling is that a database is overkill for the OP's needs; "
Yeah! I thought
So, in my opinion, a list of tuples is plenty enough :
from operator import itemgetter
li = [ ('banana', 'blue' , 24) ,
('apple', 'green' , 12) ,
('strawberry', 'blue' , 16 ) ,
('banana', 'yellow' , 13) ,
('apple', 'gold' , 3 ) ,
('pear', 'yellow' , 10) ,
('strawberry', 'orange' , 27) ,
('apple', 'blue' , 21) ,
('apple', 'silver' , 0 ) ,
('strawberry', 'green' , 4 ) ,
('banana', 'brown' , 14) ,
('strawberry', 'yellow' , 31) ,
('apple', 'pink' , 9 ) ,
('strawberry', 'gold' , 0 ) ,
('pear', 'gold' , 66) ,
('apple', 'yellow' , 9 ) ,
('pear', 'brown' , 5 ) ,
('strawberry', 'pink' , 8 ) ,
('apple', 'purple' , 7 ) ,
('pear', 'blue' , 51) ,
('chesnut', 'yellow', 0 ) ]
print set( u[1] for u in li ),': all potential colors'
print set( c for f,c,n in li if n!=0),': all effective colors'
print [ c for f,c,n in li if f=='banana' ],': all potential colors of bananas'
print [ c for f,c,n in li if f=='banana' and n!=0],': all effective colors of bananas'
print
print set( u[0] for u in li ),': all potential fruits'
print set( f for f,c,n in li if n!=0),': all effective fruits'
print [ f for f,c,n in li if c=='yellow' ],': all potential fruits being yellow'
print [ f for f,c,n in li if c=='yellow' and n!=0],': all effective fruits being yellow'
print
print len(set( u[1] for u in li )),': number of all potential colors'
print len(set(c for f,c,n in li if n!=0)),': number of all effective colors'
print len( [c for f,c,n in li if f=='strawberry']),': number of potential colors of strawberry'
print len( [c for f,c,n in li if f=='strawberry' and n!=0]),': number of effective colors of strawberry'
print
# sorting li by name of fruit
print sorted(li),' sorted li by name of fruit'
print
# sorting li by number
print sorted(li, key = itemgetter(2)),' sorted li by number'
print
# sorting li first by name of color and secondly by name of fruit
print sorted(li, key = itemgetter(1,0)),' sorted li first by name of color and secondly by name of fruit'
print
result
set(['blue', 'brown', 'gold', 'purple', 'yellow', 'pink', 'green', 'orange', 'silver']) : all potential colors
set(['blue', 'brown', 'gold', 'purple', 'yellow', 'pink', 'green', 'orange']) : all effective colors
['blue', 'yellow', 'brown'] : all potential colors of bananas
['blue', 'yellow', 'brown'] : all effective colors of bananas
set(['strawberry', 'chesnut', 'pear', 'banana', 'apple']) : all potential fruits
set(['strawberry', 'pear', 'banana', 'apple']) : all effective fruits
['banana', 'pear', 'strawberry', 'apple', 'chesnut'] : all potential fruits being yellow
['banana', 'pear', 'strawberry', 'apple'] : all effective fruits being yellow
9 : number of all potential colors
8 : number of all effective colors
6 : number of potential colors of strawberry
5 : number of effective colors of strawberry
[('apple', 'blue', 21), ('apple', 'gold', 3), ('apple', 'green', 12), ('apple', 'pink', 9), ('apple', 'purple', 7), ('apple', 'silver', 0), ('apple', 'yellow', 9), ('banana', 'blue', 24), ('banana', 'brown', 14), ('banana', 'yellow', 13), ('chesnut', 'yellow', 0), ('pear', 'blue', 51), ('pear', 'brown', 5), ('pear', 'gold', 66), ('pear', 'yellow', 10), ('strawberry', 'blue', 16), ('strawberry', 'gold', 0), ('strawberry', 'green', 4), ('strawberry', 'orange', 27), ('strawberry', 'pink', 8), ('strawberry', 'yellow', 31)] sorted li by name of fruit
[('apple', 'silver', 0), ('strawberry', 'gold', 0), ('chesnut', 'yellow', 0), ('apple', 'gold', 3), ('strawberry', 'green', 4), ('pear', 'brown', 5), ('apple', 'purple', 7), ('strawberry', 'pink', 8), ('apple', 'pink', 9), ('apple', 'yellow', 9), ('pear', 'yellow', 10), ('apple', 'green', 12), ('banana', 'yellow', 13), ('banana', 'brown', 14), ('strawberry', 'blue', 16), ('apple', 'blue', 21), ('banana', 'blue', 24), ('strawberry', 'orange', 27), ('strawberry', 'yellow', 31), ('pear', 'blue', 51), ('pear', 'gold', 66)] sorted li by number
[('apple', 'blue', 21), ('banana', 'blue', 24), ('pear', 'blue', 51), ('strawberry', 'blue', 16), ('banana', 'brown', 14), ('pear', 'brown', 5), ('apple', 'gold', 3), ('pear', 'gold', 66), ('strawberry', 'gold', 0), ('apple', 'green', 12), ('strawberry', 'green', 4), ('strawberry', 'orange', 27), ('apple', 'pink', 9), ('strawberry', 'pink', 8), ('apple', 'purple', 7), ('apple', 'silver', 0), ('apple', 'yellow', 9), ('banana', 'yellow', 13), ('chesnut', 'yellow', 0), ('pear', 'yellow', 10), ('strawberry', 'yellow', 31)] sorted li first by name of color and secondly by name of fruit
Remember there are more status codes than those defined in the HTTP/1.1 RFCs, the IANA registry is at http://www.iana.org/assignments/http-status-codes. For the case you mentioned status code 507 sounds right.
The solution that worked for me is the following one given..
I selected the particular project> right click >Build path>configure Build path> Libraries> I noticed that JRE system Library was showing(Unbound) hence..
selected that Library>click on Remove>click on Apply>click on add Library>JRE system Library>next>workspace default JRE>click on Finish>Apply>ok.
now you will not see these exclamation icon in your project.
To get e.g the value from column 'test' and row 1 it works like
df[['test']].values[0][0]
as only df[['test']].values[0]
gives back a array
data.removeAll(data);
will do the work, I think.
Add them as parameters to setInterval:
setInterval(funca, 500, 10, 3);
The syntax in your question uses eval, which is not recommended practice.
When connect to https
I got this error too, I add this line before HttpClient httpClient = new HttpClient();
and connect successfully:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
I know it from This Answer and Another Similar Anwser and the comment mentions:
This is a hack useful in development so putting a #if DEBUG #endif statement around it is the least you should do to make this safer and stop this ending up in production
Besides, I didn't try the method in Another Answer that use new X509Certificate()
or new X509Certificate2()
to make a Certificate, I'm not sure simply create by new()
will work or not.
EDIT: Some References:
Create a Self-Signed Server Certificate in IIS 7
Import and Export SSL Certificates in IIS 7
Best practices for using ServerCertificateValidationCallback
I find value of Thumbprint is equal to x509certificate.GetCertHashString()
:
I got to know about AndroidX from this Android Dev Summit video. The summarization is -
If you don't have bs-config.json
, you can change the port inside the lite-server module. Go to node_modules/lite-server/lib/config-defaults.js
in your project, then add the port in "modules.export" like this.
module.export {
port :8000, // to any available port
...
}
Then you can restart the server.
if you don't want to create an explicitly a js file but still want to test your javascript code, you can use snippets to run your JS code.
Follow the steps here:
This is the easy solution
Replace .price-input input.quantity with the class of your input feild
$(".price-input input.quantity").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
I can across this question because I was looking to implement a simple CloneObject method for arbitrary class (with a default constructor)
With generic method you can require that the type implements New().
Public Function CloneObject(Of T As New)(ByVal src As T) As T
Dim result As T = Nothing
Dim cloneable = TryCast(src, ICloneable)
If cloneable IsNot Nothing Then
result = cloneable.Clone()
Else
result = New T
CopySimpleProperties(src, result, Nothing, "clone")
End If
Return result
End Function
With non-generic assume the type has a default constructor and catch an exception if it doesn't.
Public Function CloneObject(ByVal src As Object) As Object
Dim result As Object = Nothing
Dim cloneable As ICloneable
Try
cloneable = TryCast(src, ICloneable)
If cloneable IsNot Nothing Then
result = cloneable.Clone()
Else
result = Activator.CreateInstance(src.GetType())
CopySimpleProperties(src, result, Nothing, "clone")
End If
Catch ex As Exception
Trace.WriteLine("!!! CloneObject(): " & ex.Message)
End Try
Return result
End Function
Even though this solution might seem obvious, I just wanted to post it here so the next guy will google it faster.
If you still want to have the model as a parameter in the method, you can create a DelegatingHandler
to buffer the content.
internal sealed class BufferizingHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
await request.Content.LoadIntoBufferAsync();
var result = await base.SendAsync(request, cancellationToken);
return result;
}
}
And add it to the global message handlers:
configuration.MessageHandlers.Add(new BufferizingHandler());
This solution is based on the answer by Darrel Miller.
This way all the requests will be buffered.
Ondrasej is the "most right" here, IMO.
There are also gui-er ways to do it, without resorting to Xcode. I like TryC.
Mac OS X includes Developer Tools, a developing environment for making Macintosh applications. However, if someone wants to study programming using C, Xcode is too big and too complicated for beginners, to write a small sample program. TryC is very suitable for beginners.
You don't need to launch a huge Xcode application, or type unfamiliar commands in Terminal. Using TryC, you can write, compile and run a C, C++ and Ruby program just like TextEdit. It's only available to compile one source code file but it's enough for trying sample programs.
lambda
is an anonymous function, it is equivalent to:
def func(p):
return p.totalScore
Now max
becomes:
max(players, key=func)
But as def
statements are compound statements they can't be used where an expression is required, that's why sometimes lambda
's are used.
Note that lambda
is equivalent to what you'd put in a return statement of a def
. Thus, you can't use statements inside a lambda
, only expressions are allowed.
What does max
do?
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.
So, it simply returns the object that is the largest.
How does key
work?
By default in Python 2 key
compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).
To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key
argument.
Example 1:
A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.
>>> lis = ['1', '100', '111', '2']
Here max
compares the items using their original values (strings are compared lexicographically so you'd get '2'
as output) :
>>> max(lis)
'2'
To compare the items by their integer value use key
with a simple lambda
:
>>> max(lis, key=lambda x:int(x)) # compare `int` version of each item
'111'
Example 2: Applying max
to a list of tuples.
>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]
By default max
will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:
>>> max(lis)
(4, 'e')
But, what if you wanted to compare each item by the value at index 1? Simple: use lambda
:
>>> max(lis, key = lambda x: x[1])
(-1, 'z')
Comparing items in an iterable that contains objects of different type:
List with mixed items:
lis = ['1','100','111','2', 2, 2.57]
In Python 2 it is possible to compare items of two different types:
>>> max(lis) # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x)) # compare integer version of each item
'111'
But in Python 3 you can't do that any more:
>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
max(lis)
TypeError: unorderable types: int() > str()
But this works, as we are comparing integer version of each object:
>>> max(lis, key=lambda x: int(x)) # or simply `max(lis, key=int)`
'111'
Why wouldn't the user just hit the home button? Then they can exit your app from any of your activities, not just a specific one.
If you are worried about your application continuing to do something in the background. Make sure to stop it in the relevant onPause and onStop commands (which will get triggered when the user presses Home).
If your issue is that you want the next time the user clicks on your app for it to start back at the beginning, I recommend putting some kind of menu item or UI button on the screen that takes the user back to the starting activity of your app. Like the twitter bird in the official twitter app, etc.
Type the values in single cells, because google spreadsheet cant handle duration formats at all, in any way shape or form. Or you have to learn to make scripts and graduate as a chopper pilot. that is also a option.
The below query will do for Orale DB:
select distinct(city) from station where upper(substr(city, 1,1)) in ('A','E','I','O','U') and upper(substr(city, length(city),1)) in ('A','E','I','O','U');
Otherwise you may:
header("Content-type: application/x-download");
header("Content-Transfer-Encoding: binary");
header("Content-disposition: attachment; filename=".$fileName."");
header("Cache-control: private");
echo utf8_decode($output);
One common way is to add the image to a QLabel
widget using QLabel::setPixmap()
, and then display the QLabel
as you would any other widget. Example:
#include <QtGui>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QPixmap pm("your-image.jpg");
QLabel lbl;
lbl.setPixmap(pm);
lbl.show();
return app.exec();
}
I found circular-json library on github and it worked well for my problem.
Some good features I found useful:
This code worked for me:
var updatedText = text.Normalize(NormalizationForm.FormD)
.Where(c => CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
.ToArray();
However, please don't do this with names. It's not only an insult to people with umlauts/accents in their name, it can also be dangerously wrong in certain situations (see below). There are alternative writings instead of just removing the accent.
Furthermore, it's simply wrong and dangerous, e.g. if the user has to provide his name exactly how it occurs on the passport.
For example my name is written Zuberbühler
and in the machine readable part of my passport you will find Zuberbuehler
. By removing the umlaut, the name will not match with either part. This can lead to issues for the users.
You should rather disallow umlauts/accent in an input form for names so the user can write his name correctly without its umlaut or accent.
Practical example, if the web service to apply for ESTA (https://www.application-esta.co.uk/special-characters-and) would use above code instead of transforming umlauts correctly, the ESTA application would either be refused or the traveller will have problems with the American Border Control when entering the States.
Another example would be flight tickets. Assuming you have a flight ticket booking web application, the user provides his name with an accent and your implementation is just removing the accents and then using the airline's web service to book the ticket! Your customer may not be allowed to board since the name does not match to any part of his/her passport.
Without the update-and-join notation (not all DBMS support that), use:
UPDATE QuestionTrackings
SET QuestionID = (SELECT QuestionID
FROM AnswerTrackings
WHERE AnswerTrackings.AnswerID = QuestionTrackings.AnswerID)
WHERE QuestionID IS NULL
AND EXISTS(SELECT QuestionID
FROM AnswerTrackings
WHERE AnswerTrackings.AnswerID = QuestionTrackings.AnswerID)
Often in a query like this, you need to qualify the WHERE clause with an EXISTS clause that contains the sub-query. This prevents the UPDATE from trampling over rows where there is no match (usually nulling all the values). In this case, since a missing question ID would change the NULL to NULL, it arguably doesn't matter.
Hint: break up the 32-bit integer to 4 8-bit integers, and print them out.
Something along the lines of this (not compiled, YMMV):
int i = 0xDEADBEEF; // some 32-bit integer
printf("%i.%i.%i.%i",
(i >> 24) & 0xFF,
(i >> 16) & 0xFF,
(i >> 8) & 0xFF,
i & 0xFF);
With the Visual Studio closed, I deleted the temporary folder iisexpress
in: C:\Users\<your_user>\AppData\Local\Temp\iisexpress
.
The key difference in a nutshell is that reset
moves the current branch reference, while checkout
does not (it moves HEAD).
As the Pro Git book explains under Reset Demystified,
The first thing
reset
will do is move what HEAD points to. This isn’t the same as changing HEAD itself (which is whatcheckout
does);reset
moves the branch that HEAD is pointing to. This means if HEAD is set to themaster
branch (i.e. you’re currently on themaster
branch), runninggit reset 9e5e6a4
will start by makingmaster
point to9e5e6a4
. [emphasis added]
See also VonC's answer for a very helpful text and diagram excerpt from the same article, which I won't duplicate here.
Of course there are a lot more details about what effects checkout
and reset
can have on the index and the working tree, depending on what parameters are used. There can be lots of similarities and differences between the two commands. But as I see it, the most crucial difference is whether they move the tip of the current branch.
try doing this
<div style="position: absolute;top: 32px; left: 430px;" id="outerFilterDiv">
<input name="filterTextField" type="text" id="filterTextField" tabindex="2" style="width: 140px;
position: absolute; top: 1px; left: 1px; z-index: 2;border:none;" />
<div style="position: absolute;" id="filterDropdownDiv">
<select name="filterDropDown" id="filterDropDown" tabindex="1000"
onchange="DropDownTextToBox(this,'filterTextField');" style="position: absolute;
top: 0px; left: 0px; z-index: 1; width: 165px;">
<option value="-1" selected="selected" disabled="disabled">-- Select Column Name --</option>
</select>
please look at following example fiddle
There are no implicit copies made in java via the assignment operator. Variables contain a reference value (pointer) and when you use =
you're only coping that value.
In order to preserve the contents of myTempObject
you would need to make a copy of it.
This can be done by creating a new ArrayList
using the constructor that takes another ArrayList
:
ArrayList<Object> myObject = new ArrayList<Object>(myTempObject);
Edit: As Bohemian points out in the comments below, is this what you're asking? By doing the above, both ArrayList
s (myTempObject
and myObject
) would contain references to the same objects. If you actually want a new list that contains new copies of the objects contained in myTempObject
then you would need to make a copy of each individual object in the original ArrayList
also this should work (not tested):
SELECT u.* FROM room u JOIN facilities_r fu ON fu.id_uc = u.id_uc AND u.id_fu IN(4,3) WHERE 1 AND vizibility = 1 GROUP BY id_uc ORDER BY u_premium desc , id_uc desc
If u.id_fu is a numeric field then you can remove the ' around them. The same for vizibility. Only if the field is a text field (data type char, varchar or one of the text-datatype e.g. longtext) then the value has to be enclosed by ' or even ".
Also I and Oracle too recommend to enclose table and field names in backticks. So you won't get into trouble if a field name contains a keyword.
I was able to fix the sub-menu's always pinning to the top of the parent menu from Andres's answer with the following addition:
.dropdown-menu li {
position: relative;
}
I also add an icon "icon-chevron-right" on items which contain menu sub-menus, and change the icon from black to white on hover (to compliment the text changing to white and look better with the selected blue background).
Here is the full less/css change (replace the above with this):
.dropdown-menu li {
position: relative;
[class^="icon-"] {
float: right;
}
&:hover {
// Switch to white icons on hover
[class^="icon-"] {
background-image: url("../img/glyphicons-halflings-white.png");
}
}
}
private - encapsulations in class/scope/struct ect'.
internal - encapsulation in assemblies.
This should do it for you ...
from pyspark.sql.types import FloatType
from pyspark.sql.functions import randn, rand, lit, coalesce, col
import pyspark.sql.functions as F
df_1 = sqlContext.range(0, 6)
df_2 = sqlContext.range(3, 10)
df_1 = df_1.select("id", lit("old").alias("source"))
df_2 = df_2.select("id")
df_1.show()
df_2.show()
df_3 = df_1.alias("df_1").join(df_2.alias("df_2"), df_1.id == df_2.id, "outer")\
.select(\
[coalesce(df_1.id, df_2.id).alias("id")] +\
[col("df_1." + c) for c in df_1.columns if c != "id"])\
.sort("id")
df_3.show()
You can use $timeout
to prevent the error.
$timeout(function () {
var scope = angular.element($("#myController")).scope();
scope.myMethod();
scope.$scope();
}, 1);
+ new Date()
A unary operator like plus
triggers the valueOf
method in the Date
object and it returns the timestamp (without any alteration).
Details:
On almost all current browsers you can use Date.now()
to get the UTC timestamp in milliseconds; a notable exception to this is IE8 and earlier (see compatibility table).
You can easily make a shim for this, though:
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
To get the timestamp in seconds, you can use:
Math.floor(Date.now() / 1000)
Or alternatively you could use:
Date.now() / 1000 | 0
Which should be slightly faster, but also less readable (also see this answer).
I would recommend using Date.now()
(with compatibility shim). It's slightly better because it's shorter & doesn't create a new Date
object. However, if you don't want a shim & maximum compatibility, you could use the "old" method to get the timestamp in milliseconds:
new Date().getTime()
Which you can then convert to seconds like this:
Math.round(new Date().getTime()/1000)
And you can also use the valueOf
method which we showed above:
new Date().valueOf()
Timestamp in Milliseconds
var timeStampInMs = window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now();_x000D_
_x000D_
console.log(timeStampInMs, Date.now());
_x000D_
Some cases just worked when I used Math.log10:
public static double log2(int n)
{
return (Math.log10(n) / Math.log10(2));
}
Here is my PHP solution, 100% Task Score, 100% correctness, and 100% performance. First we iterate and we store all positive elements, then we check if they exist,
function solution($A) {
$B = [];
foreach($A as $a){
if($a > 0) $B[] = $a;
}
$i = 1;
$last = 0;
sort($B);
foreach($B as $b){
if($last == $b) $i--; // Check for repeated elements
else if($i != $b) return $i;
$i++;
$last = $b;
}
return $i;
}
I think its one of the clears and simples functions here, the logic can be applied in all the other languages.
Normal behaviour with NULL is that any operation including a NULL yields a NULL...
- 9 * NULL = NULL
- NULL + '' = NULL
- etc
To overcome this use ISNULL or COALESCE to replace any instances of NULL with something else..
SELECT (ISNULL(field1,'') + '' + ISNULL(field2,'') + '' + ISNULL(field3,'')) FROM table1
I think your problem is that your initially last element next attribute isn't being changed becuase of your condition
if(next == null)
return;
Is at the beginning of your loop.
I would move it right after tmp.next has been assigned:
while(tmp != null){
tmp.next = before;
if(next == null)
return;
before = tmp;
tmp = next;
next = next.next;
}
Set the "AutoSizeColumnsMode" property to "Fill".. By default it is set to 'NONE'. Now columns will be filled across the DatagridView. Then you can set the width of other columns accordingly.
DataGridView1.Columns[0].Width=100;// The id column
DataGridView1.Columns[1].Width=200;// The abbrevation columln
//Third Colulmns 'description' will automatically be resized to fill the remaining
//space
It's not only about public or private methods or functions, it is about implementation details. Private functions are just one aspect of implementation details.
Unit-testing, after all, is a white box testing approach. For example, whoever uses coverage analysis to identify parts of the code that have been neglected in testing so far, goes into the implementation details.
A) Yes, you should be testing implementation details:
Think of a sort function which for performance reasons uses a private implementation of BubbleSort if there are up to 10 elements, and a private implementation of a different sort approach (say, heapsort) if there are more than 10 elements. The public API is that of a sort function. Your test suite, however, better makes use of the knowledge that there are actually two sort algorithms used.
In this example, surely, you could perform the tests on the public API. This would, however, require to have a number of test cases that execute the sort function with more than 10 elements, such that the heapsort algorithm is sufficiently well tested. The existence of such test cases alone is an indication that the test suite is connected to the implementation details of the function.
If the implementation details of the sort function change, maybe in the way that the limit between the two sorting algorithms is shifted or that heapsort is replaced by mergesort or whatever: The existing tests will continue to work. Their value nevertheless is then questionable, and they likely need to be reworked to better test the changed sort function. In other words, there will be a maintenance effort despite the fact that tests were on the public API.
B) How to test implementation details
One reason why many people argue one should not test private functions or implementation details is, that the implementation details are more likely to change. This higher likelyness of change at least is one of the reasons for hiding implementation details behind interfaces.
Now, assume that the implementation behind the interface contains larger private parts for which individual tests on the internal interface might be an option. Some people argue, these parts should not be tested when private, they should be turned into something public. Once public, unit-testing that code would be OK.
This is interesting: While the interface was internal, it was likely to change, being an implementation detail. Taking the same interface, making it public does some magic transformation, namely turning it into an interface that is less likely to change. Obviously there is some flaw in this argumentation.
But, there is nevertheless some truth behind this: When testing implementation details, in particular using internal interfaces, one should strive to use interfaces that are likely to remain stable. Whether some interface is likely to be stable is, however, not simply decidable based on whether it is public or private. In the projects from world I have been working in for some time, public interfaces also often enough change, and many private interfaces have remained untouched for ages.
Still, it is a good rule of thumb to use the "front door first" (see http://xunitpatterns.com/Principles%20of%20Test%20Automation.html). But keep in mind that it is called "front door first" and not "front door only".
C) Summary
Test also the implementation details. Prefer testing on stable interfaces (public or private). If implementation details change, also tests on the public API need to be revised. Turning something private into public does not magically change its stability.
I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.
you should add plug in to your local setting of firefox in your user home
vladimir@shinsengumi ~/.mozilla/plugins $ pwd
/home/vladimir/.mozilla/plugins
vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
lrwxrwxrwx 1 vladimir vladimir 60 Jan 1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so
Use this syntax:
obj[name]
Note that obj.x
is the same as obj["x"]
for all valid JS identifiers, but the latter form accepts all string as keys (not just valid identifiers).
obj["Hey, this is ... neat?"] = 42
If you want to fire the event only on changes of your input use:
$('.s').bind('input', function(){
console.log("search!");
doSearch();
});
Another way to pass named parameters to Bash... is passing by reference. This is supported as of Bash 4.0
#!/bin/bash
function myBackupFunction(){ # directory options destination filename
local directory="$1" options="$2" destination="$3" filename="$4";
echo "tar cz ${!options} ${!directory} | ssh root@backupserver \"cat > /mnt/${!destination}/${!filename}.tgz\"";
}
declare -A backup=([directory]=".." [options]="..." [destination]="backups" [filename]="backup" );
myBackupFunction backup[directory] backup[options] backup[destination] backup[filename];
An alternative syntax for Bash 4.3 is using a nameref.
Although the nameref is a lot more convenient in that it seamlessly dereferences, some older supported distros still ship an older version, so I won't recommend it quite yet.
Add this in MainActivity.
Intent intent = new Intent(getApplicationContext(), Heightimage.class);
startActivity(intent);
I modified the script by Nicolay77 to output the database to stdout (the usual way of unix scripts) so that I could output the data to text file or pipe it to any program I want. The resulting script is a bit simpler and works well.
Some examples:
./mdb_to_mysql.sh database.mdb > data.sql
./mdb_to_mysql.sh database.mdb | mysql destination-db -u user -p
Here is the modified script (save to mdb_to_mysql.sh)
#!/bin/bash
TABLES=$(mdb-tables -1 $1)
for t in $TABLES
do
echo "DROP TABLE IF EXISTS $t;"
done
mdb-schema $1 mysql
for t in $TABLES
do
mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t
done
The PHP equivalent is time()
: http://php.net/manual/en/function.time.php
add {3,5}
to your expression which means length between 3 to 5
/^([a-zA-Z0-9_-]){3,5}$/
Add the following line in your .profile
file in your home directory (using vi ~/.profile
):
PATH=$PATH:/home/me/play
export PATH
Then, for the change to take effect, simply type in your terminal:
$ . ~/.profile
This is a C++11 solution for the general problem if "If I did X, would it compile?"
template<class> struct type_sink { typedef void type; }; // consumes a type, and makes it `void`
template<class T> using type_sink_t = typename type_sink<T>::type;
template<class T, class=void> struct has_to_string : std::false_type {}; \
template<class T> struct has_to_string<
T,
type_sink_t< decltype( std::declval<T>().toString() ) >
>: std::true_type {};
Trait has_to_string
such that has_to_string<T>::value
is true
if and only if T
has a method .toString
that can be invoked with 0 arguments in this context.
Next, I'd use tag dispatching:
namespace details {
template<class T>
std::string optionalToString_helper(T* obj, std::true_type /*has_to_string*/) {
return obj->toString();
}
template<class T>
std::string optionalToString_helper(T* obj, std::false_type /*has_to_string*/) {
return "toString not defined";
}
}
template<class T>
std::string optionalToString(T* obj) {
return details::optionalToString_helper( obj, has_to_string<T>{} );
}
which tends to be more maintainable than complex SFINAE expressions.
You can write these traits with a macro if you find yourself doing it alot, but they are relatively simple (a few lines each) so maybe not worth it:
#define MAKE_CODE_TRAIT( TRAIT_NAME, ... ) \
template<class T, class=void> struct TRAIT_NAME : std::false_type {}; \
template<class T> struct TRAIT_NAME< T, type_sink_t< decltype( __VA_ARGS__ ) > >: std::true_type {};
what the above does is create a macro MAKE_CODE_TRAIT
. You pass it the name of the trait you want, and some code that can test the type T
. Thus:
MAKE_CODE_TRAIT( has_to_string, std::declval<T>().toString() )
creates the above traits class.
As an aside, the above technique is part of what MS calls "expression SFINAE", and their 2013 compiler fails pretty hard.
Note that in C++1y the following syntax is possible:
template<class T>
std::string optionalToString(T* obj) {
return compiled_if< has_to_string >(*obj, [&](auto&& obj) {
return obj.toString();
}) *compiled_else ([&]{
return "toString not defined";
});
}
which is an inline compilation conditional branch that abuses lots of C++ features. Doing so is probably not worth it, as the benefit (of code being inline) is not worth the cost (of next to nobody understanding how it works), but the existence of that above solution may be of interest.
#import "MyViewController.h"
@interface MyViewController ()
@property (strong, nonatomic) NSTimer *timer;
@end
@implementation MyViewController
double timerInterval = 1.0f;
- (NSTimer *) timer {
if (!_timer) {
_timer = [NSTimer timerWithTimeInterval:timerInterval target:self selector:@selector(onTick:) userInfo:nil repeats:YES];
}
return _timer;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
-(void)onTick:(NSTimer*)timer
{
NSLog(@"Tick...");
}
@end
@Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")
Here Value is that object of model where you want to save your Selected Value
For adding borders try this, for example:
Range("C11").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("A15:D15").Borders(xlEdgeBottom).LineStyle = xlContinuous
Hope that syntax is correct because I've done this in C#.
Following are most common way of comparing dates
(my preference is Approach 1):
Approach 1: Using Date.before()
, Date.after()
and Date.equals(
)
if (date1.after(date2)) {
System.out.println("Date1 is after Date2");
}
if (date1.before(date2)) {
System.out.println("Date1 is before Date2");
}
if (date1.equals(date2)) {
System.out.println("Date1 is equal Date2");
}
Approach 2: Date.compareTo()
if (date1.compareTo(date2) > 0) {
System.out.println("Date1 is after Date2");
} else if (date1.compareTo(date2) < 0) {
System.out.println("Date1 is before Date2");
} else {
System.out.println("Date1 is equal to Date2");
}
Approach 3: Calender.before()
, Calender.after(
) and Calender.equals()
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
if (cal1.after(cal2)) {
System.out.println("Date1 is after Date2");
}
if (cal1.before(cal2)) {
System.out.println("Date1 is before Date2");
}
if (cal1.equals(cal2)) {
System.out.println("Date1 is equal Date2");
}
You have to use Convert.FromBase64String to turn a Base64 encoded string
into a byte[]
.
I'm not sure about the "@" used in the selector. At least with the latest jQuery, I had to remove the @ to get this to function with two different checkbox arrays, otherwise all checked items were selected for each array:
var items = [];
$("input[name='items[]']:checked").each(function(){items.push($(this).val());});
var about = [];
$("input[name='about[]']:checked").each(function(){about.push($(this).val());});
Now both, items and about work.
In recent Git (I'm using v2.15.1), the following will merge upstream submodule changes into the submodules recursively:
git submodule update --recursive --remote --merge
You may add --init
to initialize any uninitialized submodules and use --rebase
if you want to rebase instead of merge.
You need to commit the changes afterwards:
git add . && git commit -m 'Update submodules to latest revisions'
Are you sure you aren't pushing over SSH? Maybe check the email associated with your SSH key in bitbucket if you have one.
I think you cannot just delete the tables property what if this is actual production data, just delete the contents that dont affect the table schema.
You didn't specify what shell you are using, but with zsh you could use the =( )
construct to achieve this. Something along the lines of:
cp =(sed ... file; sync) file
=( )
is similar to >( )
but creates a temporary file which is automatically deleted when cp
terminates.
OK, considering that you are using Windows, the most simple way to do that is to use the standard ftp
tool bundled with it. I base the following solution on Windows XP, hoping it'll work as well (or with minor modifications) on other versions.
First of all, you need to create a batch (script) file for the ftp
program, containing instructions for it. Name it as you want, and put into it:
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
open ftp.myftpsite.com
login
pass
mget *
quit
The first line opens a connection to the ftp server at ftp.myftpsite.com
. The two following lines specify the login, and the password which ftp will ask for (replace login
and pass
with just the login and password, without any keywords). Then, you use mget *
to get all files. Instead of the *
, you can use any wildcard. Finally, you use quit
to close the ftp
program without interactive prompt.
If you needed to enter some directory first, add a cd
command before mget
. It should be pretty straightforward.
Finally, write that file and run ftp
like this:
ftp -i -s:yourscript
where -i
disables interactivity (asking before downloading files), and -s
specifies path to the script you created.
Sadly, file transfer over SSH is not natively supported in Windows. But for that case, you'd probably want to use PuTTy tools anyway. The one of particular interest for this case would be pscp
which is practically the PuTTy counter-part of the openssh scp
command.
The syntax is similar to copy
command, and it supports wildcards:
pscp -batch [email protected]:iiumlabs* .
If you authenticate using a key file, you should pass it using -i path-to-key-file
. If you use password, -pw pass
. It can also reuse sessions saved using PuTTy, using the load -load your-session-name
argument.
You have it, that's all. But so, basically, what's the point of unions?
You can put in the same location content of different types. You have to know the type of what you have stored in the union (so often you put it in a struct
with a type tag...).
Why is this important? Not really for space gains. Yes, you can gain some bits or do some padding, but that's not the main point anymore.
It's for type safety, it enables you to do some kind of 'dynamic typing': the compiler knows that your content may have different meanings and the precise meaning of how your interpret it is up to you at run-time. If you have a pointer that can point to different types, you MUST use a union, otherwise you code may be incorrect due to aliasing problems (the compiler says to itself "oh, only this pointer can point to this type, so I can optimize out those accesses...", and bad things can happen).
You cannot do it because you are already looping on it.
Inorder to avoid this situation use Iterator,which guarentees you to remove the element from list safely ...
List<Object> objs;
Iterator<Object> i = objs.iterator();
while (i.hasNext()) {
Object o = i.next();
//some condition
i.remove();
}
set intersection
and dict comprehension
can be used here
# the dictionary
d = {1:2, 3:4, 5:6, 7:8}
# the subset of keys I'm interested in
l = (1,5)
>>>{key:d[key] for key in set(l) & set(d)}
{1: 2, 5: 6}
As the accepted solution of @Shane is not supported in RStudio (see here) as of now (Sep 2015), I would like to add an advice to @James Thompson answer regarding workflow:
If you use SumatraPDF as viewer you do not need to close the PDF file before making changes to it. Sumatra does not put a opened file in read-only and thus does not prevent it from being overwritten. Therefore, once you opened your PDF file with Sumatra, changes out of RStudio (or any other R IDE) are immediately displayed in Sumatra.
First Way:
In Kotlin we can create a simple extension for view:
fun View.getLocationOnScreen(): Point
{
val location = IntArray(2)
this.getLocationOnScreen(location)
return Point(location[0],location[1])
}
And simply get coordinates:
val location = yourView.getLocationOnScreen()
val absX = location.x
val absY = location.y
Second Way:
The Second way is more simple :
fun View.absX(): Int
{
val location = IntArray(2)
this.getLocationOnScreen(location)
return location[0]
}
fun View.absY(): Int
{
val location = IntArray(2)
this.getLocationOnScreen(location)
return location[1]
}
and simply get absolute X by view.absX()
and Y by view.absY()
Kind of a hack because it's not really python doing anything special here, but if you run the export command in the same sub-shell, you will probably get the result you want.
import os
cmd = "export MY_DATA='1234'; echo $MY_DATA" # or whatever command
os.system(cmd)
I've also had this problem from a service reference that was out of date, even with the server & client on the same machine. Running 'Update Service Reference' will generally fix it if this is the issue.
As a note ,
for those who need to have null value for things other than "true" or "false" strings , you can use the function below
public Boolean tryParseBoolean(String inputBoolean)
{
if(!inputBoolean.equals("true")&&!inputBoolean.equals("false")) return null;
return Boolean.valueOf(inputBoolean);
}
MySQL use HAVING statement for this tasks.
Your query would look like this:
SELECT g.group_id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m USING(group_id)
GROUP BY g.group_id
HAVING members > 4
example when references have different names
SELECT g.id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m ON g.id = m.group_id
GROUP BY g.id
HAVING members > 4
Also, make sure that you set indexes inside your database schema for keys you are using in JOINS as it can affect your site performance.
The answers did not work for me. Maybe they were outdated.
Anyway, found this website, which does all the job for you, and even prevent you from needing to read the unclear-as-usual google documentation: http://www.classynemesis.com/projects/ytembed/
You can use :+
to append element to array and +:
to prepend it:
0 +: array :+ 4
should produce:
res3: Array[Int] = Array(0, 1, 2, 3, 4)
It's the same as with any other implementation of Seq
.
to set a div at position fixed you can use
position:fixed
top:0;
left:0;
width:100%;
height:50px; /* change me */
What you do here is called a JOIN
(although you do it implicitly because you select from multiple tables). This means, if you didn't put any conditions in your WHERE clause, you had all combinations of those tables. Only with your condition you restrict your join to those rows where the drink id matches.
But there are still X multiple rows in the result for every drink, if there are X photos with this particular drinks_id. Your statement doesn't restrict which photo(s) you want to have!
If you only want one row per drink, you have to tell SQL what you want to do if there are multiple rows with a particular drinks_id. For this you need grouping and an aggregate function. You tell SQL which entries you want to group together (for example all equal drinks_ids) and in the SELECT, you have to tell which of the distinct entries for each grouped result row should be taken. For numbers, this can be average, minimum, maximum (to name some).
In your case, I can't see the sense to query the photos for drinks if you only want one row. You probably thought you could have an array of photos in your result for each drink, but SQL can't do this. If you only want any photo and you don't care which you'll get, just group by the drinks_id (in order to get only one row per drink):
SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id
GROUP BY drinks_id
name price photo
fanta 5 ./images/fanta-1.jpg
dew 4 ./images/dew-1.jpg
In MySQL, we also have GROUP_CONCAT, if you want the file names to be concatenated to one single string:
SELECT name, price, GROUP_CONCAT(photo, ',')
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id
GROUP BY drinks_id
name price photo
fanta 5 ./images/fanta-1.jpg,./images/fanta-2.jpg,./images/fanta-3.jpg
dew 4 ./images/dew-1.jpg,./images/dew-2.jpg
However, this can get dangerous if you have ,
within the field values, since most likely you want to split this again on the client side. It is also not a standard SQL aggregate function.
You might want to try screenfly. It worked great for me.
I checked for similar answer, but those given here don't fit my needs. I find something that, from my point of view, is what you're looking for. The only possible black point is a security matter (or maybe not) since I don't know about security.
I suggest using Interface (no need to use Class with constructor and so...), since you only have to create something like :
public interface ActivityClass {
public static final String MYSTRING_1 = "STRING";
public static final int MYINT_1 = 1;
}
Then you can access everywhere within your classes by using the following:
int myInt = ActivityClass.MYINT_1;
String myString = ActivityClass.MYSTRING_1;