while(inFile1.hasNext()){
token1 = inFile1.nextLine();
// put each value into an array with String#split();
String[] numStrings = line.split(", ");
// parse number string into doubles
double[] nums = new double[numString.length];
for (int i = 0; i < nums.length; i++){
nums[i] = Double.parseDouble(numStrings[i]);
}
}
More elegant approach:
echo "Memory usage for PID <>:"; for mem in {Private,Rss,Shared,Swap,Pss};do grep $mem /proc/<pid>/smaps | awk -v mem_type="$mem" '{i=i+$2} END {print mem_type,"memory usage:"i}' ;done
You just need the jQuery UI effects-core (13KB), to enable the duration of the adding (just like Omar Tariq it pointed out)
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
To remove message on logcat, i add a subtitle to track. On windows, right click on track -> Property -> Details -> insert a text on subtitle. Done :)
To get cookies expire time, use this simple method.
<?php
//#############PART 1#############
//expiration time (a*b*c*d) <- change D corresponding to number of days for cookie expiration
$time = time()+(60*60*24*365);
$timeMemo = (string)$time;
//sets cookie with expiration time defined above
setcookie("testCookie", "" . $timeMemo . "", $time);
//#############PART 2#############
//this function will convert seconds to days.
function secToDays($sec){
return ($sec / 60 / 60 / 24);
}
//checks if cookie is set and prints out expiration time in days
if(isset($_COOKIE['testCookie'])){
echo "Cookie is set<br />";
if(round(secToDays((intval($_COOKIE['testCookie']) - time())),1) < 1){
echo "Cookie will expire today.";
}else{
echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['testCookie']) - time())),1) . " day(s)";
}
}else{
echo "not set...";
}
?>
You need to keep Part 1 and Part 2 in different files, otherwise you will get the same expire date everytime.
Figured it out
class AnimatedFlutterLogo extends StatefulWidget {
@override
State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
}
class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
Timer _timer;
FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;
_AnimatedFlutterLogoState() {
_timer = new Timer(const Duration(milliseconds: 400), () {
setState(() {
_logoStyle = FlutterLogoStyle.horizontal;
});
});
}
@override
void dispose() {
super.dispose();
_timer.cancel();
}
@override
Widget build(BuildContext context) {
return new FlutterLogo(
size: 200.0,
textColor: Palette.white,
style: _logoStyle,
);
}
}
put these two lines in your .bashrc file and run source ~/.bashrc
export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
For linux I did this.(For the first line)
export ANDROID_HOME=/home/$USER/Android/Sdk
Waking up a dead question here but the answers provided will not work with jdk 7 (I read somewhere that a bug is open for this for Oracle Engineers but not fixed yet). Along with the link that @Ryan provided, you will have to also add :
System.setProperty("jsse.enableSNIExtension", "false");
(Courtesy to many stackoverflow answers combined together to figure this out)
The complete code will look as follows which worked for me (without setting the system property the Client Config did not work for me):
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
public class ClientHelper
{
public static ClientConfig configureClient()
{
System.setProperty("jsse.enableSNIExtension", "false");
TrustManager[] certs = new TrustManager[]
{
new X509TrustManager()
{
@Override
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
}
};
SSLContext ctx = null;
try
{
ctx = SSLContext.getInstance("SSL");
ctx.init(null, certs, new SecureRandom());
}
catch (java.security.GeneralSecurityException ex)
{
}
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
ClientConfig config = new DefaultClientConfig();
try
{
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
new HostnameVerifier()
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
},
ctx));
}
catch (Exception e)
{
}
return config;
}
public static Client createClient()
{
return Client.create(ClientHelper.configureClient());
}
Now in 2017 with ASP.Net Core you can do it as explained here.
The Microsoft.AspNetCore.Session package provides middleware for managing session state.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Adds a default in-memory implementation of IDistributedCache.
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
}
From the Docs: Introduction to session and application state in ASP.NET Core
Already tested on a working project
You can actually try xhtml2pdf http://flask.pocoo.org/snippets/68/
You can use the overloaded constructor of DateTime
:
DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, DateTimeKind.Utc);
If you need to convert the dictionary to binary, you need to convert it to a string (JSON) as described in the previous answer, then you can convert it to binary.
For example:
my_dict = {'key' : [1,2,3]}
import json
def dict_to_binary(the_dict):
str = json.dumps(the_dict)
binary = ' '.join(format(ord(letter), 'b') for letter in str)
return binary
def binary_to_dict(the_binary):
jsn = ''.join(chr(int(x, 2)) for x in the_binary.split())
d = json.loads(jsn)
return d
bin = dict_to_binary(my_dict)
print bin
dct = binary_to_dict(bin)
print dct
will give the output
1111011 100010 1101011 100010 111010 100000 1011011 110001 101100 100000 110010 101100 100000 110011 1011101 1111101
{u'key': [1, 2, 3]}
The stack is just a way that programs and functions use memory.
The stack always confused me, so I made an illustration:
Hope it's more helpful than confusing.
Feel free to use the SVG image (CC0 licensed).
I think concat
is a nice way to do this. If they are present it uses the name attributes of the Series as the columns (otherwise it simply numbers them):
In [1]: s1 = pd.Series([1, 2], index=['A', 'B'], name='s1')
In [2]: s2 = pd.Series([3, 4], index=['A', 'B'], name='s2')
In [3]: pd.concat([s1, s2], axis=1)
Out[3]:
s1 s2
A 1 3
B 2 4
In [4]: pd.concat([s1, s2], axis=1).reset_index()
Out[4]:
index s1 s2
0 A 1 3
1 B 2 4
Note: This extends to more than 2 Series.
In my case, I have various layer groups so that users can show/hide clusters of like type markers. But, in any case you delete an individual marker by looping over your layer groups to find and delete it. While looping, search for a marker with a custom attribute, in my case a 'key', added when the marker was added to the layer group. Add your 'key' just like adding a title attribute. Later this is gotten an a layer option. When you find that match, you .removeLayer() and it gets rid of that particular marker. Hope that helps you out!
eventsLayerGroup.addLayer(L.marker([tag.latitude, tag.longitude],{title:tag.title, layer:tag.layer, timestamp:tag.timestamp, key:tag.key, bounceOnAdd: true, icon: L.AwesomeMarkers.icon({icon: 'vignette', markerColor: 'blue', prefix: '', iconColor: 'white'}) }).bindPopup(customPopup(tag),customOptions).on('click', markerClick));
function removeMarker(id){
var layerGroupsArray = [eventsLayerGroup,landmarksLayerGroup,travelerLayerGroup,marketplaceLayerGroup,myLayerGroup];
$.each(layerGroupsArray, function (key, value) {
value.eachLayer(function (layer) {
if(typeof value !== "undefined"){
if (layer.options.layer){
console.log(layer.options.key);
console.log(id);
if (id === layer.options.key){
value.removeLayer(layer);
}
}
}
});
});
}
Here's a poor man's Linux/Python/Expect-like example based on this blog post: Upgrading simple shells to fully interactive TTYs. I needed this for old machines where I can't install Expect or add modules to Python.
Code:
(
echo 'scp [email protected]:./install.sh .'
sleep 5
echo 'scp-passwd'
sleep 5
echo 'exit'
) |
python -c 'import pty; pty.spawn("/usr/bin/bash")'
Output:
scp [email protected]:install.sh .
bash-4.2$ scp [email protected]:install.sh .
Password:
install.sh 100% 15KB 236.2KB/s 00:00
bash-4.2$ exit
exit
The full list of readyState
values is:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
(from https://www.w3schools.com/js/js_ajax_http_response.asp)
In practice you almost never use any of them except for 4.
Some XMLHttpRequest implementations may let you see partially received responses in responseText
when readyState==3
, but this isn't universally supported and shouldn't be relied upon.
To make reading of this page more valuable (for future search results) I made a list of libraries known to me.. As @CommonsWare mentioned there are super-similar questions/answers.. Anyway some libraries that can be used for making charts are:
Open Source:
Paid:
** - means I didn't try those so I can't really recommend it but other users suggested it..
You can use double quotes if ANSI SQL mode is enabled
CREATE TABLE IF NOT EXISTS misc_info
(
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
"key" TEXT UNIQUE NOT NULL,
value TEXT NOT NULL
)
ENGINE=INNODB;
or the proprietary back tick escaping otherwise. (Where to find the `
character on various keyboard layouts is covered in this answer)
CREATE TABLE IF NOT EXISTS misc_info
(
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
`key` TEXT UNIQUE NOT NULL,
value TEXT NOT NULL
)
ENGINE=INNODB;
export
in sh
and related shells (such as bash
), marks an environment variable to be exported to child-processes, so that the child inherits them.
The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.
That's because in C - integer on 32 bit machine doesn't mean that 32 bits are used for storing it, it may be 16 bits as well. It depends on the machine (implementation-dependent).
I had this problem as well, and tried to set the linear interpolator in xml without success. The solution that worked for me was to create the animation as a RotateAnimation in code.
RotateAnimation rotate = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(5000);
rotate.setInterpolator(new LinearInterpolator());
ImageView image= (ImageView) findViewById(R.id.imageView);
image.startAnimation(rotate);
You can style the option elements to some extent.
Using the * CSS tag you can style the options inside the box that is drawn by the system.
Example:
#ddlProducts *
{
border-radius:15px;
background-color:red;
}
That will look like this:
Object
input_data: Object price-row_122: " 35.1 " quantity-row_122: "1" success: true
virtualenv
is a very popular tool that creates isolated Python environments for Python libraries. If you're not familiar with this tool, I highly recommend learning it, as it is a very useful tool, and I'll be making comparisons to it for the rest of this answer.
It works by installing a bunch of files in a directory (eg: env/
), and then modifying the PATH
environment variable to prefix it with a custom bin
directory (eg: env/bin/
). An exact copy of the python
or python3
binary is placed in this directory, but Python is programmed to look for libraries relative to its path first, in the environment directory. It's not part of Python's standard library, but is officially blessed by the PyPA (Python Packaging Authority). Once activated, you can install packages in the virtual environment using pip
.
pyenv
is used to isolate Python versions. For example, you may want to test your code against Python 2.7, 3.6, 3.7 and 3.8, so you'll need a way to switch between them. Once activated, it prefixes the PATH
environment variable with ~/.pyenv/shims
, where there are special files matching the Python commands (python
, pip
). These are not copies of the Python-shipped commands; they are special scripts that decide on the fly which version of Python to run based on the PYENV_VERSION
environment variable, or the .python-version
file, or the ~/.pyenv/version
file. pyenv
also makes the process of downloading and installing multiple Python versions easier, using the command pyenv install
.
pyenv-virtualenv
is a plugin for pyenv
by the same author as pyenv
, to allow you to use pyenv
and virtualenv
at the same time conveniently. However, if you're using Python 3.3 or later, pyenv-virtualenv
will try to run python -m venv
if it is available, instead of virtualenv
. You can use virtualenv
and pyenv
together without pyenv-virtualenv
, if you don't want the convenience features.
virtualenvwrapper
is a set of extensions to virtualenv
(see docs). It gives you commands like mkvirtualenv
, lssitepackages
, and especially workon
for switching between different virtualenv
directories. This tool is especially useful if you want multiple virtualenv
directories.
pyenv-virtualenvwrapper
is a plugin for pyenv
by the same author as pyenv
, to conveniently integrate virtualenvwrapper
into pyenv
.
pipenv
aims to combine Pipfile
, pip
and virtualenv
into one command on the command-line. The virtualenv
directory typically gets placed in ~/.local/share/virtualenvs/XXX
, with XXX
being a hash of the path of the project directory. This is different from virtualenv
, where the directory is typically in the current working directory. pipenv
is meant to be used when developing Python applications (as opposed to libraries). There are alternatives to pipenv
, such as poetry
, which I won't list here since this question is only about the packages that are similarly named.
pyvenv
is a script shipped with Python 3 but deprecated in Python 3.6 as it had problems (not to mention the confusing name). In Python 3.6+, the exact equivalent is python3 -m venv
.
venv
is a package shipped with Python 3, which you can run using python3 -m venv
(although for some reason some distros separate it out into a separate distro package, such as python3-venv
on Ubuntu/Debian). It serves the same purpose as virtualenv
, but only has a subset of its features (see a comparison here). virtualenv
continues to be more popular than venv
, especially since the former supports both Python 2 and 3.
This is my personal recommendation for beginners: start by learning virtualenv
and pip
, tools which work with both Python 2 and 3 and in a variety of situations, and pick up other tools once you start needing them.
All the answers above couldn't solve the problem in my case. My ImageView
was placed in a customized UITableViewCell
. Therefore I had also call the layoutIfNeeded()
method from here. Example:
class NameTableViewCell:UITableViewCell,UITextFieldDelegate { ...
override func awakeFromNib() {
self.layoutIfNeeded()
profileImageView.layoutIfNeeded()
profileImageView.isUserInteractionEnabled = true
let square = profileImageView.frame.size.width < profileImageView.frame.height ? CGSize(width: profileImageView.frame.size.width, height: profileImageView.frame.size.width) : CGSize(width: profileImageView.frame.size.height, height: profileImageView.frame.size.height)
profileImageView.addGestureRecognizer(tapGesture)
profileImageView.layer.cornerRadius = square.width/2
profileImageView.clipsToBounds = true;
}
One other approach that we have taken successfully is to generate the WS client proxy code using wsimport (from Ant, as an Ant task) and specify the wsdlLocation attribute.
<wsimport debug="true" keep="true" verbose="false" target="2.1" sourcedestdir="${generated.client}" wsdl="${src}${wsdl.file}" wsdlLocation="${wsdl.file}">
</wsimport>
Since we run this for a project w/ multiple WSDLs, the script resolves the $(wsdl.file} value dynamically which is set up to be /META-INF/wsdl/YourWebServiceName.wsdl relative to the JavaSource location (or /src, depending on how you have your project set up). During the build proess, the WSDL and XSDs files are copied to this location and packaged in the JAR file. (similar to the solution described by Bhasakar above)
MyApp.jar
|__META-INF
|__wsdl
|__YourWebServiceName.wsdl
|__YourWebServiceName_schema1.xsd
|__YourWebServiceName_schmea2.xsd
Note: make sure the WSDL files are using relative refrerences to any imported XSDs and not http URLs:
<types>
<xsd:schema>
<xsd:import namespace="http://valueobject.common.services.xyz.com/" schemaLocation="YourWebService_schema1.xsd"/>
</xsd:schema>
<xsd:schema>
<xsd:import namespace="http://exceptions.util.xyz.com/" schemaLocation="YourWebService_schema2.xsd"/>
</xsd:schema>
</types>
In the generated code, we find this:
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2-b05-
* Generated source version: 2.1
*
*/
@WebServiceClient(name = "YourService", targetNamespace = "http://test.webservice.services.xyz.com/", wsdlLocation = "/META-INF/wsdl/YourService.wsdl")
public class YourService_Service
extends Service
{
private final static URL YOURWEBSERVICE_WSDL_LOCATION;
private final static WebServiceException YOURWEBSERVICE_EXCEPTION;
private final static QName YOURWEBSERVICE_QNAME = new QName("http://test.webservice.services.xyz.com/", "YourService");
static {
YOURWEBSERVICE_WSDL_LOCATION = com.xyz.services.webservice.test.YourService_Service.class.getResource("/META-INF/wsdl/YourService.wsdl");
WebServiceException e = null;
if (YOURWEBSERVICE_WSDL_LOCATION == null) {
e = new WebServiceException("Cannot find '/META-INF/wsdl/YourService.wsdl' wsdl. Place the resource correctly in the classpath.");
}
YOURWEBSERVICE_EXCEPTION = e;
}
public YourService_Service() {
super(__getWsdlLocation(), YOURWEBSERVICE_QNAME);
}
public YourService_Service(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
/**
*
* @return
* returns YourService
*/
@WebEndpoint(name = "YourServicePort")
public YourService getYourServicePort() {
return super.getPort(new QName("http://test.webservice.services.xyz.com/", "YourServicePort"), YourService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns YourService
*/
@WebEndpoint(name = "YourServicePort")
public YourService getYourServicePort(WebServiceFeature... features) {
return super.getPort(new QName("http://test.webservice.services.xyz.com/", "YourServicePort"), YourService.class, features);
}
private static URL __getWsdlLocation() {
if (YOURWEBSERVICE_EXCEPTION!= null) {
throw YOURWEBSERVICE_EXCEPTION;
}
return YOURWEBSERVICE_WSDL_LOCATION;
}
}
Perhaps this might help too. It's just a different approach that does not use the "catalog" approach.
Use a negative lookahead and a negative lookbehind:
> s = "one two 3.4 5,6 seven.eight nine,ten"
> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten']
In other words, you always split by \s
(whitespace), and only split by commas and periods if they are not followed (?!\d)
or preceded (?<!\d)
by a digit.
DEMO.
EDIT: As per @verdesmarald comment, you may want to use the following instead:
> s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"
> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5']
This will split "1.2,a,5"
into ["1.2", "a", "5"]
.
DEMO.
From CREATE FUNCTION
:
When a parameter of the function has a default value, the keyword
DEFAULT
must be specified when the function is called to retrieve the default value. This behavior is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value.
So you need to do:
SELECT dbo.fCalculateEstimateDate(647,DEFAULT)
For linux users, and to sum up and add to what others have said here, you should know the following:
Global variables are not evil. $CLASSPATH is specifically what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override).
The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:
export CLASSPATH=.
export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.
echo $CLASSPATH
is super handy, and what it returns should read like a colon-separated list of all the directories you want java looking in for what it needs to run your script.
Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html
I'd recommend using http://shapecatcher.com/ to help search for unicode characters. It allows you to draw the shape you're after, and then lists the closest matches to that shape.
Neither of them worked for me for some reason.
I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.
And finally this worked for me.
cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
connect.commit()
Yes, it does. The way to enable this depends on your version of Notepad++. On newer versions you can use:
Menu View ? Show Symbol ? *Show All Characters`
or
Menu View ? Show Symbol ? Show White Space and TAB
(Thanks to bers' comment and bkaid's answers below for these updated locations.)
On older versions you can look for:
Menu View ? Show all characters
or
Menu View ? Show White Space and TAB
While using string, the best possible way to print your message is:
#include <iostream>
#include <string>
using namespace std;
int main(){
string newInput;
getline(cin, newInput);
cout<<newInput;
return 0;
}
this can simply do the work instead of doing the method you adopted.
From the Intel's manual - Instruction Set Reference, the JE
and JZ
have the same opcode (74
for rel8 / 0F 84
for rel 16/32) also JNE
and JNZ
(75
for rel8 / 0F 85
for rel 16/32) share opcodes.
JE
and JZ
they both check for the ZF
(or zero flag), although the manual differs slightly in the descriptions of the first JE
rel8 and JZ
rel8 ZF
usage, but basically they are the same.
Here is an extract from the manual's pages 464, 465 and 467.
Op Code | mnemonic | Description
-----------|-----------|-----------------------------------------------
74 cb | JE rel8 | Jump short if equal (ZF=1).
74 cb | JZ rel8 | Jump short if zero (ZF ? 1).
0F 84 cw | JE rel16 | Jump near if equal (ZF=1). Not supported in 64-bit mode.
0F 84 cw | JZ rel16 | Jump near if 0 (ZF=1). Not supported in 64-bit mode.
0F 84 cd | JE rel32 | Jump near if equal (ZF=1).
0F 84 cd | JZ rel32 | Jump near if 0 (ZF=1).
75 cb | JNE rel8 | Jump short if not equal (ZF=0).
75 cb | JNZ rel8 | Jump short if not zero (ZF=0).
0F 85 cd | JNE rel32 | Jump near if not equal (ZF=0).
0F 85 cd | JNZ rel32 | Jump near if not zero (ZF=0).
If you just want direct subclasses then .__subclasses__()
works fine. If you want all subclasses, subclasses of subclasses, and so on, you'll need a function to do that for you.
Here's a simple, readable function that recursively finds all subclasses of a given class:
def get_all_subclasses(cls):
all_subclasses = []
for subclass in cls.__subclasses__():
all_subclasses.append(subclass)
all_subclasses.extend(get_all_subclasses(subclass))
return all_subclasses
I could not use localStorage
directly in the Firefox (v27) console. I got the error:
[Exception... "Component is not available" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: debugger eval code :: :: line 1" data: no]
What worked was:
window.content.localStorage
Unfortunately, MySQL doesn't support DEFAULT
parameter values, so:
CREATE PROCEDURE `blah`
(
myDefaultParam int DEFAULT 0
)
BEGIN
-- Do something here
END
returns the error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use
near 'DEFAULT 0) BEGIN END' at line 3
To work around this limitation, simply create additional procedures that assign default values to the original procedure:
DELIMITER //
DROP PROCEDURE IF EXISTS blah//
DROP PROCEDURE IF EXISTS blah2//
DROP PROCEDURE IF EXISTS blah1//
DROP PROCEDURE IF EXISTS blah0//
CREATE PROCEDURE blah(param1 INT UNSIGNED, param2 INT UNSIGNED)
BEGIN
SELECT param1, param2;
END;
//
CREATE PROCEDURE blah2(param1 INT UNSIGNED, param2 INT UNSIGNED)
BEGIN
CALL blah(param1, param2);
END;
//
CREATE PROCEDURE blah1(param1 INT UNSIGNED)
BEGIN
CALL blah2(param1, 3);
END;
//
CREATE PROCEDURE blah0()
BEGIN
CALL blah1(4);
END;
//
Then, running this:
CALL blah(1, 1);
CALL blah2(2, 2);
CALL blah1(3);
CALL blah0();
will return:
+--------+--------+
| param1 | param2 |
+--------+--------+
| 1 | 1 |
+--------+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
+--------+--------+
| param1 | param2 |
+--------+--------+
| 2 | 2 |
+--------+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
+--------+--------+
| param1 | param2 |
+--------+--------+
| 3 | 3 |
+--------+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
+--------+--------+
| param1 | param2 |
+--------+--------+
| 4 | 3 |
+--------+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Then, if you make sure to only use the blah2()
, blah1()
and blah0()
procedures, your code will not need to be immediately updated, when you add a third parameter to the blah()
procedure.
.val()
does not return an array from a DOM element: $('#fruit')
is going to find the element in the document with an ID of #fruit and get its value (if it has a value).
In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:
<body onload="parent.alertsize(document.body.scrollHeight);">
In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.
To that JavaScript function it sends how many pixels its (iframe) height is.
The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.
That's it, nothing else is needed.
But if you like to know some more small tricks keep on reading...
DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
}
</script>
to that script just add:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>
How you use the above script is easy:
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)
Complete holding page code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>
<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>
Complete iframe code: (this iframe named "theiframe.htm")
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight);
}
</script>
</head>
<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END
</body>
</html>
Unfortunately, Dictionary has problems with Model Binding in MVC. Read the full story here. Instead, create a custom model binder to get the Dictionary as a parameter for the controller action.
To solve your requirement, here is the working solution -
First create your ViewModels in following way. PersonModel can have list of RoleModels.
public class PersonModel
{
public List<RoleModel> Roles { get; set; }
public string Name { get; set; }
}
public class RoleModel
{
public string RoleName { get; set;}
public string Description { get; set;}
}
Then have a index action which will be serving basic index view -
public ActionResult Index()
{
return View();
}
Index view will be having following JQuery AJAX POST operation -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click1').click(function (e) {
var jsonObject = {
"Name" : "Rami",
"Roles": [{ "RoleName": "Admin", "Description" : "Admin Role"}, { "RoleName": "User", "Description" : "User Role"}]
};
$.ajax({
url: "@Url.Action("AddUser")",
type: "POST",
data: JSON.stringify(jsonObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
});
});
</script>
<input type="button" value="click1" id="click1" />
Index action posts to AddUser action -
[HttpPost]
public ActionResult AddUser(PersonModel model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
So now when the post happens you can get all the posted data in the model parameter of action.
Update:
For asp.net core, to get JSON data as your action parameter you should add the [FromBody]
attribute before your param name in your controller action. Note: if you're using ASP.NET Core 2.1, you can also use the [ApiController]
attribute to automatically infer the [FromBody] binding source for your complex action method parameters. (Doc)
Updated with feedback from Alan Moore
In PCRE and similar variants, you can actually create a regex that matches any line not containing a value:
^(?:(?!Andrea).)*$
This is called a tempered greedy token. The downside is that it doesn't perform well.
Here's a linearization option on simple data that uses tools from scikit learn.
Given
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import FunctionTransformer
np.random.seed(123)
# General Functions
def func_exp(x, a, b, c):
"""Return values from a general exponential function."""
return a * np.exp(b * x) + c
def func_log(x, a, b, c):
"""Return values from a general log function."""
return a * np.log(b * x) + c
# Helper
def generate_data(func, *args, jitter=0):
"""Return a tuple of arrays with random data along a general function."""
xs = np.linspace(1, 5, 50)
ys = func(xs, *args)
noise = jitter * np.random.normal(size=len(xs)) + jitter
xs = xs.reshape(-1, 1) # xs[:, np.newaxis]
ys = (ys + noise).reshape(-1, 1)
return xs, ys
transformer = FunctionTransformer(np.log, validate=True)
Code
Fit exponential data
# Data
x_samp, y_samp = generate_data(func_exp, 2.5, 1.2, 0.7, jitter=3)
y_trans = transformer.fit_transform(y_samp) # 1
# Regression
regressor = LinearRegression()
results = regressor.fit(x_samp, y_trans) # 2
model = results.predict
y_fit = model(x_samp)
# Visualization
plt.scatter(x_samp, y_samp)
plt.plot(x_samp, np.exp(y_fit), "k--", label="Fit") # 3
plt.title("Exponential Fit")
Fit log data
# Data
x_samp, y_samp = generate_data(func_log, 2.5, 1.2, 0.7, jitter=0.15)
x_trans = transformer.fit_transform(x_samp) # 1
# Regression
regressor = LinearRegression()
results = regressor.fit(x_trans, y_samp) # 2
model = results.predict
y_fit = model(x_trans)
# Visualization
plt.scatter(x_samp, y_samp)
plt.plot(x_samp, y_fit, "k--", label="Fit") # 3
plt.title("Logarithmic Fit")
Details
General Steps
x
, y
or both)np.exp()
) and fit to original dataAssuming our data follows an exponential trend, a general equation+ may be:
We can linearize the latter equation (e.g. y = intercept + slope * x) by taking the log:
Given a linearized equation++ and the regression parameters, we could calculate:
A
via intercept (ln(A)
)B
via slope (B
)Summary of Linearization Techniques
Relationship | Example | General Eqn. | Altered Var. | Linearized Eqn.
-------------|------------|----------------------|----------------|------------------------------------------
Linear | x | y = B * x + C | - | y = C + B * x
Logarithmic | log(x) | y = A * log(B*x) + C | log(x) | y = C + A * (log(B) + log(x))
Exponential | 2**x, e**x | y = A * exp(B*x) + C | log(y) | log(y-C) = log(A) + B * x
Power | x**2 | y = B * x**N + C | log(x), log(y) | log(y-C) = log(B) + N * log(x)
+Note: linearizing exponential functions works best when the noise is small and C=0. Use with caution.
++Note: while altering x data helps linearize exponential data, altering y data helps linearize log data.
In the specific case in your example, I'd use the STL algorithms to accomplish this.
#include <numeric>
sum = std::accumulate( polygon.begin(), polygon.end(), 0 );
For a more general, but still fairly simple case, I'd go with:
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
using namespace boost::lambda;
std::for_each( polygon.begin(), polygon.end(), sum += _1 );
Have you taken a look at the Intel Math Kernel Library? It claims to outperform even ATLAS. MKL can be used in Java through JNI wrappers.
To make an exact copy, permissions, ownership, and all use "-a" with "cp". "-r" will copy the contents of the files but not necessarily keep other things the same.
cp -av Source/* Dest/
(make sure Dest/ exists first)
If you want to repeatedly update from one to the other or make sure you also copy all dotfiles, rsync
is a great help:
rsync -av --delete Source/ Dest/
This is also "recoverable" in that you can restart it if you abort it while copying. I like "-v" because it lets you watch what is going on but you can omit it.
In ES6:
const ID_LENGTH = 36
const START_LETTERS_ASCII = 97 // Use 64 for uppercase
const ALPHABET_LENGTH = 26
const uniqueID = () => [...new Array(ID_LENGTH)]
.map(() => String.fromCharCode(START_LETTERS_ASCII + Math.random() * ALPHABET_LENGTH))
.join('')
Example:
> uniqueID()
> "bxppcnanpuxzpyewttifptbklkurvvetigra"
If you want to use SimpleDateFormat
, you could write:
private final SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
{ sdf.setTimeZone(TimeZone.getTimeZone("GMT")); }
private long parseTimeToMillis(final String time) throws ParseException
{ return sdf.parse("1970-01-01 " + time).getTime(); }
But a custom method would be much more efficient. SimpleDateFormat
, because of all its calendar support, time-zone support, daylight-savings-time support, and so on, is pretty slow. The slowness is worth it if you actually need some of those features, but since you don't, it might not be. (It depends how often you're calling this method, and whether efficiency is a concern for your application.)
Also, SimpleDateFormat
is non-thread-safe, which is sometimes a pain. (Without knowing anything about your application, I can't guess whether that matters.)
Personally, I'd probably write a custom method.
$_SERVER['HTTP_REFERER']
is the answer
It's easy, do this way
private static final int REQUEST_READ_PHONE_STATE = 110 , REQUEST_ACCESS_FINE_LOCATION = 111, REQUEST_WRITE_STORAGE = 112;
In your onCreate
//request permission
boolean hasPermissionPhoneState = (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermissionPhoneState) {
ActivityCompat.requestPermissions(LoginActivity.this,
new String[]{Manifest.permission.READ_PHONE_STATE},
REQUEST_READ_PHONE_STATE);
}
boolean hasPermissionLocation = (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
if (!hasPermissionLocation) {
ActivityCompat.requestPermissions(LoginActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_ACCESS_FINE_LOCATION);
}
boolean hasPermissionWrite = (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermissionWrite) {
ActivityCompat.requestPermissions(LoginActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
Then check result
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_READ_PHONE_STATE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(LoginActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show();
//reload my activity with permission granted or use the features what required the permission
finish();
startActivity(getIntent());
} else
{
Toast.makeText(LoginActivity.this, "The app was not allowed to get your phone state. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
case REQUEST_ACCESS_FINE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(LoginActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show();
//reload my activity with permission granted or use the features what required the permission
finish();
startActivity(getIntent());
} else
{
Toast.makeText(LoginActivity.this, "The app was not allowed to get your location. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
case REQUEST_WRITE_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(LoginActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show();
//reload my activity with permission granted or use the features what required the permission
finish();
startActivity(getIntent());
} else
{
Toast.makeText(LoginActivity.this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
If you have a class for each of your input box, then you can do it as
var checked = []
$('input.Booking').each(function ()
{
checked.push($(this).val());
});
Instead of sudo, try
su - username command
In my experience, sudo is not always available on RHEL systems, but su is, because su is part of the coreutils package whereas sudo is in the sudo package.
EDIT: This did/does work at the time I wrote it, but as Blexen pointed out, it's not in the spec.
Add an option like so:
<option default>Select Your Beverage</option>
The correct way:
<option selected="selected">Select Your Beverage</option>
Here's the NON-jQuery solution that instantly removes the address bar without scrolling. Also, it works when you rotate the browser's orientation.
function hideAddressBar(){
if(document.documentElement.scrollHeight<window.outerHeight/window.devicePixelRatio)
document.documentElement.style.height=(window.outerHeight/window.devicePixelRatio)+'px';
setTimeout(window.scrollTo(1,1),0);
}
window.addEventListener("load",function(){hideAddressBar();});
window.addEventListener("orientationchange",function(){hideAddressBar();});
It should work with the iPhone also, but I couldn't test this.
jQuery:
$('#container').append('<img src="/path/to/image.jpg"
width="16" height="16" alt="Test Image" title="Test Image" />');
I've found that this works even better because you don't have to worry about HTML escaping anything (which should be done in the above code, if the values weren't hard coded). It's also easier to read (from a JS perspective):
$('#container').append($('<img>', {
src : "/path/to/image.jpg",
width : 16,
height : 16,
alt : "Test Image",
title : "Test Image"
}));
1 workaround to solve this problem is:
Download the notebook which you are not able to save by going to: File --> Download as --> Notebook (ipynb).
Open the downloaded notebook by clicking on the downloaded file on the jupyter browser UI
Now, you should be able to save (or rename) this notebook from jupyter UI
First of all, you don't need to "clean up" string
s and int
s - they will be taken care of automatically by the garbage collector. The only thing that needs to be cleaned up in Dispose
are unmanaged resources or managed recources that implement IDisposable
.
However, assuming this is just a learning exercise, the recommended way to implement IDisposable
is to add a "safety catch" to ensure that any resources aren't disposed of twice:
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Clear all property values that maybe have been set
// when the class was instantiated
id = 0;
name = String.Empty;
pass = String.Empty;
}
// Indicate that the instance has been disposed.
_disposed = true;
}
}
isFinite(String(n)) returns true for n=0 or '0', '1.1' or 1.1,
but false for '1 dog' or '1,2,3,4', +- Infinity and any NaN values.
What I do usually after new installation is to modify the main css file where all visual styles are stored. I use Miniconda but location is similar with others C:\Miniconda3\Lib\site-packages\notebook\static\style\style.min.css
With some screens these resolutions are different and more than 1. To be on the safe side I change all to 98% so if I disconnect from my external screens on my laptop I still have 98% screen width.
Then just replace 1140px with 98% of the screen width.
@media (min-width: 1200px) {
.container {
width: 1140px;
}
}
After editing
@media (min-width: 1200px) {
.container {
width: 98%;
}
}
Save and restart your notebook
Update
Recently had to wider Jupyter cells on an environment it is installed, which led me to come back here and remind myself.
If you need to do it in virtual env you installed jupyter on. You can find the css file in this subdir
env/lib/python3.6/site-packages/notebook/static/style/stye.min.css
SELECT COUNT (COL_NAME)
FROM TABLE
WHERE TRIM (COL_NAME) IS NULL
or COL_NAME='NULL'
//Pour inserer :
$pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
$filetype = addslashes($_FILES['inputname']['type']);//pour le test
$namepdf = addslashes($_FILES['inputname']['name']);
if (substr($filetype, 0, 11) == 'application'){
$mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
}
//Pour afficher :
$row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
foreach($row as $result){
$file=$result['pdf'];
}
header('Content-type: application/pdf');
echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));
When you write a lambda expression, the argument list to the left of ->
can be either a parenthesized argument list (possibly empty), or a single identifier without any parentheses. But in the second form, the identifier cannot be declared with a type name. Thus:
this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));
is incorrect syntax; but
this.stops.stream().filter((Stop s)-> s.getStation().getName().equals(name));
is correct. Or:
this.stops.stream().filter(s -> s.getStation().getName().equals(name));
is also correct if the compiler has enough information to figure out the types.
Consider the following code:
class X():
def __init__(self):
print("X")
class Y(X):
def __init__(self):
# X.__init__(self)
super(Y, self).__init__()
print("Y")
class P(X):
def __init__(self):
super(P, self).__init__()
print("P")
class Q(Y, P):
def __init__(self):
super(Q, self).__init__()
print("Q")
Q()
If change constructor of Y
to X.__init__
, you will get:
X
Y
Q
But using super(Y, self).__init__()
, you will get:
X
P
Y
Q
And P
or Q
may even be involved from another file which you don't know when you writing X
and Y
. So, basically, you won't know what super(Child, self)
will reference to when you are writing class Y(X)
, even the signature of Y is as simple as Y(X)
. That's why super could be a better choice.
We can directly specify the destination file with the dest
option now. In the below example, the output json is stored into the /tmp/repo_version_file
- name: Get repository file repo_version model to set ambari_managed_repositories=false
uri:
url: 'http://<server IP>:8080/api/v1/stacks/HDP/versions/3.1/repository_versions/1?fields=operating_systems/*'
method: GET
force_basic_auth: yes
user: xxxxx
password: xxxxx
headers:
"X-Requested-By": "ambari"
"Content-type": "Application/json"
status_code: 200
dest: /tmp/repo_version_file
.gitkeep
is just a placeholder. A dummy file, so Git will not forget about the directory, since Git tracks only files.
If you want an empty directory and make sure it stays 'clean' for Git, create a .gitignore
containing the following lines within:
# .gitignore sample
###################
# Ignore all files in this dir...
*
# ... except for this one.
!.gitignore
If you desire to have only one type of files being visible to Git, here is an example how to filter everything out, except .gitignore and all .txt
files:
# .gitignore to keep just .txt files
###################################
# Filter everything...
*
# ... except the .gitignore...
!.gitignore
# ... and all text files.
!*.txt
('#' indicates comments.)
$first = doubleval($_POST['first']);
$second = doubleval($_POST['second']);
if($_POST['group1'] == 'add') {
echo "$first + $second = ".($first + $second);
}
// etc
I have a working codepen with left- and right-aligned nav links that all collapse into a responsive menu together using .justify-content-between
on the parent tag: https://codepen.io/epan/pen/bREVVW?editors=1000
<nav class="navbar navbar-toggleable-sm navbar-inverse bg-inverse">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbar" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Acme</a>
<div class="collapse navbar-collapse justify-content-between" id="navbar">
<div class="navbar-nav">
<a class="nav-item nav-link" href="#">Ball Bearings</a>
<a class="nav-item nav-link" href="#">TNT Boxes</a>
</div>
<div class="navbar-nav">
<a class="nav-item nav-link" href="#">Logout</a>
</div>
</div>
</nav>
I think natually do it is straightforward, whether Intellij IDEA or Android Studio, I always click new Java class menu, and then typing the class name, press Enter to create. after that, I manually typing "extends Activity" in the class file, and then import the class by shortcut key. finally, I also manually override the onCreate() method and invoke the setContentView() method.
If anyone else stumbles upon this answer like I did but for a different reason, you may check your Laravel DB charset/collation.
I was installing an application (Snipe-IT) and had configured the Laravel database config to use the following:
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_general_ci',
Removing mb4
from both strings fixed the issue, although I believe Antonio's answer is the real solution to the problem.
I think your question is a bit more general than I originally thought. type()
with one argument returns the type
or class
of the object. So if you have a = 'abc'
and use type(a)
this returns str
because the variable a
is a string. If b = 10
, type(b)
returns int
.
See also python documentation on type().
If you want a comparison you could use: if type(v) == h5py.h5r.Reference
(to check if it is a h5py.h5r.Reference
instance).
But it is recommended that one uses if isinstance(v, h5py.h5r.Reference)
but then also subclasses will evaluate to True
.
If you want to print the class use print v.__class__.__name__
.
More generally: You can compare if two instances have the same class by using type(v) is type(other_v)
or isinstance(v, other_v.__class__)
.
you cannot access array (php array) from js try
<?php
$array = array(1,2,3,4,5,6);
echo implode('~',$array);
?>
and js
$(document).ready( function() {
$('#prev').click(function() {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: 'id=testdata',
cache: false,
success: function(data) {
result=data.split('~');
$('#content1').html(result[0]);
},
});
});
});
you have to call set and add functions on chart object before calling redraw.
chart.xAxis[0].setCategories([2,4,5,6,7], false);
chart.addSeries({
name: "acx",
data: [4,5,6,7,8]
}, false);
chart.redraw();
I managed to use soap,wsdl and Node.js
You need to install soap with npm install soap
Create a node server called server.js
that will define soap service to be consumed by a remote client. This soap service computes Body Mass Index based on weight(kg) and height(m).
const soap = require('soap');
const express = require('express');
const app = express();
/**
* this is remote service defined in this file, that can be accessed by clients, who will supply args
* response is returned to the calling client
* our service calculates bmi by dividing weight in kilograms by square of height in metres
*/
const service = {
BMI_Service: {
BMI_Port: {
calculateBMI(args) {
//console.log(Date().getFullYear())
const year = new Date().getFullYear();
const n = args.weight / (args.height * args.height);
console.log(n);
return { bmi: n };
}
}
}
};
// xml data is extracted from wsdl file created
const xml = require('fs').readFileSync('./bmicalculator.wsdl', 'utf8');
//create an express server and pass it to a soap server
const server = app.listen(3030, function() {
const host = '127.0.0.1';
const port = server.address().port;
});
soap.listen(server, '/bmicalculator', service, xml);
Next, create a client.js
file that will consume soap service defined by server.js
. This file will provide arguments for the soap service and call the url with SOAP's service ports and endpoints.
const express = require('express');
const soap = require('soap');
const url = 'http://localhost:3030/bmicalculator?wsdl';
const args = { weight: 65.7, height: 1.63 };
soap.createClient(url, function(err, client) {
if (err) console.error(err);
else {
client.calculateBMI(args, function(err, response) {
if (err) console.error(err);
else {
console.log(response);
res.send(response);
}
});
}
});
Your wsdl file is an xml based protocol for data exchange that defines how to access a remote web service. Call your wsdl file bmicalculator.wsdl
<definitions name="HelloService" targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<message name="getBMIRequest">
<part name="weight" type="xsd:float"/>
<part name="height" type="xsd:float"/>
</message>
<message name="getBMIResponse">
<part name="bmi" type="xsd:float"/>
</message>
<portType name="Hello_PortType">
<operation name="calculateBMI">
<input message="tns:getBMIRequest"/>
<output message="tns:getBMIResponse"/>
</operation>
</portType>
<binding name="Hello_Binding" type="tns:Hello_PortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="calculateBMI">
<soap:operation soapAction="calculateBMI"/>
<input>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/>
</input>
<output>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/>
</output>
</operation>
</binding>
<service name="BMI_Service">
<documentation>WSDL File for HelloService</documentation>
<port binding="tns:Hello_Binding" name="BMI_Port">
<soap:address location="http://localhost:3030/bmicalculator/" />
</port>
</service>
</definitions>
Hope it helps
I also had this problem recently. Working with a new client, trying to get a an old web forms app running from Visual Studio, with IISExpress using Windows Authentication. For me, the web.config was correctly configured
However, the IISExpress.config settings file had:
<windowsAuthentication enabled="false">
The user account the developer was logged in was very new, so unlikely it had been edited. Simple fix it turned out, change this to enabled=true and it all ran as it should then.
As can be seen by the many answers here, there are lots of problems that can result in this error message when you start the MySQL service. The thing is, MySQL will generally tell you exactly what's wrong, if you just look in the appropriate log file.
For example, on Ubuntu, you should check /var/log/syslog
. Since lots of other things might also be logging to this file, you probably want to use grep
to look at mysql messages, and tail
to look at only the most recent. All together, that might look like:
grep mysql /var/log/syslog | tail -50
Don't blindly make changes to your configuration because someone else said 'This worked for my system.' Figure out what is actually wrong with your system and you'll get a better result much faster.
As an addition to the solution:
ul li:before {
content: '?';
}
You can use any SVG icon as the content, such as the Font Aswesome.
ul {_x000D_
list-style: none;_x000D_
padding-left: 0;_x000D_
}_x000D_
li {_x000D_
position: relative;_x000D_
padding-left: 1.5em; /* space to preserve indentation on wrap */_x000D_
}_x000D_
li:before {_x000D_
content: ''; /* placeholder for the SVG */_x000D_
position: absolute;_x000D_
left: 0; /* place the SVG at the start of the padding */_x000D_
width: 1em;_x000D_
height: 1em;_x000D_
background: url("data:image/svg+xml;utf8,<?xml version='1.0' encoding='utf-8'?><svg width='18' height='18' viewBox='0 0 1792 1792' xmlns='http://www.w3.org/2000/svg'><path d='M1671 566q0 40-28 68l-724 724-136 136q-28 28-68 28t-68-28l-136-136-362-362q-28-28-28-68t28-68l136-136q28-28 68-28t68 28l294 295 656-657q28-28 68-28t68 28l136 136q28 28 28 68z'/></svg>") no-repeat;_x000D_
}
_x000D_
<ul>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>This is my text, it's pretty long so it needs to wrap. Note that wrapping preserves the indentation that bullets had!</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
</ul>
_x000D_
Note: To solve the wrapping problem that other answers had:
<li>
position: absolute; left: 0
)Here are more Font Awesome black icons.
Check this CODEPEN to see how you can add colors and change their size.
Without Storyboard:
class PaddingLabel: UILabel {
var topInset: CGFloat
var bottomInset: CGFloat
var leftInset: CGFloat
var rightInset: CGFloat
required init(withInsets top: CGFloat, _ bottom: CGFloat,_ left: CGFloat,_ right: CGFloat) {
self.topInset = top
self.bottomInset = bottom
self.leftInset = left
self.rightInset = right
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
get {
var contentSize = super.intrinsicContentSize
contentSize.height += topInset + bottomInset
contentSize.width += leftInset + rightInset
return contentSize
}
}
}
let label = PaddingLabel(8, 8, 16, 16)
label.font = .boldSystemFont(ofSize: 16)
label.text = "Hello World"
label.backgroundColor = .black
label.textColor = .white
label.textAlignment = .center
label.layer.cornerRadius = 8
label.clipsToBounds = true
label.sizeToFit()
view.addSubview(label)
Kind of an anonymous lookup table rather than a long switch statement:
return (const char *[]) {
"bananas & monkeys",
"Round and orange",
"APPLE",
}[enumVal];
In case you are using docker/docker-compose and want to prevent redis from writing to file, you can create a redis config and mount into a container
docker.compose.override.yml
redis:¬
volumes:¬
- ./redis.conf:/usr/local/etc/redis/redis.conf¬
ports:¬
- 6379:6379¬
You can download the default config from here
in the redis.conf file make sure you comment out these 3 lines
save 900 1
save 300 10
save 60 10000
myou can view more solutions for removing the persistent data here
If you don't want to have to specify the version every time you use pip:
Install pip:
$ curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python3
and export the path:
$ export PATH=/Library/Frameworks/Python.framework/Versions/<version number>/bin:$PATH
I also have the same problem, first I tried to restart redis-server by sudo service restart
but the problem still remained. Then I removed redis-server
by sudo apt-get purge redis-server
and install it again by sudo apt-get install redis-server
and then the redis was working again. It also worth to have a look at redis log which located in here /var/log/redis/redis-server.log
Currently (June 2016) typing in the link as http://www.example.com will only produce plain text.
You can now however put in an html anchor :
<a href="http://www.example.com">My Example Site</a>
There is JChart which is all open source. I'm not sure exactly what you are graphing and how you are graphing it (servlets, swing, etc) so I would say just look at a couple different ones and see which works for you.
http://sourceforge.net/projects/jchart/
I've also used JGraph but I've only used their commercial version. They do offer an open source version however:
In the list of arguments, each entry must be on its own. Using
output = subprocess.check_output(["ping", "-c","2", "-W","2", "1.1.1.1"])
should fix your problem.
Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:
For radio button:
var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();
For textbox:
var txt=$('input:text[name=DrugDurationLength]').val();
I finally found the problem. The error was not the good one.
Apparently, Ole DB source have a bug that might make it crash and throw that error. I replaced the OLE DB destination with a OLE DB Command with the insert statement in it and it fixed it.
The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/
Strange Bug, Hope it will help other people.
If you are using 1.2.x
import numpy as np
import matplotlib.pyplot as plt
x = np.random.randn(100000)
y = np.random.randn(100000)
plt.hist2d(x,y,bins=100)
plt.show()
First of all, if you're duplicating a lot of forms with cut and paste, consider a common base class for your forms (or for a category of your forms) that implements shared/common functionality or look & feel elements. You can also create a template for new forms that meet your needs and create new forms from that template.
Personally I just cut and paste then fix any lingering name errors. Since I abstract out common functionality, I have not felt enough pain to look for a better way ;-)
My Solution
public class CalendarUtils {
public static String dateFormat = "dd-MM-yyyy hh:mm";
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
public static String ConvertMilliSecondsToFormattedDate(String milliSeconds){
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(Long.parseLong(milliSeconds));
return simpleDateFormat.format(calendar.getTime());
}
}
Even though the name is immutable, you may still want to have the option of computing it rather than storing it in a field. (I realize this is unlikely for "name", but let's aim for the general case.) For that reason, even constant fields are best wrapped inside of getters:
class Foo {
public:
const std::string& getName() const {return name_;}
private:
const std::string& name_;
};
Note that if you were to change getName()
to return a computed value, it couldn't return const ref. That's ok, because it won't require any changes to the callers (modulo recompilation.)
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
Here's a real world example of why Closures kick ass... This is straight out of my Javascript code. Let me illustrate.
Function.prototype.delay = function(ms /*[, arg...]*/) {
var fn = this,
args = Array.prototype.slice.call(arguments, 1);
return window.setTimeout(function() {
return fn.apply(fn, args);
}, ms);
};
And here's how you would use it:
var startPlayback = function(track) {
Player.play(track);
};
startPlayback(someTrack);
Now imagine you want the playback to start delayed, like for example 5 seconds later after this code snippet runs. Well that's easy with delay
and it's closure:
startPlayback.delay(5000, someTrack);
// Keep going, do other things
When you call delay
with 5000
ms, the first snippet runs, and stores the passed in arguments in it's closure. Then 5 seconds later, when the setTimeout
callback happens, the closure still maintains those variables, so it can call the original function with the original parameters.
This is a type of currying, or function decoration.
Without closures, you would have to somehow maintain those variables state outside the function, thus littering code outside the function with something that logically belongs inside it. Using closures can greatly improve the quality and readability of your code.
You could use 'corrplot' package.
d <- data.frame(x1=rnorm(10),
x2=rnorm(10),
x3=rnorm(10))
M <- cor(d) # get correlations
library('corrplot') #package corrplot
corrplot(M, method = "circle") #plot matrix
More information here: http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html
If the above CMD command option is not working and you cannot make it work in any other way then follow this below.
Click on below link
and download the first link with name ADB Kits ( contains adb.exe and necessary .dll files).
After downloading replace these files with the ones in the path
Android/Sdk/platform-tools/
Now click on adb.exe and it will open cmd and will start the adb server.
Now it will detect the device and no problem. OOOOOllllaaaaa.....
If the Problem persists again then do the same... save the folder somewhere.... just replace files... it will detect the device automatically then
not so elegant but you dont need to declare any variable:
for k in (select max(1) from table where 1 = 1) loop
update x where column = value;
end loop;
To create icon you can use Glyphicon in Bootstrap:
<a href="#" class="btn btn-info btn-sm">
<span class="glyphicon glyphicon-menu-hamburger"></span>
</a>
And then control size of icon in css:
.glyphicon-menu-hamburger {
font-size: npx;
}
try this
@Html.DropDownListFor(model => model.UserName, new List<SelectListItem>
{ new SelectListItem{Text="Active", Value="True",Selected =true },
new SelectListItem{Text="Deactive", Value="False"}})
I stumbled upon this problem during attempt to dockerise Avahi which needs to be aware of its public IP to function properly. Assigning static IP to the container is tricky due to lack of support for static IP assignment in Docker.
This article describes technique how to assign static IP to the container on Debian:
Docker service should be started with DOCKER_OPTS="--bridge=br0 --ip-masq=false --iptables=false"
. I assume that br0
bridge is already configured.
Container should be started with --cap-add=NET_ADMIN --net=bridge
Inside container pre-up ip addr flush dev eth0
in /etc/network/interfaces
can be used to dismiss IP address assigned by Docker as in following example:
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
pre-up ip addr flush dev eth0
address 192.168.0.249
netmask 255.255.255.0
gateway 192.168.0.1
/etc/init.d/networking start
. Also entry script needs to edit or populate /etc/hosts
file in order to remove references to Docker-assigned IP.First open a console then cd to where you've downloaded your file like some-package.whl and use
pip install some-package.whl
Note: if pip.exe is not recognized, you may find it in the "Scripts" directory from where python has been installed. I have multiple Python installations, and needed to use the pip associated with Python 3 to install a version 3 wheel.
If pip is not installed, and you are using Windows: How to install pip on Windows?
list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append
Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]
Time complexity, append O(1), insert O(n)
This will work
<div style="width:800px;">
<div style="width:300px; float:left;"></div>
<div style="width:300px; float:right;"></div>
</div>
<div style="clear: both;"></div>
echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts
the >>
appends the output of echo
to the file.
Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.
First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.
Second, it requires you to add an entry for every host name on a domain; just adding websitename.com
will not block www.websitename.com
, for example.
Consider using a Spinner instead of a Number Picker in a Dialog. It's not exactly what was asked for, but it's much easier to implement, more contextual UI design, and should fulfill most use cases. The equivalent code for a Spinner is:
Spinner picker = new Spinner(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, yourStringList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
picker.setAdapter(adapter);
For someone who want to use onchange event directly on file input, set onchange="somefunction()
, example code from the link:
<html>
<body>
<script language="JavaScript">
function inform(){
document.form1.msg.value = "Filename has been changed";
}
</script>
<form name="form1">
Please choose a file.
<input type="file" name="uploadbox" size="35" onChange='inform()'>
<br><br>
Message:
<input type="text" name="msg" size="40">
</form>
</body>
</html>
I wanted it with date and the time but no seconds so I used this:
var dateWithoutSecond = new Date();
dateWithoutSecond.toLocaleTimeString([], {year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit'});
It produced the following output:
7/29/2020, 2:46 PM
Which was the exact thing I needed. Worked in FireFox.
Just some more input from my own experience with maps, on when I would use each one:
removeEldestEntry()
method. This lets you create a Cache object that can expire data using some criteria that you define.In Python 2.7 or Python 3
Instead of making a Popen
object directly, you can use the subprocess.check_output()
function to store output of a command in a string:
from subprocess import check_output
out = check_output(["ntpq", "-p"])
In Python 2.4-2.6
Use the communicate
method.
import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()
out
is what you want.
Important note about the other answers
Note how I passed in the command. The "ntpq -p"
example brings up another matter. Since Popen
does not invoke the shell, you would use a list of the command and options—["ntpq", "-p"]
.
This can happen if you don't have mod_proxy_http
enabled
sudo a2enmod proxy_http
For me to get my https based load balancer working, i had to enable the following:
sudo a2enmod ssl
sudo a2enmod proxy
sudo a2enmod proxy_balancer
sudo a2enmod proxy_http
tl;dr:
For classes, you might be looking for:
let index = someArray.firstIndex{$0 === someObject}
Full answer:
I think it's worth mentioning that with reference types (class
) you might want to perform an identity comparison, in which case you just need to use the ===
identity operator in the predicate closure:
Swift 5, Swift 4.2:
let person1 = Person(name: "John")
let person2 = Person(name: "Sue")
let person3 = Person(name: "Maria")
let person4 = Person(name: "Loner")
let people = [person1, person2, person3]
let indexOfPerson1 = people.firstIndex{$0 === person1} // 0
let indexOfPerson2 = people.firstIndex{$0 === person2} // 1
let indexOfPerson3 = people.firstIndex{$0 === person3} // 2
let indexOfPerson4 = people.firstIndex{$0 === person4} // nil
Note that the above syntax uses trailing closures syntax, and is equivalent to:
let indexOfPerson1 = people.firstIndex(where: {$0 === person1})
Swift 4 / Swift 3 - the function used to be called index
Swift 2 - the function used to be called indexOf
* Note the relevant and useful comment by paulbailey about class
types that implement Equatable
, where you need to consider whether you should be comparing using ===
(identity operator) or ==
(equality operator). If you decide to match using ==
, then you can simply use the method suggested by others (people.firstIndex(of: person1)
).
I use to have the same problem.
Add the domain solved it..
mySmtpClient.Credentials = New System.Net.NetworkCredential("[email protected]", "password", "domain.com")
use return before calling the function, while you click the submit button, two events(form posting as you used submit button and function call for onclick) will happen, to prevent form posting you have to return false, you have did it, also you have to specify the return i.e, to expect a value from the function,
this is a code:
input type="submit" name="continue" value="submit" onClick="**return** checkform();"
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar. INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC. Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
Having said that, I would use INTEGER and store seconds since Unix epoch (1970-01-01 00:00:00 UTC).
string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
final
adds an explicit intent to not have your function overridden, and will cause a compiler error should this be violated:
struct A {
virtual int foo(); // #1
};
struct B : A {
int foo();
};
As the code stands, it compiles, and B::foo
overrides A::foo
. B::foo
is also virtual, by the way. However, if we change #1 to virtual int foo() final
, then this is a compiler error, and we are not allowed to override A::foo
any further in derived classes.
Note that this does not allow us to "reopen" a new hierarchy, i.e. there's no way to make B::foo
a new, unrelated function that can be independently at the head of a new virtual hierarchy. Once a function is final, it can never be declared again in any derived class.
You can't do this with CSS alone. Using jQuery you can do
HTML
<label id="lab">Checkbox</label>
<input id="check" type="checkbox" />
CSS
.highlight{
background:yellow;
}
jQuery
$('#check').click(function(){
$('#lab').toggleClass('highlight')
})
This will work in all browsers
Try this:
.circle {
height: 20px;
width: 20px;
padding: 5px;
text-align: center;
border-radius: 50%;
display: inline-block;
color:#fff;
font-size:1.1em;
font-weight:600;
background-color: rgba(0,0,0,0.1);
border: 1px solid rgba(0,0,0,0.2);
}
Here's my alternative. It also uses different DIVs for the header, body and footer but synchronised for window resizing and with searching, scrolling, sorting, filtering and positioning:
Click on the Jazz, Classical... buttons to see the tables. It's set up so that it's adequate even if JavaScript is turned off.
Seems OK on IE, FF and WebKit (Chrome, Safari).
pandas dataframe plot will return the ax
for you, And then you can start to manipulate the axes whatever you want.
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(100,5))
# you get ax from here
ax = df.plot()
type(ax) # matplotlib.axes._subplots.AxesSubplot
# manipulate
vals = ax.get_yticks()
ax.set_yticklabels(['{:,.2%}'.format(x) for x in vals])
You can combine the columns without using macros. Type the following function in the formula bar:
=IF(ROW()<=COUNTA(A:A),INDEX(A:A,ROW()),IF(ROW()<=COUNTA(A:B),INDEX(B:B,ROW()-COUNTA(A:A)),IF(ROW()>COUNTA(A:C),"",INDEX(C:C,ROW()-COUNTA(A:B)))))
The statement uses 3 IF functions, because it needs to combine 3 columns:
Swift 5.2 Xcode 11.4
The Apple Symbol chevron.left now allows a more elegant solution to make a custom button. I have matched the size and spacing as close as possible.
import UIKit
class CustomBackButton: UIBarButtonItem {
convenience init(target: Any, selector: Selector) {
// Create UIButton
let button = UIButton(frame: .zero)
// Customise Title
button.setTitle("Back", for: .normal)
button.setTitleColor(.systemBlue, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 17)
// Customise Image
let config = UIImage.SymbolConfiguration(pointSize: 19.0, weight: .semibold, scale: .large)
let image = UIImage(systemName: "chevron.left", withConfiguration: config)
button.setImage(image, for: .normal)
// Add Target
button.addTarget(target, action: selector, for: .touchUpInside)
// Customise Spacing to match system Back button
button.imageEdgeInsets = UIEdgeInsets(top: 0.0, left: -18.0, bottom: 0.0, right: 0.0)
button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -12.0, bottom: 0.0, right: 0.0)
self.init(customView: button)
}
}
This can be implemented either as a UIToolbarItem
, or a UINavigationItem
override func viewDidLoad() {
super.viewDidLoad()
// UIToolbar Item
let barBackButton = CustomBackButton(target: self, selector: #selector(backButtonTapped))
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
navigationController?.setToolbarHidden(false, animated: false)
toolbarItems = [barBackButton, flexSpace]
// Navigation Item
let navBackButton = CustomBackButton(target: self, selector: #selector(backButtonTapped))
navigationItem.leftBarButtonItem = navBackButton
}
@objc func backButtonTapped() {
print("Back tapped")
}
If you want to flip the button and have the arrow pointing to the Right:
Use Apple Symbol named "chevron.right"
Add the following code to the CustomBackButton
class:
// Put the image of the right side of the button
button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
Seems like the most reusable and elegant solution combines the abive to take MaxLength from the Input attribute and then reference the Span element with a predictable id....
Then to use, all you need to do is add '.countit' to the Input class and 'counter_' + [input-ID] to your span
HTML
<textarea class="countit" name="name" maxlength='6' id="post"></textarea>
<span>characters remaining: <span id="counter_name"></span></span>
<br>
<textarea class="countit" name="post" maxlength='20' id="post"></textarea>
<span>characters remaining: <span id="counter_post"></span></span>
<br>
<textarea class="countit" name="desc" maxlength='10' id="desc"></textarea>
<span>characters remaining: <span id="counter_desc"></span></span>
Jquery
$(".countit").keyup(function () {
var maxlength = $(this).attr("maxlength");
var currentLength = $(this).val().length;
if( currentLength >= maxlength ){
$("#counter_" + $(this).attr("id")).html(currentLength + ' / ' + maxlength);
}else{
$("#counter_" + $(this).attr("id")).html(maxlength - currentLength + " chars left");
}
});
The $ solution didn't work for me. However, By actually putting the tab character itself in the command did: sort -t'' -k2
Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).
var websocket;
if ("WebSocket" in window)
{
websocket = new WebSocket("ws://yourDomainNameHere.org/");
websocket.onopen = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
};
websocket.onclose = function (event) {
var reason;
alert(event.code);
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
if (event.code == 1000)
reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
else if(event.code == 1001)
reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
else if(event.code == 1002)
reason = "An endpoint is terminating the connection due to a protocol error";
else if(event.code == 1003)
reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
else if(event.code == 1004)
reason = "Reserved. The specific meaning might be defined in the future.";
else if(event.code == 1005)
reason = "No status code was actually present.";
else if(event.code == 1006)
reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
else if(event.code == 1007)
reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
else if(event.code == 1008)
reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
else if(event.code == 1009)
reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
else if(event.code == 1011)
reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
else if(event.code == 1015)
reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
else
reason = "Unknown reason";
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
};
websocket.onmessage = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
};
websocket.onerror = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
};
}
else
{
alert("Websocket is not supported by your browser");
return;
}
websocket.send("Yo wazzup");
websocket.close();
I had great luck with OWASP Anti-Samy and an AspectJ advisor on all my Spring Controllers that blocks XSS from getting in.
public class UserInputSanitizer {
private static Policy policy;
private static AntiSamy antiSamy;
private static AntiSamy getAntiSamy() throws PolicyException {
if (antiSamy == null) {
policy = getPolicy("evocatus-default");
antiSamy = new AntiSamy();
}
return antiSamy;
}
public static String sanitize(String input) {
CleanResults cr;
try {
cr = getAntiSamy().scan(input, policy);
} catch (Exception e) {
throw new RuntimeException(e);
}
return cr.getCleanHTML();
}
private static Policy getPolicy(String name) throws PolicyException {
Policy policy =
Policy.getInstance(Policy.class.getResourceAsStream("/META-INF/antisamy/" + name + ".xml"));
return policy;
}
}
You can get the AspectJ advisor from the this stackoverflow post
I think this is a better approach then c:out particular if you do a lot of javascript.
there are some mistasks in demo http://jsfiddle.net/brandonzylstra/hjk9mvcy/ mentioned by https://stackoverflow.com/users/241142/iconoclast.
in his demo, add these code will works:
setTimeout(() => {
console.log(EntryElm[0].offsetWidth)
}, 0)
Take a look at http://www.w3schools.com/jsref/jsref_obj_date.asp
There is a function UTC()
that returns the milliseconds from the unix epoch.
Both are shorthands for longer expressions.
?:
is short for $a ? $a : $b
. This expression will evaluate to $a if $a evaluates to TRUE.
??
is short for isset($a) ? $a : $b
. This expression will evaluate to $a if $a is set and not null.
Their use cases overlaps when $a is undefined or null. When $a is undefined ??
will not produce an E_NOTICE, but the results are the same. When $a is null the result is the same.
I had the same issue just add this function to the open dialog options and it worked sharm
open: function(){
var closeBtn = $('.ui-dialog-titlebar-close');
closeBtn.append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span>');
},
and on close event you need to remove that
close: function () {
var closeBtn = $('.ui-dialog-titlebar-close');
closeBtn.html('');}
Complete example
<div id="deleteDialog" title="Confirm Delete">
Can you confirm you want to delete this event?
</div>
$("#deleteDialog").dialog({
width: 400, height: 200,
modal: true,
open: function () {
var closeBtn = $('.ui-dialog-titlebar-close');
closeBtn.append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span>');
},
close: function () {
var closeBtn = $('.ui-dialog-titlebar-close');
closeBtn.html('');
},
buttons: {
"Confirm": function () {
calendar.fullCalendar('removeEvents', event._id);
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$("#dialog").dialog("open");
Not exactly the answer to the question, but I needed to scroll down as soon as an EditText got the focus. However the accepted answer would make the ET also lose focus right away (to the ScrollView I assume).
My workaround was the following:
emailEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
Toast.makeText(getActivity(), "got the focus", Toast.LENGTH_LONG).show();
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
}, 200);
}else {
Toast.makeText(getActivity(), "lost the focus", Toast.LENGTH_LONG).show();
}
}
});
The []-operator is resolved to the access property this[sometype index]
, with implementation depending upon the Element-Collection.
An Enumerable-Interface declares a blueprint of what a Collection should look like in the first place.
Take this example to demonstrate the usefulness of clean Interface separation:
var ienu = "13;37".Split(';').Select(int.Parse);
//provides an WhereSelectArrayIterator
var inta = "13;37".Split(';').Select(int.Parse).ToArray()[0];
//>13
//inta.GetType(): System.Int32
Also look at the syntax of the []-operator:
//example
public class SomeCollection{
public SomeCollection(){}
private bool[] bools;
public bool this[int index] {
get {
if ( index < 0 || index >= bools.Length ){
//... Out of range index Exception
}
return bools[index];
}
set {
bools[index] = value;
}
}
//...
}
http://ajmoore.blogspot.com/2007/11/svn-java-project-with-eclipse.html
Try this:
body
{
background:url("images/plaid.jpg") no-repeat fixed center;
}
jsfiddle example: http://jsfiddle.net/Q9Zfa/
As well as making sure that you have first called $("#myForm").validate();
, make sure that your dynamic control has been added to the DOM before adding the validation rules.
You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all
from the stringr
package, though gsub
from base R works just as well.
The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.
x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")
(The base R equivalent is gsub("[[:punct:]]", " ", x)
.)
An alternative is to swap out all non-alphanumeric characters.
str_replace_all(x, "[^[:alnum:]]", " ")
Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.
Its not possible to hide address bar of browser.
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
I'm not really sure what your question is, but to get the text of the li
element you can use:
$(this).text();
And to get the id
of an element you can use .attr('id');
. Once you have a reference to the element you want (e.g. $(this)
) you can perform any jQuery function on it.
Since Google takes you to this post when searching for C# Web API Referrer
here's the deal: Web API
uses a different type of Request
from normal MVC Request
called HttpRequestMessage
which does not include UrlReferrer
. Since a normal Web API
request does not include this information, if you really need it, you must have your clients go out of their way to include it. Although you could make this be part of your API Object
, a better way is to use Headers
.
First, you can extend HttpRequestMessage
to provide a UrlReferrer()
method:
public static string UrlReferrer(this HttpRequestMessage request)
{
return request.Headers.Referrer == null ? "unknown" : request.Headers.Referrer.AbsoluteUri;
}
Then your clients need to set the Referrer Header
to their API Request
:
// Microsoft.AspNet.WebApi.Client
client.DefaultRequestHeaders.Referrer = new Uri(url);
And now the Web API Request
includes the referrer data which you can access like this from your Web API
:
Request.UrlReferrer();
If you want to know a property's underlying type, try this:
propInfo.PropertyType.UnderlyingSystemType.GenericTypeArguments[0]
"new" and "original" are different dicts, that's why you can update just one of them.. The items are shallow-copied, not the dict itself.
distcp command use for copying from one cluster to another cluster in parallel. You have to set the path for namenode of src and path for namenode of dst, internally it use mapper.
Example:
$ hadoop distcp <src> <dst>
there few options you can set for distcp
-m for no. of mapper for copying data this will increase speed of copying.
-atomic for auto commit the data.
-update will only update data that is in old version.
There are generic command for copying files in hadoop are -cp and -put but they are use only when the data volume is less.
As far as I can tell, the command is correct, ASSUMING your input file is a valid gzipped tar file. Your output says that it isn't. If you downloaded the file from the internet, you probably didn't get the entire file, try again.
Without more knowledge of the source of your file, nobody here is going to be able to give you a concrete solution, just educated guesses.
If you are looking for a robust version that can deal with any form of URLs, this should do nicely:
<?php
$url = "http://foobar.com/foo/bar/1?baz=qux#fragment/foo";
$lastSegment = basename(parse_url($url, PHP_URL_PATH));
No alternative method is provided in the method's description because the preferred approach (as of API level 11) is to instantiate PreferenceFragment objects to load your preferences from a resource file. See the sample code here: PreferenceActivity
Turn off the push notification. Then,Restart your XCode and Turn back ON the Push Notification. It works for me.
For npm: you can run:
npm update -g typescript
By default, it will install latest version.
For yarn, you can run:
yarn upgrade typescript
Or you can remove the orginal version, run yarn global remove typescript
, and then execute yarn global add typescript
, by default it will also install the latest version of typescript.
more details, you can read yarn docs.
Look at the following commands (especially the commented block).
DROP TABLE foo;
DROP TABLE bar;
CREATE TABLE foo (a int, b text);
CREATE TABLE bar (a serial, b text);
INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i;
INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, 5) i;
-- blocks of commands to turn foo into bar
CREATE SEQUENCE foo_a_seq;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
ALTER TABLE foo ALTER COLUMN a SET NOT NULL;
ALTER SEQUENCE foo_a_seq OWNED BY foo.a; -- 8.2 or later
SELECT MAX(a) FROM foo;
SELECT setval('foo_a_seq', 5); -- replace 5 by SELECT MAX result
INSERT INTO foo (b) VALUES('teste');
INSERT INTO bar (b) VALUES('teste');
SELECT * FROM foo;
SELECT * FROM bar;
The "this" is already coloured in Javascript.
View->Syntax-> and choose your language to highlight.
Its may be due to the default storage space set to 40GB ( default path , /var/lib/docker)
you can change the storage volume to point to different path
DOCKER_STORAGE_OPTIONS='--storage-driver=overlay --graph=CUSTOM_PATH'
if you run command docker info ( it should show storage driver as overlay)
Please enter domain nginx file :
nano /etc/nginx/sites-available/domain.set
Add to file this code
client_max_body_size 24000M;
If you get error use this command
nginx -t
WhatsApp has chosen Erlang a language built for writing scalable applications that are designed to withstand errors. Erlang uses an abstraction called the Actor model for it's concurrency - http://en.wikipedia.org/wiki/Actor_(programming_language) Instead of the more traditional shared memory approach, actors communicate by sending each other messages. Actors unlike threads are designed to be lightweight. Actors could be on the same machine or on different machines and the message passing abstractions works for both. A simple implementation of WhatsApp could be: Each user/device is represented as an actor. This actor is responsible for handling the inbox of the user, how it gets serialized to disk, the messages that the user sends and the messages that the user receives. Let's assume that Alice and Bob are friends on WhatsApp. So there is an an Alice actor and a Bob actor.
Let's trace a series of messages flowing back and forth:
Alice decides to message Bob. Alice's phone establishes a connection to the WhatsApp server and it is established that this connection is definitely from Alice's phone. Alice now sends via TCP the following message: "For Bob: A giant monster is attacking the Golden Gate Bridge". One of the WhatsApp front end server deserializes this message and delivers this message to the actor called Alice.
Alice the actor decides to serialize this and store it in a file called "Alice's Sent Messages", stored on a replicated file system to prevent data loss due to unpredictable monster rampage. Alice the actor then decides to forward this message to Bob the actor by passing it a message "Msg1 from Alice: A giant monster is attacking the Golden Gate Bridge". Alice the actor can retry with exponential back-off till Bob the actor acknowledges receiving the message.
Bob the actor eventually receives the message from (2) and decides to store this message in a file called "Bob's Inbox". Once it has stored this message durably Bob the actor will acknowledge receiving the message by sending Alice the actor a message of it's own saying "I received Msg1". Alice the actor can now stop it's retry efforts. Bob the actor then checks to see if Bob's phone has an active connection to the server. It does and so Bob the actor streams this message to the device via TCP.
Bob sees this message and replies with "For Alice: Let's create giant robots to fight them". This is now received by Bob the actor as outlined in Step 1. Bob the actor then repeats Step 2 and 3 to make sure Alice eventually receives the idea that will save mankind.
WhatsApp actually uses the XMPP protocol instead of the vastly superior protocol that I outlined above, but you get the point.
This is also in response to naomik's excellent post! Unfortunately I don't have the rep to post in the correct place but I leave this here in case it can help anyone.
If you need British English written form you need to make some adaptions to the code. British English differs from the American in a couple of ways. Basically you need to insert the word 'and' in two specific places.
The first situation can be addressed by checking for 10s and 1s in the makeGroup method and appending 'and' when they exist.
makeGroup = ([ones,tens,huns]) => {
var adjective = this.num(ones) ? ' hundred and ' : this.num(tens) ? ' hundred and ' : ' hundred';
return [
this.num(huns) === 0 ? '' : this.a[huns] + adjective,
this.num(ones) === 0 ? this.b[tens] : this.b[tens] && this.b[tens] + '-' || '',
this.a[tens+ones] || this.a[ones]
].join('');
};
The second case is more complicated. It is equivalent to
1,100,057 one million one hundred thousand and fifty seven. 5,000,006 five million and six
I think this could be implemented in @naomik's code through the use of a filter function but I wasn't able to work out how. In the end I settled on hackily looping through the returned array of words and using indexOf to look for instances where the word 'hundred' was missing from the final element.
This was not yet mentioned but make sure that your SYSTEM TIME is correct. If it is too out of sync it will cause a EINTEGRITY error. When you are doing npm publish / install.
I like to stay away from the marshaller.
Using CString newString(originalString);
Seems much cleaner and faster to me. No need to worry about creating and deleting a context.
There is a new possible error for this one related to the latest Android Wear technology. I was trying to get an emulator started for the wear SDK in preparation for next week. The API level only supports it in the latest build of 4.4.2 KitKat.
So if you are using something such as the wearable, it starts the default off still in Eclipse as 2.3.3 Gingerbread. Be sure that your target matches the lowest possible supported target. For the wearables its the latest 19 KitKat.
Adding a @
works for me!
I tested with error_reporting(E_ALL ^ E_DEPRECATED);
You may or may not have to use setOpaque method to ensure that the colors show up by passing true to the method.
First of all the term fragmentation cues there's an entity divided into parts — fragments.
Internal fragmentation: Typical paper book is a collection of pages (text divided into pages). When a chapter's end isn't located at the end of page and new chapter starts from new page, there's a gap between those chapters and it's a waste of space — a chunk (page for a book) has unused space inside (internally) — "white space"
External fragmentation: Say you have a paper diary and you didn't write your thoughts sequentially page after page, but, rather randomly. You might end up with a situation when you'd want to write 3 pages in row, but you can't since there're no 3 clean pages one-by-one, you might have 15 clean pages in the diary totally, but they're not contiguous
Yes you can (provided you have at least the professional version of visual studio), although it requires a little setting up once you've done this it's not much different from debugging code. MSDN has a basic walkthrough.
I ran into the same issue and figured out the problem. When you initialize a repository there aren't actually any branches. When you start a project run git add .
and then git commit
and the master branch will be created.
Without checking anything in you have no master branch. In that case you need to follow the steps other people here have suggested.
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set
is needed because TextRange
is a class, so hyperLinkText
is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.
This directive pass the selected files as well:
/**
*File Input - custom call when the file has changed
*/
.directive('onFileChange', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var onChangeHandler = scope.$eval(attrs.onFileChange);
element.bind('change', function() {
scope.$apply(function() {
var files = element[0].files;
if (files) {
onChangeHandler(files);
}
});
});
}
};
});
The HTML, how to use it:
<input type="file" ng-model="file" on-file-change="onFilesSelected">
In my controller:
$scope.onFilesSelected = function(files) {
console.log("files - " + files);
};
Fiddle: http://jsfiddle.net/uenrX/1/
The opacity property of the outer DIV cannot be undone by the inner DIV. If you want to achieve transparency, use rgba
or hsla
:
Outer div:
background-color: rgba(255, 255, 255, 0.9); /* Color white with alpha 0.9*/
Inner div:
background-color: #FFF; /* Background white, to override the background propery*/
EDIT
Because you've added filter:alpha(opacity=90)
to your question, I assume that you also want a working solution for (older versions of) IE. This should work (-ms-
prefix for the newest versions of IE):
/*Padded for readability, you can write the following at one line:*/
filter: progid:DXImageTransform.Microsoft.Gradient(
GradientType=1,
startColorStr="#E6FFFFFF",
endColorStr="#E6FFFFFF");
/*Similarly: */
filter: progid:DXImageTransform.Microsoft.Gradient(
GradientType=1,
startColorStr="#E6FFFFFF",
endColorStr="#E6FFFFFF");
I've used the Gradient filter, starting with the same start-
and end-color
, so that the background doesn't show a gradient, but a flat colour. The colour format is in the ARGB hex format. I've written a JavaScript snippet to convert relative opacity values to absolute alpha-hex values:
var opacity = .9;
var A_ofARGB = Math.round(opacity * 255).toString(16);
if(A_ofARGB.length == 1) A_ofARGB = "0"+a_ofARGB;
else if(!A_ofARGB.length) A_ofARGB = "00";
alert(A_ofARGB);
In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before
css to match yours.
In case if it is IE10 then using below css3 it is possible
select::-ms-expand {
display: none;
}
However if you're interested in jQuery plugin, try Chosen.js
or you can create your own in js.
C# has a lot of reference types. Even if a container stores the references contiguously, the objects themselves may be scattered through the heap
If you don't want to repeat the list twice (as per @J W's answer), then put the updates in a table variable and use a JOIN
in the UPDATE
:
declare @ToDo table (FromName varchar(10), ToName varchar(10))
insert into @ToDo(FromName,ToName) values
('AAA','BBB'),
('CCC','DDD'),
('EEE','FFF')
update ts set LastName = ToName
from dbo.TestStudents ts
inner join
@ToDo t
on
ts.LastName = t.FromName
use js split() method to create an array
var keywords = $('#searchKeywords').val().split(",");
then loop through the array using jQuery.each() function. as the documentation says:
In the case of an array, the callback is passed an array index and a corresponding array value each time
$.each(keywords, function(i, keyword){
console.log(keyword);
});
https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.
Might as well throw up an actual response with my solution, which was inspired by Peter Liljenberg's:
$ mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12"%" }'
0.75%
This will use awk
to print out 100 minus the 12th field (idle), with a percentage sign after it. awk
will only do this for a line where the 12th field has numbers and dots only ($12 ~ /[0-9]+/
).
You can also average five samples, one second apart:
$ mpstat 1 5 | awk 'END{print 100-$NF"%"}'
Test it like this:
$ mpstat 1 5 | tee /dev/tty | awk 'END{print 100-$NF"%"}'
Why think? If not
confuses you, switch your if and else clauses around to avoid the negation.
i want to make sure that ( u0 <= u < u0+step ) before do sth.
Just write that.
if u0 <= u < u0+step:
"do sth" # What language is "sth"? No vowels. An odd-looking word.
else:
u0 = u0+ step
Why overthink it?
If you need an empty if
-- and can't work out the logic -- use pass
.
if some-condition-that's-too-complex-for-me-to-invert:
pass
else:
do real work here
The accepted answer to set git config core.filemode false
, works, but with consequences. Setting core.filemode
to false tells git to ignore any executable bit changes on the filesystem so it won't view this as a change. If you do need to stage an executable bit change for this repository anytime in the future, you would have to do it manually, or set core.filemode
back to true.
A less consequential alternative, if all the modified files should have mode 100755, is to do something like
chmod 100755 $(git ls-files --modified)
which just does exactly the change in mode, no more, no less, without additional implications.
(in my case, it was due to a OneDrive sync with my filesystem on MacOS; by not changing core.filemode
, I'm leaving the possibility open that the mode change might happen again in the future; in my case, I'd like to know if it happens again, and changing core.filemode
will hide it from me, which I don't want)
Class.getResources
would retrieve the resource by the classloader which load the object. While ClassLoader.getResource
would retrieve the resource using the classloader specified.
In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me
//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\
You can also use:
button.setStyleSheet("qproperty-icon: url(:/path/to/images.png);");
Note: This is a little hacky. You should use this only as last resort. Icons should be set from C++
code or Qt Designer
.
An alternative would be to place your regexp in non-capturing parentheses. Then make that expression optional using the ?
qualifier, which will look for 0 (i.e. empty string) or 1 instances of the non-captured group.
For example:
/(?: some regexp )?/
In your case the regular expression would look something like this:
/^(?:[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+)?$/
No |
"or" operator necessary!
Here is the Mozilla documentation for JavaScript Regular Expression syntax.
In my case other solutions did not work than this way:
$('.bootstrap-filestyle :input').val('');
However, if you will have more than 1 file input on page, it will reset the text on all of them.
Quick and dirty, but it does the job:
import java.io.*;
public class Counter {
public final static void main(String[] args) throws IOException {
if (args.length > 0) {
File file = new File(args[0]);
System.out.println(countLines(file));
}
}
public final static int countLines(File file) throws IOException {
ProcessBuilder builder = new ProcessBuilder("wc", "-l", file.getAbsolutePath());
Process process = builder.start();
InputStream in = process.getInputStream();
LineNumberReader reader = new LineNumberReader(new InputStreamReader(in));
String line = reader.readLine();
if (line != null) {
return Integer.parseInt(line.trim().split(" ")[0]);
} else {
return -1;
}
}
}
First import:
import org.apache.log4j.PropertyConfigurator;
Then add below code to main method:
String log4jConfPath ="path to/log4j.properties";
PropertyConfigurator.configure(log4jConfPath);
Create a file at path to and add the below code to that file.
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n
It was a problem in Instagram Developer Console. max_id
and min_id
doesn't work there.
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
For me, the problem was a NuGet package without a strong name. The solution was to install StrongNamer from NuGet, which automatically adds a strong name to all referenced assemblies. Just simply having it referenced in the project fixed my issue.
You can compile your C programs with an ARM cross-compiler:
arm-linux-gnueabi-gcc -static -march=armv7-a test.c -o test
Then you can push your compiled binary file to somewhere (don't push it in to the SD card):
adb push test /data/local/tmp/test
use jquery Every time Plugin .using this you can do ajax call for "X" time period
$("#select").everyTime(1000,function(i) {
//ajax call
}
you can also use setInterval
display
syntax instead, for clarityThe display
CSS property in fact sets two things at once: the outer display type, and the inner display type. The outer display type affects how the element (which acts as a container) is displayed in its context. The inner display type affects how the children of the element (or the children of the container) are laid out.
If you use the two-value display
syntax, which is only supported in some browsers like Firefox, the difference between the two is much more obvious:
display: block
is equivalent to display: block flow
display: inline
is equivalent to display: inline flow
display: flex
is equivalent to display: block flex
display: inline-flex
is equivalent to display: inline flex
display: grid
is equivalent to display: block grid
display: inline-grid
is equivalent to display: inline grid
block
or inline
:An element with the outer display type of block
will take up the whole width available to it, like <div>
does. An element with the outer display type of inline
will only take up the width that it needs, with wrapping, like <span>
does.
flow
, flex
or grid
:The inner display type flow
is the default inner display type when flex
or grid
is not specified. It is the way of laying out children elements that we are used to in a <p>
for instance. flex
and grid
are new ways of laying out children that each deserve their own post.
The difference between display: flex
and display: inline-flex
is the outer display type, the first's outer display type is block
, and the second's outer display type is inline
. Both of them have the inner display type of flex
.
The original question was how to rename a tag, which is easy: first create NEW as an alias of OLD: git tag NEW OLD
then delete OLD: git tag -d OLD
.
The quote regarding "the Git way" and (in)sanity is off base, because it's talking about preserving a tag name, but making it refer to a different repository state.
Since I wanted my kafka broker to connect with remote producers and consumers, So I don't want advertised.listener
to be commented out. In my case, (running kafka on kubernetes), I found out that my kafka pod was not assigned any Cluster IP. By removing the line clusterIP: None
from services.yml, the kubernetes assigns an internal-ip to kafka pod. This resolved my issue of LEADER_NOT_AVAILABLE and also remote connection of kafka producers/consumers.
I know this is an old thread, but the most common use case for ++i is not covered, that being manually indexing sets when there are no provided indices. This situation is why python provides enumerate()
Example : In any given language, when you use a construct like foreach to iterate over a set - for the sake of the example we'll even say it's an unordered set and you need a unique index for everything to tell them apart, say
i = 0
stuff = {'a': 'b', 'c': 'd', 'e': 'f'}
uniquestuff = {}
for key, val in stuff.items() :
uniquestuff[key] = '{0}{1}'.format(val, i)
i += 1
In cases like this, python provides an enumerate method, e.g.
for i, (key, val) in enumerate(stuff.items()) :
This is how you use bundle:
Bundle b = new Bundle();
b.putInt("id", id);
Fragment frag= new Fragment();
frag.setArguments(b);
retrieve value from bundle:
bundle = getArguments();
if (bundle != null) {
id = bundle.getInt("id");
}
I got this error too. I figured out that my version of PHP didn't have openssl compiled in, so simply adding the extension directive to php.ini wasn't enough. I don't know how you have to solve this in your particular case, but for me, I use macports, and the command was just:
sudo port install php5-openssl
When GROUP BY is not used, the WHERE and HAVING clauses are essentially equivalent.
However, when GROUP BY is used:
I know question is specific to MVC4. But since we are way past MVC4 and if anyone looking for ASP.NET Core, you can use:
<partial name="_My_Partial" model="Model.MyInfo" />
BYTE*
is probably a typedef for unsigned char*
, but I can't say for sure. It would help if you tell us what BYTE
is.
If BYTE* is unsigned char*, you can convert it to an std::string using the std::string range constructor, which will take two generic Iterators.
const BYTE* str1 = reinterpret_cast<const BYTE*> ("Hello World");
int len = strlen(reinterpret_cast<const char*>(str1));
std::string str2(str1, str1 + len);
That being said, are you sure this is a good idea? If BYTE
is unsigned char
it may contain non-ASCII characters, which can include NULLs. This will make strlen
give an incorrect length.
This answer relates to modern setups (TypeScript 2.x, Webpack > 2.x)
You don't need to install @types/node (which is all of Node.js types and is irrelevant for front-end code, actually complicating things such as setTimout different return values, etc..
You do need to install @types/webpack-env
npm i -D @types/webpack-env
which gives the runtime signatures that Webpack has (including require
, require.ensure
, etc.)
Also make sure that your tsconfig.json file has no set 'types' array -> which will make it pickup all type definitions in your node_modules/@types folder.
If you want to restrict search of types you can set the typeRoot property to node_modules/@types.
You can use:
SELECT IDENT_CURRENT('tablename')
to access the latest identity for a perticular table.
e.g. Considering following code:
INSERT INTO dbo.MyTable(columns....) VALUES(..........)
INSERT INTO dbo.YourTable(columns....) VALUES(..........)
SELECT IDENT_CURRENT('MyTable')
SELECT IDENT_CURRENT('YourTable')
This would yield to correct value for corresponding tables.
It returns the last IDENTITY
value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.
IDENT_CURRENT
is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT
returns the identity value generated for a specific table in any session and any scope.
...better is declare the name as varible ,and ask before if thereis a apostrophe in the string:
e.g.:
DIM YourName string
YourName = "Daniel O'Neal"
If InStr(YourName, "'") Then
SELECT * FROM tblStudents WHERE [name] Like """ Your Name """ ;
else
SELECT * FROM tblStudents WHERE [name] Like '" Your Name "' ;
endif
The return type depends on the server, sometimes the response is indeed a JSON array but sent as text/plain
Setting the accept headers in the request should get the correct type:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
which can then be serialized to a JSON list or array. Thanks for the comment from @svick which made me curious that it should work.
The Exception I got without configuring the accept headers was System.Net.Http.UnsupportedMediaTypeException.
Following code is cleaner and should work (untested, but works in my case):
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs");
var model = await response.Content.ReadAsAsync<List<Job>>();
Another thing to check is if any applications still have a hold on the file.
Had some issues with MoveFile. Part of my permissions problem was that my script opens the file (in this case in Excel), makes a modification, closes it, then moves it to a "processed" folder.
In debugging a couple things, the script crashed a few times. Digging into the permission denied error I found that I had 4 instances of Excel running in the background because the script was never able to properly terminate the application due to said crashes. Apparently one of them still had a hold on the file and, thusly, "permission denied."