The only elasticsearch vs solr performance comparison I've been able to find so far is here:
Install GCC in Ubuntu Debian Base
sudo apt-get install build-essential
Just my two cents to this very old question. I would highly recommend taking a look at ElasticSearch.
Elasticsearch is a search server based on Lucene. It provides a distributed, multitenant-capable full-text search engine with a RESTful web interface and schema-free JSON documents. Elasticsearch is developed in Java and is released as open source under the terms of the Apache License.
The advantages over other FTS (full text search) Engines are:
We are using this search engine at our project and very happy with it.
Just use multiple in-clauses to get around this:
select field1, field2, field3 from table1
where name in ('value1', 'value2', ..., 'value999')
or name in ('value1000', ..., 'value1999')
or ...;
I want to add the important hint that converting a project like this can have side effects which are noticeable when you have a larger project. This is due the fact that Intellij Idea (2017) takes some important settings only from the pom.xml then which can lead to some confusion, following sections are affected at least:
All these points need review and adjusting but after this it works like charm.
Further more unfortunately there is no sufficient pom.xml template created, I have added an example which might help to solve most problems.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Name</groupId>
<artifactId>Artifact</artifactId>
<version>4.0</version>
<properties>
<!-- Generic properties -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<!--All dependencies to put here, including module dependencies-->
</dependencies>
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<testSourceDirectory> ${project.basedir}/src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>${project.basedir}/src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<annotationProcessors/>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
Edit 2019:
When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT
variable for you; after all, your script runs in their environment.
Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000
instead of process.env.PORT || 3000
where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.
This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;
app.listen(port);
One cheeky solution :
function printDiv(divID) {
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divElements + "</body>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}
HTML :
<form id="form1" runat="server">
<div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
Print me I am in 1st Div
</div>
<div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
I am not going to print
</div>
<input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>
In my case, even after sign up to Visual Studio account, I cant sign in and the license still expired.
Solution from across the internet: Download iso version of the installer. Then run installer, select repair. That would solve the problem for most case.
In my case, I got an iso version of ms Visual Studio 2013. Installed it and I can successfully sign in and its forever free.
class M(type):
_dict = {}
def __call__(cls, key):
if key in cls._dict:
print 'EXISTS'
return cls._dict[key]
else:
print 'NEW'
instance = super(M, cls).__call__(key)
cls._dict[key] = instance
return instance
class A(object):
__metaclass__ = M
def __init__(self, key):
print 'INIT'
self.key = key
print
a1 = A('aaa')
a2 = A('bbb')
a3 = A('aaa')
outputs:
NEW
INIT
NEW
INIT
EXISTS
NB As a side effect M._dict
property automatically becomes accessible from A
as A._dict
so take care not to overwrite it incidentally.
Try this:
^[0-9]{4,6}$
{4,6}
= between 4 and 6 characters, inclusive.
Consider creating a function which can return a table and be used in a query.
https://msdn.microsoft.com/en-us/library/ms186755.aspx
The main difference between a function and a procedure is that a function makes no changes to any table. It only returns a value.
In this example I'm creating a query to give me the counts of all the columns in a given table which aren't null or empty.
There are probably many ways to clean this up. But it illustrates a function well.
USE Northwind
CREATE FUNCTION usp_listFields(@schema VARCHAR(50), @table VARCHAR(50))
RETURNS @query TABLE (
FieldName VARCHAR(255)
)
BEGIN
INSERT @query
SELECT
'SELECT ''' + @table+'~'+RTRIM(COLUMN_NAME)+'~''+CONVERT(VARCHAR, COUNT(*)) '+
'FROM '+@schema+'.'+@table+' '+
' WHERE isnull("'+RTRIM(COLUMN_NAME)+'",'''')<>'''' UNION'
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table and TABLE_SCHEMA = @schema
RETURN
END
Then executing the function with
SELECT * FROM usp_listFields('Employees')
produces a number of rows like:
SELECT 'Employees~EmployeeID~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees WHERE isnull("EmployeeID",'')<>'' UNION
SELECT 'Employees~LastName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees WHERE isnull("LastName",'')<>'' UNION
SELECT 'Employees~FirstName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees WHERE isnull("FirstName",'')<>'' UNION
For python2 you can use this code before csv_writer.writerows(rows)
This code will NOT convert integers to utf-8 strings
def encode_rows_to_utf8(rows): encoded_rows = [] for row in rows: encoded_row = [] for value in row: if isinstance(value, basestring): value = unicode(value).encode("utf-8") encoded_row.append(value) encoded_rows.append(encoded_row) return encoded_rows
Use the pointtype
and pointsize
options, e.g.
plot "./points.dat" using 1:2 pt 7 ps 10
where pt 7
gives you a filled circle and ps 10
is the size.
See: Plotting data.
with
statementDifferentiating between exceptions that occur in a with
statement is tricky because they can originate in different places. Exceptions can be raised from either of the following places (or functions called therein):
ContextManager.__init__
ContextManager.__enter__
with
ContextManager.__exit__
For more details see the documentation about Context Manager Types.
If we want to distinguish between these different cases, just wrapping the with
into a try .. except
is not sufficient. Consider the following example (using ValueError
as an example but of course it could be substituted with any other exception type):
try:
with ContextManager():
BLOCK
except ValueError as err:
print(err)
Here the except
will catch exceptions originating in all of the four different places and thus does not allow to distinguish between them. If we move the instantiation of the context manager object outside the with
, we can distinguish between __init__
and BLOCK / __enter__ / __exit__
:
try:
mgr = ContextManager()
except ValueError as err:
print('__init__ raised:', err)
else:
try:
with mgr:
try:
BLOCK
except TypeError: # catching another type (which we want to handle here)
pass
except ValueError as err:
# At this point we still cannot distinguish between exceptions raised from
# __enter__, BLOCK, __exit__ (also BLOCK since we didn't catch ValueError in the body)
pass
Effectively this just helped with the __init__
part but we can add an extra sentinel variable to check whether the body of the with
started to execute (i.e. differentiating between __enter__
and the others):
try:
mgr = ContextManager() # __init__ could raise
except ValueError as err:
print('__init__ raised:', err)
else:
try:
entered_body = False
with mgr:
entered_body = True # __enter__ did not raise at this point
try:
BLOCK
except TypeError: # catching another type (which we want to handle here)
pass
except ValueError as err:
if not entered_body:
print('__enter__ raised:', err)
else:
# At this point we know the exception came either from BLOCK or from __exit__
pass
The tricky part is to differentiate between exceptions originating from BLOCK
and __exit__
because an exception that escapes the body of the with
will be passed to __exit__
which can decide how to handle it (see the docs). If however __exit__
raises itself, the original exception will be replaced by the new one. To deal with these cases we can add a general except
clause in the body of the with
to store any potential exception that would have otherwise escaped unnoticed and compare it with the one caught in the outermost except
later on - if they are the same this means the origin was BLOCK
or otherwise it was __exit__
(in case __exit__
suppresses the exception by returning a true value the outermost except
will simply not be executed).
try:
mgr = ContextManager() # __init__ could raise
except ValueError as err:
print('__init__ raised:', err)
else:
entered_body = exc_escaped_from_body = False
try:
with mgr:
entered_body = True # __enter__ did not raise at this point
try:
BLOCK
except TypeError: # catching another type (which we want to handle here)
pass
except Exception as err: # this exception would normally escape without notice
# we store this exception to check in the outer `except` clause
# whether it is the same (otherwise it comes from __exit__)
exc_escaped_from_body = err
raise # re-raise since we didn't intend to handle it, just needed to store it
except ValueError as err:
if not entered_body:
print('__enter__ raised:', err)
elif err is exc_escaped_from_body:
print('BLOCK raised:', err)
else:
print('__exit__ raised:', err)
PEP 343 -- The "with" Statement specifies an equivalent "non-with" version of the with
statement. Here we can readily wrap the various parts with try ... except
and thus differentiate between the different potential error sources:
import sys
try:
mgr = ContextManager()
except ValueError as err:
print('__init__ raised:', err)
else:
try:
value = type(mgr).__enter__(mgr)
except ValueError as err:
print('__enter__ raised:', err)
else:
exit = type(mgr).__exit__
exc = True
try:
try:
BLOCK
except TypeError:
pass
except:
exc = False
try:
exit_val = exit(mgr, *sys.exc_info())
except ValueError as err:
print('__exit__ raised:', err)
else:
if not exit_val:
raise
except ValueError as err:
print('BLOCK raised:', err)
finally:
if exc:
try:
exit(mgr, None, None, None)
except ValueError as err:
print('__exit__ raised:', err)
The need for such special exception handling should be quite rare and normally wrapping the whole with
in a try ... except
block will be sufficient. Especially if the various error sources are indicated by different (custom) exception types (the context managers need to be designed accordingly) we can readily distinguish between them. For example:
try:
with ContextManager():
BLOCK
except InitError: # raised from __init__
...
except AcquireResourceError: # raised from __enter__
...
except ValueError: # raised from BLOCK
...
except ReleaseResourceError: # raised from __exit__
...
There's now a new css3 property for this: text-decoration-color
So you can now have text in one color and a text-decoration underline - in a different color... without needing an extra 'wrap' element
p {_x000D_
text-decoration: underline;_x000D_
-webkit-text-decoration-color: red; /* safari still uses vendor prefix */_x000D_
text-decoration-color: red;_x000D_
}
_x000D_
<p>black text with red underline in one element - no wrapper elements here!</p>
_x000D_
NB:
1) Browser Support is limited at the moment to Firefox and Chrome (fully supported as of V57) and Safari
2) You could also use the text-decoration shorthand property which looks like this:
<text-decoration-line> || <text-decoration-style> || <text-decoration-color>
...so using the text-decoration
shorthand - the example above would simply be:
p {
text-decoration: underline red;
}
p {_x000D_
text-decoration: underline red;_x000D_
}
_x000D_
<p>black text with red underline in one element - no wrapper elements here!</p>
_x000D_
Use Enum
's static method, GetNames
. It returns a string[]
, like so:
Enum.GetNames(typeof(DataSourceTypes))
If you want to create a method that does only this for only one type of enum
, and also converts that array to a List
, you can write something like this:
public List<string> GetDataSourceTypes()
{
return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}
You will need Using System.Linq;
at the top of your class to use .ToList()
one way;
var = count("find me", Range("A1:A100"))
function count(find as string, lookin as range) As Long
dim cell As Range
for each cell in lookin
if (cell.Value = find) then count = count + 1 '//case sens
next
end function
I like to use Printable
with Raw Values
.
enum Audience: String, Printable {
case Public = "Public"
case Friends = "Friends"
case Private = "Private"
var description: String {
return self.rawValue
}
}
Then we can do:
let audience = Audience.Public.description // audience = "Public"
or
println("The value of Public is \(Audience.Public)")
// Prints "The value of Public is Public"
You can simulate capturing in vanilla awk too, without extensions. Its not intuitive though:
step 1. use gensub to surround matches with some character that doesnt appear in your string. step 2. Use split against the character. step 3. Every other element in the splitted array is your capture group.
$ echo 'ab cb ad' | awk '{ split(gensub(/a./,SUBSEP"&"SUBSEP,"g",$0),cap,SUBSEP); print cap[2]"|" cap[4] ; }' ab|ad
Sometime missing "jasmine" from tsconfig.json may cause this error. (TypeScript 2.X)
So add
"types": [
"node",
"jasmine"
]
to your tsconfig.json
file.
To add some clarification here, when you create your service, the service class uses the default 'wsdlLocation', which was inserted into it when the class was built from the wsdl. So if you have a service class called SomeService, and you create an instance like this:
SomeService someService = new SomeService();
If you look inside SomeService, you will see that the constructor looks like this:
public SomeService() {
super(__getWsdlLocation(), SOMESERVICE_QNAME);
}
So if you want it to point to another URL, you just use the constructor that takes a URL argument (there are 6 constructors for setting qname and features as well). For example, if you have set up a local TCP/IP monitor that is listening on port 9999, and you want to redirect to that URL:
URL newWsdlLocation = new URL("http://theServerName:9999/somePath");
SomeService someService = new SomeService(newWsdlLocation);
and that will call this constructor inside the service:
public SomeService(URL wsdlLocation) {
super(wsdlLocation, SOMESERVICE_QNAME);
}
The default limit for the length of the request line is 8190 bytes (see LimitRequestLine
directive). And if we subtract three bytes for the request method (i.e. GET
), eight bytes for the version information (i.e. HTTP/1.0
/HTTP/1.1
) and two bytes for the separating space, we end up with 8177 bytes for the URI path plus query.
You can make a numpy array immutable and use the first element:
numpyarrayname[0] = "write once"
then:
numpyarrayname.setflags(write=False)
or
numpyarrayname.flags.writeable = False
@Michiel is correct to create a button but the code for ActionScript 3 it is a little different - where movieClipName is the name of your 'button'.
movieClipName.addEventListener(MouseEvent.CLICK, callLink);
function callLink:void {
var url:String = "http://site";
var request:URLRequest = new URLRequest(url);
try {
navigateToURL(request, '_blank');
} catch (e:Error) {
trace("Error occurred!");
}
}
source: http://scriptplayground.com/tutorials/as/getURL-in-Actionscript-3/
I actually looked at this a little in the disassembler, since source isn't available.
/usr/bin/java and /usr/libexec/java_home both make use of JavaLaunching.framework. The JAVA_HOME environment variable is indeed checked first by /usr/bin/java and friends (but not /usr/libexec/java_home.) The framework uses the JAVA_VERSION and JAVA_ARCH envirionment variables to filter the available JVMs. So, by default:
$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
11.0.5, x86_64: "Amazon Corretto 11" /Library/Java/JavaVirtualMachines/amazon-corretto-11.jdk/Contents/Home
1.8.0_232, x86_64: "Amazon Corretto 8" /Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home
/Library/Java/JavaVirtualMachines/amazon-corretto-11.jdk/Contents/Home
But setting, say, JAVA_VERSION can override the default:
$ JAVA_VERSION=1.8 /usr/libexec/java_home
/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home
You can also set JAVA_LAUNCHER_VERBOSE=1 to see some additional debug logging as far as search paths, found JVMs, etc., with both /usr/bin/java and /usr/libexec/java_home.
In the past, JavaLaunching.framework actually used the preferences system (under the com.apple.java.JavaPreferences domain) to set the preferred JVM order, allowing the default JVM to be set with PlistBuddy - but as best as I can tell, that code has been removed in recent versions of macOS. Environment variables seem to be the only way (aside from editing the Info.plist in the JDK bundles themselves.)
Setting default environment variables can of course be done through your .profile or via launchd, if you need them be set at a session level.
Usage:
sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");
"
is shown as \"
in the debugger, but the data is correct in the string, and you don't need to replace anything. Try to dump your string to a file and you will note that the string is correct.
Yes, it is possible. The steps are:
First Put the .mdf
and .ldf
file in C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\
folder
Then go to sql software , Right-click “Databases” and click the “Attach” option to open the Attach Databases dialog box
Click the “Add” button to open and Locate Database Files From C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\
folder
Click the "OK" button. SQL Server Management Studio loads the database from the .MDF
file.
I recommend: if your search is simple , you can use `
column*1 = column
` operator interesting :) is work and faster than on fields varchar/char
SELECT * FROM myTable WHERE column*1 = column;
ABC*1 => 0 (NOT EQU **ABC**)
AB15*A => 15 (NOT EQU **AB15**)
15AB => 15 (NOT EQU **15AB**)
15 => 15 (EQUALS TRUE **15**)
I like to use Log.d(TAG, some string, often a String.format ()).
TAG is always the class name
Transform Log.d(TAG, --> Logd( in the text of your class
private void Logd(String str){
if (MainClass.debug) Log.d(className, str);
}
In this way when you are ready to make a release version, set MainClass.debug to false!
If you're using .NET 4.5 and want to use async then you can use HttpClient
in System.Net.Http
:
using (var httpClient = new HttpClient())
{
var json = await httpClient.GetStringAsync("url");
// Now parse with JSON.Net
}
The way you are trying to do it is called LBYL (look before you leap), since you are checking conditions before trying to increment your value.
The other approach is called EAFP (easier to ask forgiveness then permission). In that case, you would just try the operation (increment the value). If it fails, you catch the exception and set the value to 1. This is a slightly more Pythonic way to do it (IMO).
http://mail.python.org/pipermail/python-list/2003-May/205182.html
SELECT specific_name FROM `information_schema`.`ROUTINES` WHERE routine_schema='database_name'
I have thesame issue before but i solved it easily by just following this steps:
*connect your android phone in a debugging mode (to enable debugging mode goto settings scroll down About Phone scroll down tap seven times Build Number and it will automatically enable developer option turn on developer options and check USB debugging)
download Universal ADB Driver Installer
*choose Adb Driver Installer (Universal)
*install it *it will automatically detect your android device(any kind of brand) *chose the device and install
This is the Simple method, Use ParseExact
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result;
String dateString = "Sun 08 Jun 2013 8:30 AM -06:00";
String format = "ddd dd MMM yyyy h:mm tt zzz";
result = DateTime.ParseExact(dateString, format, provider);
This should work for you.
@praneeth-nidarshan has covered mostly all the steps, except some:
$ sudo apt-get install php-pear
sh: phpize: not found
ERROR: `phpize’ failed
$ sudo apt-get install php7.2-dev
$ sudo pecl install mcrypt-1.0.1
extension=mcrypt.so
to your php.ini configuration file; if you don't know where it is, search with:$ sudo php -i | grep 'Configuration File'
Try this. It uses the split
function which is a core part of javascript, nothing to do with jQuery.
var parts = html.split(":-"),
i, l
;
for (i = 0, l = parts.length; i < l; i += 2) {
$("#" + parts[i]).text(parts[i + 1]);
}
Ok, let me give the details of code, how to use other module's component.
For example, I have M2 module, M2 module have comp23 component and comp2 component, Now I want to use comp23 and comp2 in app.module, here is how:
this is app.module.ts, see my comment,
// import this module's ALL component, but not other module's component, only this module
import { AppComponent } from './app.component';
import { Comp1Component } from './comp1/comp1.component';
// import all other module,
import { SwModule } from './sw/sw.module';
import { Sw1Module } from './sw1/sw1.module';
import { M2Module } from './m2/m2.module';
import { CustomerDashboardModule } from './customer-dashboard/customer-dashboard.module';
@NgModule({
// declare only this module's all component, not other module component.
declarations: [
AppComponent,
Comp1Component,
],
// imports all other module only.
imports: [
BrowserModule,
SwModule,
Sw1Module,
M2Module,
CustomerDashboardModule // add the feature module here
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
this is m2 module:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// must import this module's all component file
import { Comp2Component } from './comp2/comp2.component';
import { Comp23Component } from './comp23/comp23.component';
@NgModule({
// import all other module here.
imports: [
CommonModule
],
// declare only this module's child component.
declarations: [Comp2Component, Comp23Component],
// for other module to use these component, must exports
exports: [Comp2Component, Comp23Component]
})
export class M2Module { }
My commend in code explain what you need to do here.
now in app.component.html, you can use
<app-comp23></app-comp23>
follow angular doc sample import modul
Usally, I end up writing a static class with properties to access each of the settings of my web.config.
public static class ConfigManager
{
public static string MyBaseDir
{
return ConfigurationManager.AppSettings["MyBaseDir"].toString();
}
public static string Dir1
{
return MyBaseDir + ConfigurationManager.AppSettings["Dir1"].toString();
}
}
Usually, I also do type conversions when required in this class. It allows to have a typed access to your config, and if settings change, you can edit them in only one place.
Usually, replacing settings with this class is relatively easy and provides a much greater maintainability.
An optional prefix
!
which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
http://schacon.github.com/git/gitignore.html
*.json
!spec/*.json
I just had a look at the source - Protractor is waiting for Angular only in a few cases (like when element.all
is invoked, or setting / getting location).
So Protractor won't wait for Angular to stabilise after every command.
Also, it looks like sometimes in my tests I had a race between Angular digest cycle and click event, so sometimes I have to do:
elm.click();
browser.driver.sleep(1000);
browser.waitForAngular();
using sleep to wait for execution to enter AngularJS context (triggered by click
event).
I had the same problem - I just removed the project from my workspace, then cleaned up the "eclipse files/folders, for example: .project, .settings, etc) then imported the maven project again, it worked.
Please try to avoid using takePersistableUriPermission method because it raised runtime exception for me. /** * Select from gallery. */
public void selectFromGallery() {
if (Build.VERSION.SDK_INT < AppConstants.KITKAT_API_VERSION) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
((Activity)mCalledContext).startActivityForResult(intent,AppConstants.GALLERY_INTENT_CALLED);
} else {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
((Activity)mCalledContext).startActivityForResult(intent, AppConstants.GALLERY_AFTER_KITKAT_INTENT_CALLED);
}
}
OnActivity for result to handle the image data:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//gallery intent result handling before kit-kat version
if(requestCode==AppConstants.GALLERY_INTENT_CALLED
&& resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
photoFile = new File(filePath);
mImgCropping.startCropImage(photoFile,AppConstants.REQUEST_IMAGE_CROP);
}
//gallery intent result handling after kit-kat version
else if (requestCode == AppConstants.GALLERY_AFTER_KITKAT_INTENT_CALLED
&& resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
InputStream input = null;
OutputStream output = null;
try {
//converting the input stream into file to crop the
//selected image from sd-card.
input = getApplicationContext().getContentResolver().openInputStream(selectedImage);
try {
photoFile = mImgCropping.createImageFile();
} catch (IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
output = new FileOutputStream(photoFile);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = input.read(bytes)) != -1) {
try {
output.write(bytes, 0, read);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
As others have stated there is no standard so you should choose one yourself. Here are a couple of things to consider when doing so:
If you are using JavaScript to consume JSON then using the same naming convention for properties in both will provide visual consistency and possibly some opportunities for cleaner code re-use.
A small reason to avoid kebab-case is that the hyphens may clash visually with -
characters that appear in values.
{
"bank-balance": -10
}
if you want see select query output in pl/sql you need to use a explicit cursor. Which will hold active data set and by fetching each row at a time it will show all the record from active data set as long as it fetches record from data set by iterating in loop. This data will not be generated in tabular format this result will be in plain text format. Hope this will be helpful. For any other query you may ask....
set serveroutput on;
declare
cursor c1 is
select foo, bar from foobar;
begin
for i in c1 loop
dbms_output.put_line(i.foo || ' ' || i.bar);
end loop;
end;
You can use jQuery UI and do something like this
Html:
<button id="callConfirm">Confirm!</button>
<div id="dialog" title="Confirmation Required">
Are you sure about this?
</div>?
Javascript:
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons : {
"Confirm" : function() {
alert("You have confirmed!");
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#callConfirm").on("click", function(e) {
e.preventDefault();
$("#dialog").dialog("open");
});
?
Use TO_TIMESTAMP function
TO_TIMESTAMP(date_string,'YYYY-MM-DD HH24:MI:SS')
Try this...
update [table_name] set [field_name] =
replace([field_name],'[string_to_find]','[string_to_replace]');
In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged
event:
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
// Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
// To work around this, we create the binding once we get the viewmodel through the datacontext.
var newViewModel = e.NewValue as MyViewModel;
var executablePathBinding = new Binding
{
Source = newViewModel,
Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
};
BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}
We have also had cases were we just saved the DataContext
to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext
around, I think it would be nice to also call:
BindingOperations.ClearBinding(myText, TextBlock.TextProperty);
to clear the binding of the old viewmodel (e.oldValue
in the event handler).
I see that you are looking for an implementation of the problem more than solving that error. Here you have a possible solution:
from itertools import chain
def involved(courses, person):
courses_info = chain.from_iterable(x.values() for x in courses.values())
return filter(lambda x: x['teacher'] == person, courses_info)
print involved(courses, 'Dave')
The first thing I do is getting the list of the courses and then filter by teacher's name.
you can also use this code
public static double roundToDecimals(double d, int c)
{
int temp = (int)(d * Math.pow(10 , c));
return ((double)temp)/Math.pow(10 , c);
}
It gives you control of how many numbers after the point are needed.
d = number to round;
c = number of decimal places
think it will be helpful
I would like to offer the following that worked in an automated capacity for me. It shows the sequence of steps and the relationship between setting the name first, then joining the domain. I use this in a script as an orchestration point for Win2008r2 and win2012r2 via Scalr CMP for EC2 and Openstack cloud instances.
$userid="$DOMAIN\$USERNAME"
$secure_string_pwd = convertto-securestring "SECRET_PASSWORD" -asplaintext -force
$creds = New-Object System.Management.Automation.PSCredential $userid,$secure_string_pwd
Rename-Computer "newhostname" -DomainCredential $creds -Force
WARNING: The changes will take effect after you restart the computer OLDHOSTNAME.
Add-Computer -NewName "newhostname" -DomainName $DOMAIN -Credential $creds \
-OUPath "OU=MYORG,OU=MYSUBORG,DC=THEDOMAIN,DC=Net" -Force
WARNING: The changes will take effect after you restart the computer OLDHOSTNAME.
Restart-Computer
One caveat is to be careful with the credentials, pull them from a key store rather than hard-coded as illustrated here ... but that's a different topic.
Thanks, everyone, for your answers.
Others have described the Null Coalescing Operator
quite well. In cases where a single test for null is required, the shortened syntax ??=
can add readability.
Legacy null test:
if (myvariable == null)
{
myvariable = new MyConstructor();
}
Using the Null Coalescing Operator this can be written:
myvariable = myvariable ?? new MyConstructor();
which can also be written with the shortened syntax:
myvariable ??= new MyConstructor();
Some find it more readable and succinct.
What really helped me here is spiv's tip (which I would vote up and comment on if I had the reputation points) for getting a stack trace out of an unprepared Python process. Except it didn't work until I modified the gdbinit script. So:
download http://svn.python.org/projects/python/trunk/Misc/gdbinit and put it in ~/.gdbinit
edit it, changing [edit: no longer needed; the linked file already has this change as of 2010-01-14]PyEval_EvalFrame
to PyEval_EvalFrameEx
Attach gdb: gdb -p PID
Get the python stack trace: pystack
You can do it with the code you have, you just need to ensure that html
and body
are set to 100% height.
Demo: http://jsfiddle.net/kevinPHPkevin/a7eGN/
html, body {
height:100%;
}
body {
background-color: white;
background-image: url('http://www.canvaz.com/portrait/charcoal-1.jpg');
background-size: auto 100%;
background-repeat: no-repeat;
background-position: left top;
}
I've given this answer a lot of thought, especially given the don't-parse-ls stuff. At first, I tried
<WARNING! DID NOT WORK>
du --inodes --files0-from=<(find . -maxdepth 1 -type f -print0) | awk '{sum+=int($1)}END{print sum}'
</WARNING! DID NOT WORK>
which worked if there was only a filename like
touch $'w\nlf.aa'
but failed if I made a filename like this
touch $'firstline\n3 and some other\n1\n2\texciting\n86stuff.jpg'
I finally came up with what I'm putting below. Note I was trying to get a count of all files in the directory (not including any subdirectories). I think it, along with the answers by @Mat and @Dan_Yard , as well as having at least most of the requirements set out by @mogsie (I'm not sure about memory.) I think the answer by @mogsie is correct, but I always try to stay away from parsing ls
unless it's an extremely specific situation.
awk -F"\0" '{print NF-1}' < <(find . -maxdepth 1 -type f -print0) | awk '{sum+=$1}END{print sum}'
More readably:
awk -F"\0" '{print NF-1}' < \
<(find . -maxdepth 1 -type f -print0) | \
awk '{sum+=$1}END{print sum}'
This is doing a find specifically for files, delimiting the output with a null character (to avoid problems with spaces and linefeeds), then counting the number of null characters. The number of files will be one less than the number of null characters, since there will be a null character at the end.
To answer the OP's question, there are two cases to consider
1) Non-recursive search:
awk -F"\0" '{print NF-1}' < \
<(find . -maxdepth 1 -type f -name "log*" -print0) | \
awk '{sum+=$1}END{print sum}'
2) Recursive search. Note that what's inside the -name
parameter might need to be changed for slightly different behavior (hidden files, etc.).
awk -F"\0" '{print NF-1}' < \
<(find . -type f -name "log*" -print0) | \
awk '{sum+=$1}END{print sum}'
If anyone would like to comment on how these answers compare to those I've mentioned in this answer, please do.
Note, I got to this thought process while getting this answer.
Notice that instance methods are also attributes (of the class) and that you could set them at the class or instance level if you really wanted to be a badass. Or that you may set a class variable (which is also an attribute of the class), where handy readonly properties won't work neatly out of the box. What I'm trying to say is that the "readonly attribute" problem is in fact more general than it's usually perceived to be. Fortunately there are conventional expectations at work that are so strong as to blind us wrt these other cases (after all, almost everything is an attribute of some sort in python).
Building upon these expectations I think the most general and lightweight approach is to adopt the convention that "public" (no leading underscore) attributes are readonly except when explicitly documented as writeable. This subsumes the usual expectation that methods won't be patched and class variables indicating instance defaults are better let alone. If you feel really paranoid about some special attribute, use a readonly descriptor as a last resource measure.
Using the Maven artifact org.json:json
I got the following code, which I think is quite short. Not as short as possible, but still usable.
package so4308554;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonReader {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
System.out.println(json.toString());
System.out.println(json.get("id"));
}
}
If you want to get an attribute-by-attribute comparison, and see if and where it fails, you can use the following list comprehension:
[i for i,j in
zip([getattr(obj_1, attr) for attr in dir(obj_1)],
[getattr(obj_2, attr) for attr in dir(obj_2)])
if not i==j]
The extra advantage here is that you can squeeze it one line and enter in the "Evaluate Expression" window when debugging in PyCharm.
$model = Mage::getModel('catalog/product'); //getting product model
$_products = $model->getCollection(); //getting product object for particular product id
foreach($_products as $_product) { ?>
<a href = '<?php echo $model->load($_product->getData("entity_id"))->getUrl_path(); ?>'> <img src= '<?php echo $model->load($_product->getData("entity_id"))->getImageUrl(); ?>' width="75px" height="75px"/></a>
<?php echo "<br/>".$model->load($_product->getData("entity_id"))->getPrice()."<br/>". $model->load($_product->getData("entity_id"))->getSpecial_price()."<br/>".$model->load($_product->getData("entity_id"))->getName()?>
<?php
You can use one of the following commands:
pip2 install SomePackage
pip3 install SomePackage
python2 -m pip install SomePackage
python3 -m pip install SomePackage
And of course, make sure that you have the correct version of pip installed
sudo apt-get install python-pip
sudo apt-get install python3-pip
I haven't used these commands myself but, some answers above suggests using them to specify exactly the version of python you want to use
pip-2.7 install SomePackage
python-3.6 -m pip install SomePackage
Taking @Ants Aasmas answer one step further, you can create a wrapper that takes any method call and forwards it to all elements of a given list:
class AllOf:
def __init__(self, elements):
self.elements = elements
def __getattr__(self, attr):
def on_all(*args, **kwargs):
for obj in self.elements:
getattr(obj, attr)(*args, **kwargs)
return on_all
That class can then be used like this:
class Foo:
def __init__(self, val="quux!"):
self.val = val
def foo(self):
print "foo: " + self.val
a = [ Foo("foo"), Foo("bar"), Foo()]
AllOf(a).foo()
Which produces the following output:
foo: foo foo: bar foo: quux!
With some work and ingenuity it could probably be enhanced to handle attributes as well (returning a list of attribute values).
You can still use installutil without visual studio, it is included with the .net framework
On your server, open a command prompt as administrator then:
CD C:\Windows\Microsoft.NET\Framework\v4.0.version (insert your version)
installutil "C:\Program Files\YourWindowsService\YourWindowsService.exe" (insert your service name/location)
To uninstall:
installutil /u "C:\Program Files\YourWindowsService\YourWindowsService.exe" (insert your service name/location)
Just to add to the other answers, the documentation gives this explanation:
KEY
is normally a synonym forINDEX
. The key attributePRIMARY KEY
can also be specified as justKEY
when given in a column definition. This was implemented for compatibility with other database systems.A
UNIQUE
index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, aUNIQUE
index permits multipleNULL
values for columns that can containNULL
.A
PRIMARY KEY
is a unique index where all key columns must be defined asNOT NULL
. If they are not explicitly declared asNOT NULL
, MySQL declares them so implicitly (and silently). A table can have only onePRIMARY KEY
. The name of aPRIMARY KEY
is alwaysPRIMARY
, which thus cannot be used as the name for any other kind of index.
The following steps can be followed
1) Download Jquery by clicking on this link DOWNLOAD
2) Copy the js file into your root web directory eg. www.test.com/jquery-1.3.2.min.js
3) In your index.php or index.html between the head tags include the following code, and then JQuery will be installed.
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
def querySet_to_list(qs):
"""
this will return python list<dict>
"""
return [dict(q) for q in qs]
def get_answer_by_something(request):
ss = Answer.objects.filter(something).values()
querySet_to_list(ss) # python list return.(json-able)
this code convert django queryset to python list
System.currentTimeMillis()
is not safe for elapsed time because this method is sensitive to the system realtime clock changes of the system.
You should use System.nanoTime
.
Please refer to Java System help:
About nanoTime method:
.. This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis()..
If you use System.currentTimeMillis()
your elapsed time can be negative (Back <-- to the future)
I had this issue when I was trying to render an object on a child component that was receiving props.
I fixed this when I realized that my code was trying to render an object and not the object key's value that I was trying to render.
label
is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center
but since the label is only as wide as the text you don't notice.
The best thing to do is to apply a specific width to the label
that is greater than the width of the content - this will give you the results you want.
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010_000;
use utf8;
binmode STDOUT, ":encoding(utf8)";
use Text::CSV_XS;
use FindBin;
use lib $FindBin::Bin . '/../lib';
use Net::Google::Spreadsheets::V4;
use Net::Google::DataAPI::Auth::OAuth2;
use lib 'lib';
use Term::Prompt;
use Net::Google::DataAPI::Auth::OAuth2;
use Net::Google::Spreadsheets;
use Data::Printer ;
my $oauth2 = Net::Google::DataAPI::Auth::OAuth2->new(
client_id => $ENV{CLIENT_ID},
client_secret => $ENV{CLIENT_SECRET},
scope => ['https://www.googleapis.com/auth/spreadsheets'],
);
my $url = $oauth2->authorize_url();
# system("open '$url'");
print "go to the following url with your browser \n" ;
print "$url\n" ;
my $code = prompt('x', 'paste code: ', '', '');
my $objToken = $oauth2->get_access_token($code);
my $refresh_token = $objToken->refresh_token() ;
print "my refresh token is : \n" ;
# debug p($refresh_token ) ;
p ( $objToken ) ;
my $gs = Net::Google::Spreadsheets::V4->new(
client_id => $ENV{CLIENT_ID}
, client_secret => $ENV{CLIENT_SECRET}
, refresh_token => $refresh_token
, spreadsheet_id => '1hGNULaWpYwtnMDDPPkZT73zLGDUgv5blwJtK7hAiVIU'
);
my($content, $res);
my $title = 'My foobar sheet';
my $sheet = $gs->get_sheet(title => $title);
# create a sheet if does not exit
unless ($sheet) {
($content, $res) = $gs->request(
POST => ':batchUpdate',
{
requests => [
{
addSheet => {
properties => {
title => $title,
index => 0,
},
},
},
],
},
);
$sheet = $content->{replies}[0]{addSheet};
}
my $sheet_prop = $sheet->{properties};
# clear all cells
$gs->clear_sheet(sheet_id => $sheet_prop->{sheetId});
# import data
my @requests = ();
my $idx = 0;
my @rows = (
[qw(name age favorite)], # header
[qw(tarou 31 curry)],
[qw(jirou 18 gyoza)],
[qw(saburou 27 ramen)],
);
for my $row (@rows) {
push @requests, {
pasteData => {
coordinate => {
sheetId => $sheet_prop->{sheetId},
rowIndex => $idx++,
columnIndex => 0,
},
data => $gs->to_csv(@$row),
type => 'PASTE_NORMAL',
delimiter => ',',
},
};
}
# format a header row
push @requests, {
repeatCell => {
range => {
sheetId => $sheet_prop->{sheetId},
startRowIndex => 0,
endRowIndex => 1,
},
cell => {
userEnteredFormat => {
backgroundColor => {
red => 0.0,
green => 0.0,
blue => 0.0,
},
horizontalAlignment => 'CENTER',
textFormat => {
foregroundColor => {
red => 1.0,
green => 1.0,
blue => 1.0
},
bold => \1,
},
},
},
fields => 'userEnteredFormat(backgroundColor,textFormat,horizontalAlignment)',
},
};
($content, $res) = $gs->request(
POST => ':batchUpdate',
{
requests => \@requests,
},
);
exit;
#Google Sheets API, v4
# Scopes
# https://www.googleapis.com/auth/drive View and manage the files in your Google D# # i# rive
# https://www.googleapis.com/auth/drive.file View and manage Google Drive files and folders that you have opened or created with this app
# https://www.googleapis.com/auth/drive.readonly View the files in your Google Drive
# https://www.googleapis.com/auth/spreadsheets View and manage your spreadsheets in Google Drive
# https://www.googleapis.com/auth/spreadsheets.readonly View your Google Spreadsheets
This works for me:
$.get("data.php", function(data){
var expected = ['justIn', 'recent', 'old'];
var outString = '';
$.each(expected, function(i, val){
var contentArray = data[val];
outString += '<ul><li><b>' + val + '</b>: ';
$.each(contentArray, function(i1, val2){
var textID = val2.textId;
var text = val2.text;
var textType = val2.textType;
outString += '<br />('+textID+') '+'<i>'+text+'</i> '+textType;
});
outString += '</li></ul>';
});
$('#contentHere').append(outString);
}, 'json');
This produces this output:
<div id="contentHere"><ul>
<li><b>justIn</b>:
<br />
(123) <i>Hello</i> Greeting<br>
(514) <i>What's up?</i> Question<br>
(122) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>recent</b>:
<br />
(1255) <i>Hello</i> Greeting<br>
(6564) <i>What's up?</i> Question<br>
(0192) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>old</b>:
<br />
(5213) <i>Hello</i> Greeting<br>
(9758) <i>What's up?</i> Question<br>
(7655) <i>Come over here</i> Order</li>
</ul></div>
And looks like this:
Also, remember to set the contentType
as 'json'
The /etc/apache2/httpd.conf
is empty in Ubuntu, because the Apache configuration resides in /etc/apache2/apache2.conf
!
“httpd.conf is for user options.” No it isn't, it's there for historic reasons.
Using Apache server, all user options should go into a new *.conf
-file inside /etc/apache2/conf.d/
. This method should be "update-safe", as httpd.conf
or apache2.conf
may get overwritten on the next server update.
Inside /etc/apache2/apache2.conf
, you will find the following line, which includes those files:
# Include generic snippets of statements
Include conf.d/
As of Apache 2.4+ the user configuration directory is /etc/apache2/conf-available/
. Use a2enconf FILENAME_WITHOUT_SUFFIX
to enable the new configuration file or manually create a symlink in /etc/apache2/conf-enabled/
. Be aware that as of Apache 2.4 the configuration files must have the suffix .conf
(e.g. conf-available/my-settings.conf
);
I had the same warning using the raster package.
> my_mask[my_mask[] != 1] <- NA
Error: cannot allocate vector of size 5.4 Gb
The solution is really simple and consist in increasing the storage capacity of R, here the code line:
##To know the current storage capacity
> memory.limit()
[1] 8103
## To increase the storage capacity
> memory.limit(size=56000)
[1] 56000
## I did this to increase my storage capacity to 7GB
Hopefully, this will help you to solve the problem Cheers
Kiwi Browser is mobile Chromium and allows installing extensions. Install Kiwi and then install "Mini JS console" Chrome extension(just search in Google and install from Chrome extensions website, uBlock also works ;). It will become available in Kiwi menu at the bottom and will show the console output for the current page.
In addition to Laurence's answer, if you also want to make it null-safe:
private static <T> boolean listEqualsIgnoreOrder(List<T> list1, List<T> list2) {
if (list1 == null)
return list2==null;
if (list2 == null)
return list1 == null;
return new HashSet<>(list1).equals(new HashSet<>(list2));
}
just copy " _CRT_SECURE_NO_WARNINGS " paste it on projects->properties->c/c++->preprocessor->preprocessor definitions click ok.it will work
there any rule I can follow to be sure that my app executes my own code just in the main thread?
Typically you wouldn't need to do anything to ensure this — your list of things is usually enough. Unless you're interacting with some API that happens to spawn a thread and run your code in the background, you'll be running on the main thread.
If you want to be really sure, you can do things like
[self performSelectorOnMainThread:@selector(myMethod:) withObject:anObj waitUntilDone:YES];
to execute a method on the main thread. (There's a GCD equivalent too.)
I had a similar issue and found out that if you have a class that contains transitions, the element will blink. I tried to add ng-cloak without success, but by removing the transition the button stopped blinking.
I'm using ionic framework and the button-outline has this transition
.button-outline {
-webkit-transition: opacity .1s;
transition: opacity .1s;
}
Simply overwrite the class to remove the transition and the button will stop blinking.
Update
Again on ionic there is a flicker when using ng-show/ng-hide. Adding the following CSS resolves it:
.ng-hide-add,
.ng-hide-remove {
display: none !important;
}
Source: http://forum.ionicframework.com/t/beta-14-ng-hide-show/14270/9
This article covers various ways of concatenating strings in SQL, including an improved version of your code which doesn't XML-encode the concatenated values.
SELECT ID, abc = STUFF
(
(
SELECT ',' + name
FROM temp1 As T2
-- You only want to combine rows for a single ID here:
WHERE T2.ID = T1.ID
ORDER BY name
FOR XML PATH (''), TYPE
).value('.', 'varchar(max)')
, 1, 1, '')
FROM temp1 As T1
GROUP BY id
To understand what's happening, start with the inner query:
SELECT ',' + name
FROM temp1 As T2
WHERE T2.ID = 42 -- Pick a random ID from the table
ORDER BY name
FOR XML PATH (''), TYPE
Because you're specifying FOR XML
, you'll get a single row containing an XML fragment representing all of the rows.
Because you haven't specified a column alias for the first column, each row would be wrapped in an XML element with the name specified in brackets after the FOR XML PATH
. For example, if you had FOR XML PATH ('X')
, you'd get an XML document that looked like:
<X>,aaa</X>
<X>,bbb</X>
...
But, since you haven't specified an element name, you just get a list of values:
,aaa,bbb,...
The .value('.', 'varchar(max)')
simply retrieves the value from the resulting XML fragment, without XML-encoding any "special" characters. You now have a string that looks like:
',aaa,bbb,...'
The STUFF
function then removes the leading comma, giving you a final result that looks like:
'aaa,bbb,...'
It looks quite confusing at first glance, but it does tend to perform quite well compared to some of the other options.
With 4 lines, I import a rss to an array.
$feed = implode(file('http://yourdomains.com/feed.rss'));
$xml = simplexml_load_string($feed);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
For a more complex solution
$feed = new DOMDocument();
$feed->load('file.rss');
$json = array();
$json['title'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$json['description'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$json['link'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
$json['item'] = array();
$i = 0;
foreach($items as $key => $item) {
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
$guid = $item->getElementsByTagName('guid')->item(0)->firstChild->nodeValue;
$json['item'][$key]['title'] = $title;
$json['item'][$key]['description'] = $description;
$json['item'][$key]['pubdate'] = $pubDate;
$json['item'][$key]['guid'] = $guid;
}
echo json_encode($json);
Most of the posts that I found will timeout after a second iteration. Particularly if you are looping through a bunch if images as I have been. So to improve the suggestions above here is the entire method:
public System.Drawing.Image DownloadImage(string imageUrl)
{
System.Drawing.Image image = null;
try
{
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
webRequest.AllowWriteStreamBuffering = true;
webRequest.Timeout = 30000;
webRequest.ServicePoint.ConnectionLeaseTimeout = 5000;
webRequest.ServicePoint.MaxIdleTime = 5000;
using (System.Net.WebResponse webResponse = webRequest.GetResponse())
{
using (System.IO.Stream stream = webResponse.GetResponseStream())
{
image = System.Drawing.Image.FromStream(stream);
}
}
webRequest.ServicePoint.CloseConnectionGroup(webRequest.ConnectionGroupName);
webRequest = null;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
return image;
}
You could also use the following, as of C# 6.0
string myString = null;
string result = myString?.ToUpper();
The string result will be null.
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
if [ $( ls <file> ) ]; then rm <file>; fi
Also, if you redirect your output with >
instead of >>
it will overwrite the previous file
When styling a file input, you shouldn't break any of native interaction the input provides.
The display: none
approach breaks the native drag and drop support.
To not break anything, you should use the opacity: 0
approach for the input, and position it using relative / absolute pattern in a wrapper.
Using this technique, you can easily style a click / drop zone for the user, and add custom class in javascript on dragenter
event to update styles and give user a feedback to let him see that he can drop a file.
HTML :
<label for="test">
<div>Click or drop something here</div>
<input type="file" id="test">
</label>
CSS :
input[type="file"] {
position: absolute;
left: 0;
opacity: 0;
top: 0;
bottom: 0;
width: 100%;
}
div {
position: absolute;
left: 0;
top: 0;
bottom: 0;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #ccc;
border: 3px dotted #bebebe;
border-radius: 10px;
}
label {
display: inline-block;
position: relative;
height: 100px;
width: 400px;
}
Here is a working example (with additional JS to handle dragover
event and dropped files).
https://jsfiddle.net/j40xvkb3/
Hope this helped !
You might want to take a look at Standard Compression Scheme for Unicode.
SQL Server 2008 R2 use it internally and can achieve up to 50% compression.
Take a look at sprintf()
and family.
Another tool is Google Analytix, which will also allow you to run metrics even if you can`t build the project in case of errors
For a production system, you can use this configuration :
--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT CONNECT ON DATABASE nova TO user;
--ACCESS SCHEMA
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO user;
--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL ON ALL TABLES IN SCHEMA public TO admin ;
Use the filename
property like this:
uriContent = "data:application/octet-stream;filename=filename.txt," +
encodeURIComponent(codeMirror.getValue());
newWindow=window.open(uriContent, 'filename.txt');
EDIT:
Apparently, there is no reliable way to do this. See: Is there any way to specify a suggested filename when using data: URI?
The RequestContext
is deprecated from Primefaces 6.2. From this version use the following:
if (componentID != null && PrimeFaces.current().isAjaxRequest()) {
PrimeFaces.current().ajax().update(componentID);
}
And to execute javascript from the backbean use this way:
PrimeFaces.current().executeScript(jsCommand);
If you want to set it to LF as default, you can go to File->Preferences->Settings and under user settings you can paste this line in below your other user settings.
"files.eol": "\n"
For example.
"git.confirmSync": false,
"window.zoomLevel": -1,
"workbench.activityBar.visible": true,
"editor.wordWrap": true,
"workbench.iconTheme": "vscode-icons",
"window.menuBarVisibility": "default",
"vsicons.projectDetection.autoReload": true,
"files.eol": "\n"
For users of GitHub, this worked for me:
git reset --hard <full_hash_of_commit_to_reset_to>
git push --force
This will "correct" the branch history on your local machine and the GitHub server, but anyone who has sync'ed this branch with the server since the bad commit will have the history on their local machine. If they have permission to push to the branch directly then these commits will show right back up when they sync.
All everyone else needs to do is the git reset
command from above to "correct" the branch on their local machine. Of course they would need to be wary of any local commits made to this branch after the target hash. Cherry pick/backup and reapply those as necessary, but if you are in a protected branch then the number of people who can commit directly to it is likely limited.
What's probably happening is that React thinks that only one MyInput
(unemployment-duration
) is added between the renders. As such, the job-title
never gets replaced with the unemployment-reason
, which is also why the predefined values are swapped.
When React does the diff, it will determine which components are new and which are old based on their key
property. If no such key is provided in the code, it will generate its own.
The reason why the last code snippet you provide works is because React essentially needs to change the hierarchy of all elements under the parent div
and I believe that would trigger a re-render of all children (which is why it works). Had you added the span
to the bottom instead of the top, the hierarchy of the preceding elements wouldn't change, and those element's wouldn't re-render (and the problem would persist).
Here's what the official React documentation says:
The situation gets more complicated when the children are shuffled around (as in search results) or if new components are added onto the front of the list (as in streams). In these cases where the identity and state of each child must be maintained across render passes, you can uniquely identify each child by assigning it a key.
When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused).
You should be able to fix this by providing a unique key
element yourself to either the parent div
or to all MyInput
elements.
For example:
render(){
if (this.state.employed) {
return (
<div key="employed">
<MyInput ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div key="notEmployed">
<MyInput ref="unemployment-reason" name="unemployment-reason" />
<MyInput ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
OR
render(){
if (this.state.employed) {
return (
<div>
<MyInput key="title" ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div>
<MyInput key="reason" ref="unemployment-reason" name="unemployment-reason" />
<MyInput key="duration" ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
Now, when React does the diff, it will see that the divs
are different and will re-render it including all of its' children (1st example). In the 2nd example, the diff will be a success on job-title
and unemployment-reason
since they now have different keys.
You can of course use any keys you want, as long as they are unique.
Update August 2017
For a better insight into how keys work in React, I strongly recommend reading my answer to Understanding unique keys in React.js.
Update November 2017
This update should've been posted a while ago, but using string literals in ref
is now deprecated. For example ref="job-title"
should now instead be ref={(el) => this.jobTitleRef = el}
(for example). See my answer to Deprecation warning using this.refs for more info.
You should keep in mind, that HTML is intended to DESCRIBE the content it contains.
So, if you wish to convey a paragraph, then do so.
Your comparison isn't exactly right, though. The more direct comparison would be
When to use a
<div>
instead of a<p>
?
as both are block level elements.
A <span>
is inline, much like an anchor (<a>
), <strong>
, emphasis (<em>
), etc., so bear in mind that by it's default nature in both html and in natural writing, that a paragraph will cause a break before and after itself, like a <div>
.
Sometimes, when styling things — inline things — a <span>
is great to give you something to "hook" the css to, but it is otherwise an empty tag devoid of semantic or stylistic meaning.
Notepad++ will only auto-insert subsequent indents if you manually indent the first line in a block; otherwise you can re-indent your code after the fact using TextFX > TextFX Edit > Reindent C++ code.
You should use a sticky footer solution such as this one :
* {
margin: 0;
}
html, body {
height: 100%;
}
.wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
height: 142px; /* .push must be the same height as .footer */
}
There are others like this;
* {margin:0;padding:0;}
/* must declare 0 margins on everything, also for main layout components use padding, not
vertical margins (top and bottom) to add spacing, else those margins get added to total height
and your footer gets pushed down a bit more, creating vertical scroll bars in the browser */
html, body, #wrap {height: 100%;}
body > #wrap {height: auto; min-height: 100%;}
#main {padding-bottom: 150px;} /* must be same height as the footer */
#footer {position: relative;
margin-top: -150px; /* negative value of footer height */
height: 150px;
clear:both;}
/* CLEAR FIX*/
.clearfix:after {content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;}
.clearfix {display: inline-block;}
/* Hides from IE-mac \*/
* html .clearfix { height: 1%;}
.clearfix {display: block;}
with the html:
<div id="wrap">
<div id="main" class="clearfix">
</div>
</div>
<div id="footer">
</div>
Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.
You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.
Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.
So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".
That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.
SOAP:
SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.
REST:
REST is a design concept.
The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.
It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)
Flickr's REST API goes further and lets you return images as well.
JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.
I created animation from pbm's answer with little modification
to make the aninmation run only once
in the other word the Animation appear with you scroll down only
private int lastPosition = -1;
private void setAnimation(View viewToAnimate, int position) {
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition) {
ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(new Random().nextInt(501));//to make duration random number between [0,501)
viewToAnimate.startAnimation(anim);
lastPosition = position;
}
}
and in onBindViewHolder
call the function
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.getTextView().setText("some text");
// call Animation function
setAnimation(holder.itemView, position);
}
String.prototype.padZero= function(len, c){
var s= this, c= c || '0';
while(s.length< len) s= c+ s;
return s;
}
dispite the name, you can left-pad with any character, including a space. I never had a use for right side padding, but that would be easy enough.
It could be done by getting the page title by Selenium and do assertion by using TestNG.
Import Assert class in the import section:
`import org.testng.Assert;`
Create a WebDriver object:
WebDriver driver=new FirefoxDriver();
Apply this to assert the title of the page:
Assert.assertEquals("Expected page title", driver.getTitle());
(shown in let's say cv2.imshow)
cv2.waitKey(0)
would continue after pressing "Scr" button (or its combination), but you can try this
cv2.waitKey(0)
input('')
cv2.waitkey(0) to give the program enough time to process everything you want to see in the imshow and input('')
to make it wait for you to press Enter in the console window
this works on python 3
To expand a bit on why the error happened: A forward slash at the beginning of a path means "start from the root of the filesystem, and look for the given path". No forward slash means "start from the current working directory, and look for the given path".
The path
/tmp/test.jpg
thus translates to looking for the file test.jpg in the tmp folder at the root of the filesystem (e.g. c:\ on windows, / on *nix), instead of the webapp folder. Adding a period (.) in front of the path explicitly changes this to read "start from the current working directory", but is basically the same as leaving the forward slash out completely.
./tmp/test.jpg = tmp/test.jpg
I'm working on Windows Server 2012. .NET Extensibility 4.5 feature is on. WebDAVModule removed. I was still getting 500.21 error on ASP.NET route '/docs'.
Changing 'skipManagedModules' to false fixed the problem.
<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="false">
<add initializationPage="/docs" />
</applicationInitialization>
Thanks to https://groups.google.com/forum/#!topic/bonobo-git-server/GbdMXdDO4tI
@section
is for defining a content are override from a shared view. Basically, it is a way for you to adjust your shared view (similar to a Master Page in Web Forms).
You might find Scott Gu's write up on this very interesting.
Edit: Based on additional question clarification
The @RenderSection
syntax goes into the Shared View, such as:
<div id="sidebar">
@RenderSection("Sidebar", required: false)
</div>
This would then be placed in your view with @Section
syntax:
@section Sidebar{
<!-- Content Here -->
}
In MVC3+ you can either define the Layout file to be used for the view directly or you can have a default view for all views.
Common view settings can be set in _ViewStart.cshtml which defines the default layout view similar to this:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
You can also set the Shared View to use directly in the file, such as index.cshtml directly as shown in this snippet.
@{
ViewBag.Title = "Corporate Homepage";
ViewBag.BodyID = "page-home";
Layout = "~/Views/Shared/_Layout2.cshtml";
}
There are a variety of ways you can adjust this setting with a few more mentioned in this SO answer.
For those who are using 2012-2013 versions, you can do this:
$('#from').datepicker('remove');
Then to enable it back:
$('#from').datepicker('add');
Here's the documentation.
To enable GZIP compression, you need to modify the configuration of the embedded Tomcat instance. To do so, you declare a EmbeddedServletContainerCustomizer
bean in your Java configuration and then register a TomcatConnectorCustomizer
with it.
For example:
@Bean
public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainerFactory factory) {
((TomcatEmbeddedServletContainerFactory) factory).addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override
public void customize(Connector connector) {
AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
httpProtocol.setCompression("on");
httpProtocol.setCompressionMinSize(64);
}
});
}
};
}
See the Tomcat documentation for more details on the various compression configuration options that are available.
You say that you want to selectively enable compression. Depending on your selection criteria, then the above approach may be sufficient. It enables you to control compression by the request's user-agent, the response's size, and the response's mime type.
If this doesn't meet your needs then I believe you will have to perform the compression in your controller and return a byte[] response with a gzip content-encoding header.
You can try the same with replacewith()
$('.click').click(function() {
// get the contents of the link that was clicked
var linkText = $(this).text();
// replace the contents of the div with the link text
$('#content-container').replaceWith(linkText);
// cancel the default action of the link by returning false
return false;
});
The .replaceWith()
method removes content from the DOM and inserts new content in its place with a single call.
Your program should not write temporary files (or anything else for that matter) to the program directory. Any program should use %TEMP% for temporary files and %APPDATA% for user specific application data. This has been true since Windows 2000/XP so you should change your aplication.
The problem is not Windows 7.
You can ask for appdata folder path:
string dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
or for TEMP path
string dir = Path.GetTempPath()
The most simple way is to use Record type Record<number, productDetails >
interface productDetails {
productId : number ,
price : number ,
discount : number
};
const myVar : Record<number, productDetails> = {
1: {
productId : number ,
price : number ,
discount : number
}
}
I tried the options in the existing answers, mainly the one marked correct which did not work in my scenario. However, what did work was using phpMyAdmin. Select the database and then select the table, from the bottom drop down menu select "Repair table".
You can covert numpy.ndarray
to object
using astype(object)
This will work:
>>> a = [np.zeros((224,224,3)).astype(object), np.zeros((224,224,3)).astype(object), np.zeros((224,224,13)).astype(object)]
Your diameter variable won't work because you're trying to store a String into a variable that will only accept a double. In order for it to work you will need to parse it
Ex:
diameter = Double.parseDouble(JOptionPane.showInputDialog("enter the diameter of a sphere.");
For Swift 3 :
import AVFoundation
/// **must** define instance variable outside, because .play() will deallocate AVAudioPlayer
/// immediately and you won't hear a thing
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else {
print("url not found")
return
}
do {
/// this codes for making this app ready to takeover the device audio
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
/// change fileTypeHint according to the type of your audio file (you can omit this)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)
// no need for prepareToPlay because prepareToPlay is happen automatically when calling play()
player!.play()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
}
The best practice for local assets is to put it inside assets.xcassets
and you load the file like this :
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else {
print("url not found")
return
}
do {
/// this codes for making this app ready to takeover the device audio
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
/// change fileTypeHint according to the type of your audio file (you can omit this)
/// for iOS 11 onward, use :
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/// else :
/// player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)
// no need for prepareToPlay because prepareToPlay is happen automatically when calling play()
player!.play()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
}
Try the following, note that when user refreshes the page, the value is "Male" again, data should be stored on database.
<p id="pTest">Male</p>
<button>change</button>
<script>
$('button').click(function(){
$('#pTest').text('test')
})
</script>
Well you can simply use Math.pow(a,b)
as you have used earlier and just convert its value by using (int)
before it. Below could be used as an example to it.
int x = (int) Math.pow(a,b);
where a
and b
could be double
or int
values as you want.
This will simply convert its output to an integer value as you required.
It must be synchronized, using an object lock, stateless, or immutable.
link: http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:
Viewport Changes
Viewport meta tags using
"width=device-width"
cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding"shrink-to-fit=no"
to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.
Here's a worked visual example which shows the difference upon loading the page in the two configurations.
The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw
). Note how in the first example the page is zoomed to fit when shrink-to-fit=no
is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.
The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.
Use Insert
method:
list.Insert(0, item);
Here is a really useful guide which solved my problem(OSX 10.13.6).
codesign -fs gdbc /usr/local/bin/gdb
in terminal: this asks for the root passwordHere is a good start maybe
Have a look in the examples for a number of different formating options Double.ToString(string)
Will be more portable in case of extending to other alphabets:
char='abcdefghijklmnopqrstuvwxyz'[code]
or, to be more compatible (with our beloved IE):
char='abcdefghijklmnopqrstuvwxyz'.charAt(code);
As many of the answer suggesting better solution is to use ArrayList. ArrayList size is not fixed and it is easily manageable.
It is resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.
Note that this implementation is not synchronized.
ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test1");
scripts.add("test2");
scripts.add("test3");
The best answer
sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));
Either you are quoting wrong or github has different recommendation on different pages or they may learned with time and updated their reco.
We strongly recommend using an SSH connection when interacting with GitHub. SSH keys are a way to identify trusted computers, without involving passwords. The steps below will walk you through generating an SSH key and then adding the public key to your GitHub account.
@mohammed, this is usually attributed to the authentication plugin that your mysql database is using.
By default and for some reason, mysql 8 default plugin is auth_socket. Applications will most times expect to log in to your database using a password.
If you have not yet already changed your mysql default authentication plugin, you can do so by:
1. Log in as root to mysql
2. Run this sql command:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password
BY 'password';
Replace 'password' with your root password. In case your application does not log in to your database with the root user, replace the 'root' user in the above command with the user that your application uses.
Digital ocean expounds some more on this here Installing Mysql
I will make my contribution here... why? just because :p Its a different implementation, based on the Any LINQ extension, and a delegate. Here it is:
public static class Extensions
{
public static int IndexOf<T>(
this IEnumerable<T> list,
Predicate<T> condition) {
int i = -1;
return list.Any(x => { i++; return condition(x); }) ? i : -1;
}
}
void Main()
{
TestGetsFirstItem();
TestGetsLastItem();
TestGetsMinusOneOnNotFound();
TestGetsMiddleItem();
TestGetsMinusOneOnEmptyList();
}
void TestGetsFirstItem()
{
// Arrange
var list = new string[] { "a", "b", "c", "d" };
// Act
int index = list.IndexOf(item => item.Equals("a"));
// Assert
if(index != 0)
{
throw new Exception("Index should be 0 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsLastItem()
{
// Arrange
var list = new string[] { "a", "b", "c", "d" };
// Act
int index = list.IndexOf(item => item.Equals("d"));
// Assert
if(index != 3)
{
throw new Exception("Index should be 3 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsMinusOneOnNotFound()
{
// Arrange
var list = new string[] { "a", "b", "c", "d" };
// Act
int index = list.IndexOf(item => item.Equals("e"));
// Assert
if(index != -1)
{
throw new Exception("Index should be -1 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsMinusOneOnEmptyList()
{
// Arrange
var list = new string[] { };
// Act
int index = list.IndexOf(item => item.Equals("e"));
// Assert
if(index != -1)
{
throw new Exception("Index should be -1 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsMiddleItem()
{
// Arrange
var list = new string[] { "a", "b", "c", "d", "e" };
// Act
int index = list.IndexOf(item => item.Equals("c"));
// Assert
if(index != 2)
{
throw new Exception("Index should be 2 but is: " + index);
}
"Test Successful".Dump();
}
If nothing happens even if you added all the annotation needed, try to add this dependency to your pom.xml
, I just faced the same problem and resolved it by adding this one here:
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.9</version>
</dependency>
Well, in this case the car
variable will be null
, so dereferencing it (as you do when you access car.length
) will throw a NullPointerException
.
In fact, you can't access that variable at all until some value has definitely been assigned to it - otherwise the compiler will complain that "variable car might not have been initialized".
What is it you're trying to do here (it's not clear to me exactly what "solution" you're looking for)?
Instead of early binding the reference, there's an open source project called NetOffice that abstracts this from your project, making life much easier. That way you don't have to rely on your users having a specific version of Office installed.
I have a case of multiple key-value replacement in one file around 1000 lines. And after replacement the file structure should keep the same. for example:
key1=value_tobe_replaced1
key2=value_tobe_replaced1
. .
. .
key1000=value_tobe_replaced1000
I've tried:
the voted answer from @elmotec for massedit.
answer from @Cecil Curry.
answer from @Keithel.
The three answers definitely helped me a lot but after test I found it costs nearly 40-50s for 1st and 2ed. 3rd is not suitable for multi-replacement so I fixed it.
Notice: refer to the answers before go on.
Here's my code:
start_time = datetime.datetime.now()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_file:
with open(abs_keypair_file) as kf:
for line in kf:
line_to_write = ''
match_flag = False
for (key, value) in tuple_list:
# print ' %s = %r' % (key, value)
if not re.search(patten, line, flags=re.I):
continue
line_to_write = re.sub(r'\$\({}\)'.format(key), value, line, flags=re.I)
match_flag = True
if not match_flag:
line_to_write = line
tmp_file.write(line_to_write)
shutil.copystat(abs_keypair_file, tmp_file.name)
shutil.move(tmp_file.name, abs_keypair_file)
time_costs = datetime.datetime.now() - start_time
print 'time costs: %s' % time_costs
time costs: 0:00:42.533879
start_time = datetime.datetime.now()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_file:
with open(abs_keypair_file) as kf:
text = kf.read()
for (key, value) in tuple_list:
text = re.sub(patten, value, text, flags=re.M|re.I)
tmp_file.write(text)
shutil.copystat(abs_keypair_file, tmp_file.name)
shutil.move(tmp_file.name, abs_keypair_file)
time_costs = datetime.datetime.now() - start_time
print 'time costs: %s' % time_costs
time costs: 0:00:00.348458
So I suggest if you match my case and your file size is not too large you may follow file replacement mode
.
How to replace if file size is huge? I have no idea.
Hope this helps.
First go through this tutorial for getting familiar with Android Google Maps and this for API 2.
To retrive the current location of device see this answer or this another answer and for API 2
Then you can get places near by your location using Google Place API and for use of Place Api see this blog.
After getting Placemarks of near by location use this blog with source code to show markers on map with balloon overlay with API 2.
You also have great sample to draw route between two points on map look here in these links Link1 and Link2 and this Great Answer.
After following these steps you will be easily able to do your application. The only condition is, you will have to read it and understand it, because like magic its not going to be complete in a click.
Is it really worth it? Every protection mechanism can be broken with sufficient determination. Consider your market, price of the product, amount of customers, etc.
If you want something more reliable then go down the path of hardware keys, but that's rather troublesome (for the user) and more expensive. Software solutions would be probably a waste of time and resources, and the only thing they would give you is the false sense of 'security'.
Few more ideas (none is perfect, as there is no perfect one).
And don't waste too much time on it, because the crackers have a lot of experience with the typical techniques and are few steps ahead of you. Unless you want to use a lot of resources, probably change the programming language (do it the Skype way).
You mention you are using Pandas (in your title). If so, there is no need to use an external library, you can just use to_datetime
>>> pandas.to_datetime('today').normalize()
Timestamp('2015-10-14 00:00:00')
This will always return today's date at midnight, irrespective of the actual time, and can be directly used in pandas to do comparisons etc. Pandas always includes 00:00:00 in its datetimes.
Replacing today
with now
would give you the date in UTC instead of local time; note that in neither case is the tzinfo (timezone) added.
In pandas versions prior to 0.23.x, normalize
may not have been necessary to remove the non-midnight timestamp.
By default std::map
(and std::set
) use operator<
to determine sorting. Therefore, you need to define operator<
on your class.
Two objects are deemed equivalent if !(a < b) && !(b < a)
.
If, for some reason, you'd like to use a different comparator, the third template argument of the map
can be changed, to std::greater
, for example.
#sorting first by age then profession,you can change it in function "fun".
a = []
def fun(v):
return (v[1],v[2])
# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John", 8, "Student"])
a.append(["Paul", 8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])
a.sort(key=fun)
print a
From http://hc.apache.org/httpclient-3.x/sslguide.html:
Protocol.registerProtocol("https",
new Protocol("https", new MySSLSocketFactory(), 443));
HttpClient httpclient = new HttpClient();
GetMethod httpget = new GetMethod("https://www.whatever.com/");
try {
httpclient.executeMethod(httpget);
System.out.println(httpget.getStatusLine());
} finally {
httpget.releaseConnection();
}
Where MySSLSocketFactory example can be found here. It references a TrustManager
, which you can modify to trust everything (although you must consider this!)
Another clever way from that ancient thread:
int age = (
Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) -
Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;
If you use eg. "id" you can do it this way:
(function() {_x000D_
let x = document.getElementById("idName");_x000D_
let y = document.getElementById("liName");_x000D_
_x000D_
y.addEventListener('click', function(e) {_x000D_
y.appendChild(x);_x000D_
});_x000D_
_x000D_
_x000D_
})();
_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
<title></title>_x000D_
<meta charset="UTF-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<p id="idName">TEXT</p>_x000D_
<ul>_x000D_
<li id="liName">_x000D_
_x000D_
</li>_x000D_
</ul>_x000D_
</body>_x000D_
<script src="js/scripts/script.js"></script>_x000D_
_x000D_
</html>
_x000D_
It is better to look up shadow:
.header{
-webkit-box-shadow: 0 -8px 73px 0 rgba(0,0,0,0.2);
-moz-box-shadow: 0 -8px 73px 0 rgba(0,0,0,0.2);
box-shadow: 0 -8px 73px 0 rgba(0,0,0,0.2);
}
this code is currently using on stackoverflow web.
There's some sort of bogus character at the end of that source. Try deleting the last line and adding it back.
I can't figure out exactly what's there, yet ...
edit — I think it's a zero-width space, Unicode 200B. Seems pretty weird and I can't be sure of course that it's not a Stackoverflow artifact, but when I copy/paste that last function including the complete last line into the Chrome console, I get your error.
A notorious source of such characters are websites like jsfiddle. I'm not saying that there's anything wrong with them — it's just a side-effect of something, maybe the use of content-editable input widgets.
If you suspect you've got a case of this ailment, and you're on MacOS or Linux/Unix, the od
command line tool can show you (albeit in a fairly ugly way) the numeric values in the characters of the source code file. Some IDEs and editors can show "funny" characters as well. Note that such characters aren't always a problem. It's perfectly OK (in most reasonable programming languages, anyway) for there to be embedded Unicode characters in string constants, for example. The problems start happening when the language parser encounters the characters when it doesn't expect them.
update INC.PROV_CSP_DEMO_ADDR_TEMP pd
set pd.practice_name = (
select PRSQ_COMMENT FROM INC.CMC_PRSQ_SITE_QA PRSQ
WHERE PRSQ.PRSQ_MCTR_ITEM = 'PRNM'
AND PRSQ.PRAD_ID = pd.provider_id
AND PRSQ.PRAD_TYPE = pd.prov_addr_type
AND ROWNUM = 1
)
Create the column:
ALTER TABLE yourtable ADD COLUMN combined VARCHAR(50);
Update the current values:
UPDATE yourtable SET combined = CONCAT(zipcode, ' - ', city, ', ', state);
Update all future values automatically:
CREATE TRIGGER insert_trigger
BEFORE INSERT ON yourtable
FOR EACH ROW
SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);
CREATE TRIGGER update_trigger
BEFORE UPDATE ON yourtable
FOR EACH ROW
SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);
---- in form level Declaration of cbx veriable---
Dim cbx as string
Private Sub comboBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comboBox1.Enter
cbx = Me.comboBox1.Text
End Sub
Private Sub comboBox1_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comboBox1.Leave
Me.comboBox1.Text = cbx
End Sub
IUS offers an installation script for subscribing to their repository and importing associated GPG keys. Make sure you’re in your home directory, and retrieve the script using curl:
curl 'https://setup.ius.io/' -o setup-ius.sh
sudo bash setup-ius.sh
Install Required Packages-:
sudo yum install -y mod_php70u php70u-cli php70u-mysqlnd php70u-json php70u-gd php70u-dom php70u-simplexml php70u-mcrypt php70u-intl
Swamibebop's solution works, but by taking advantage of table.*
syntax, we can avoid repeating the column names of the inner select
and get a simpler/shorter result:
SELECT @r := @r+1 ,
z.*
FROM(/* your original select statement goes in here */)z,
(SELECT @r:=0)y;
So that will give you:
SELECT @r := @r+1 ,
z.*
FROM(
SELECT itemID,
count(*) AS ordercount
FROM orders
GROUP BY itemID
ORDER BY ordercount DESC
)z,
(SELECT @r:=0)y;
The CSS one is much more maintainable and readable.
Here is the example to sort implemented linked list in java without using any standard java libraries.
package SelFrDemo;
class NodeeSort {
Object value;
NodeeSort next;
NodeeSort(Object val) {
value = val;
next = null;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public NodeeSort getNext() {
return next;
}
public void setNext(NodeeSort next) {
this.next = next;
}
}
public class SortLinkList {
NodeeSort head;
int size = 0;
NodeeSort add(Object val) {
// TODO Auto-generated method stub
if (head == null) {
NodeeSort nodee = new NodeeSort(val);
head = nodee;
size++;
return head;
}
NodeeSort temp = head;
while (temp.next != null) {
temp = temp.next;
}
NodeeSort newNode = new NodeeSort(val);
temp.setNext(newNode);
newNode.setNext(null);
size++;
return head;
}
NodeeSort sort(NodeeSort nodeSort) {
for (int i = size - 1; i >= 1; i--) {
NodeeSort finalval = nodeSort;
NodeeSort tempNode = nodeSort;
for (int j = 0; j < i; j++) {
int val1 = (int) nodeSort.value;
NodeeSort nextnode = nodeSort.next;
int val2 = (int) nextnode.value;
if (val1 > val2) {
if (nodeSort.next.next != null) {
NodeeSort CurrentNext = nodeSort.next.next;
nextnode.next = nodeSort;
nextnode.next.next = CurrentNext;
if (j == 0) {
finalval = nextnode;
} else
nodeSort = nextnode;
for (int l = 1; l < j; l++) {
tempNode = tempNode.next;
}
if (j != 0) {
tempNode.next = nextnode;
nodeSort = tempNode;
}
} else if (nodeSort.next.next == null) {
nextnode.next = nodeSort;
nextnode.next.next = null;
for (int l = 1; l < j; l++) {
tempNode = tempNode.next;
}
tempNode.next = nextnode;
nextnode = tempNode;
nodeSort = tempNode;
}
} else
nodeSort = tempNode;
nodeSort = finalval;
tempNode = nodeSort;
for (int k = 0; k <= j && j < i - 1; k++) {
nodeSort = nodeSort.next;
}
}
}
return nodeSort;
}
public static void main(String[] args) {
SortLinkList objsort = new SortLinkList();
NodeeSort nl1 = objsort.add(9);
NodeeSort nl2 = objsort.add(71);
NodeeSort nl3 = objsort.add(6);
NodeeSort nl4 = objsort.add(81);
NodeeSort nl5 = objsort.add(2);
NodeeSort NodeSort = nl5;
NodeeSort finalsort = objsort.sort(NodeSort);
while (finalsort != null) {
System.out.println(finalsort.getValue());
finalsort = finalsort.getNext();
}
}
}
Error (While using Visual Studio 2015 in win 10 64 bit machine):
Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The system cannot find the file specified.
Solution: Open IIS Go to current server – > Application Pools Select the application pool your 32-bit application will run under Click Advanced setting or Application Pool Default Set Enable 32-bit Applications to True
The above solution is solved my problem. Thanks.
Follow the steps given below:
Download Plugin Manager from here.
Extract the contents of zip file under "C:\Program Files\Notepad++"
Restart Notepad++
That's it !!
The first one creates a single lambda function and calls it ten times.
The second one doesn't call the function. It creates 10 different lambda functions. It puts all of those in a list. To make it equivalent to the first you need:
[(lambda x: x*x)(x) for x in range(10)]
Or better yet:
[x*x for x in range(10)]
There is one more way to run grunt on windows, without adding anything globally. This is a case when you don't have to do anything with %PATH%
if you have grunt and grunt-cli installed (without -g switch). Either by:
npm install grunt-cli
npm install [email protected]
Or by having that in your packages.json file like:
"devDependencies": {
"grunt-cli": "^1.2.0",
"grunt": "^0.4.5",
You can call grunt from your local installation by:
node node_modules\grunt-cli\bin\grunt --version
This is a solution for those who for some reasons don't want to or can't play with PATH, or have something else messing it all the time, for instance on a build agent.
Edit: Added versions as the grunt-cli works with grunt > 0.3
string str = "GoodMorning"
string strModified = str.Substring(0,5);
String file = "";
try {
InputStream is = new FileInputStream(filename);
String UTF8 = "utf8";
int BUFFER_SIZE = 8192;
BufferedReader br = new BufferedReader(new InputStreamReader(is,
UTF8), BUFFER_SIZE);
String str;
while ((str = br.readLine()) != null) {
file += str;
}
} catch (Exception e) {
}
Try this,.. :-)
c=0
words = ['challa','reddy','challa']
for idx, word in enumerate(words):
if idx==0:
firstword=word
print(firstword)
elif idx == len(words)-1:
lastword=word
print(lastword)
if firstword==lastword:
c=c+1
print(c)
In another case I'm able to use template literal ES6 with backticks, so for yours could be set as:
<img v-bind:src="`${imgPreUrl()}img/logo.png`">
The solution is well documented in the official docs: https://ipython.readthedocs.org/en/latest/install/kernel_install.html
I tried the first approach. Since I already had ipykernel
installed, simply running python3 -m ipykernel install --user
solved the problem.
May be this is useful to you.
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = @"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSUTF8StringEncoding
error:nil];
}
//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
//use simple alert from my library (see previous post for details)
[ASFunctions alert:content];
[content release];
}
Did you tried JQuery's scrollTo
method? http://demos.flesler.com/jquery/scrollTo/
Or you can extend JQuery and add your custom mentod:
jQuery.fn.extend({
scrollToMe: function () {
var x = jQuery(this).offset().top - 100;
jQuery('html,body').animate({scrollTop: x}, 400);
}});
Then you can call this method like:
$("#header").scrollToMe();
An alternative to @tv's answer:
var elems = $(parentSelect).nextAll(), count = elems.length;
elems.each( function(i) {
$(this).fadeOut(200, function() {
$(this).remove();
if (!--count) doMyThing();
});
});
Note that .each()
itself is synchronous — the statement that follows the call to .each()
will be executed only after the .each()
call is complete. However, asynchronous operations started in the .each()
iteration will of course continue on in their own way. That's the issue here: the calls to fade the elements are timer-driven animations, and those continue at their own pace.
The solution above, therefore, keeps track of how many elements are being faded. Each call to .fadeOut()
gets a completion callback. When the callback notices that it's counted through all of the original elements involved, some subsequent action can be taken with confidence that all of the fading has finished.
This is a four-year-old answer (at this point in 2014). A modern way to do this would probably involve using the Deferred/Promise mechanism, though the above is simple and should work just fine.
If message.value[] is string:
if message.value[0] in ('/', '\'):
do_stuff()
If it not str
The trick is to make an invisible anchor tag in the render()
and add a React ref
allowing to trigger a click once we have the axios response:
class Example extends Component {
state = {
ref: React.createRef()
}
exportCSV = () => {
axios.get(
'/app/export'
).then(response => {
let blob = new Blob([response.data], {type: 'application/octet-stream'})
let ref = this.state.ref
ref.current.href = URL.createObjectURL(blob)
ref.current.download = 'data.csv'
ref.current.click()
})
}
render(){
return(
<div>
<a style={{display: 'none'}} href='empty' ref={this.state.ref}>ref</a>
<button onClick={this.exportCSV}>Export CSV</button>
</div>
)
}
}
Here is the documentation: https://reactjs.org/docs/refs-and-the-dom.html. You can find a similar idea here: https://thewebtier.com/snippets/download-files-with-axios/.
If you want to use the SQL ISO standard INFORMATION_SCHEMA and not the SQL Server-specific sysobjects
, you can do this:
IF EXISTS (
SELECT ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME = N'FunctionName'
)
DROP FUNCTION [dbo].[FunctionName]
GO
From the man page, npm start:
runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.
Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.
Anyhow, what really happens is that npm looks in your package.json file, and if you have something like
"scripts": { "start": "coffee server.coffee" }
then it will do that. If npm can't find your start script, it defaults to:
node server.js
$('#new_user_form :input')
should be your way forward. Note the omission of the >
selector. A valid HTML form wouldn't allow for a input tag being a direct child of a form tag.
In addition to VAV's answer, The first one was most useful in my environment
select * from USER_ROLE_PRIVS where USERNAME='SAMPLE';
select * from USER_TAB_PRIVS where Grantee = 'SAMPLE';
select * from USER_SYS_PRIVS where USERNAME = 'SAMPLE';
The best way depends on whether you have a project with a package manager like npm.
Package manager
If you're using a package manager, use it to get popper.js like this:
npm install popper.js --save
CDN
For a prototype or playground environment (like http://codepen.io) or may just want a url to a CDN file:
https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.js https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.min.js
note: Bootstrap 4 requires the versions under the umd path (more info on popper/bs4).
Local file
Just save one of the CDN files to use locally. For example, paste one of these URLs in a browser, then Save As... to get a local copy.
https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.js https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.min.js
No, you cannot know when a page was last updated or last changed or uploaded to a server (which might, depending on interpretation, be three different things) just by accessing the page.
A server may, and should (according to the HTTP 1.1 protocol), send a Last-Modified
header, which you can find out in several ways, e.g. using Rex Swain’s HTTP Viewer. However, according to the protocol, this is just
“the date and time at which the origin server believes the variant was last modified”.
And the protocol realistically adds:
“The exact meaning of this header field depends on the implementation of the origin server and the nature of the original resource. For files, it may be just the file system last-modified time. For entities with dynamically included parts, it may be the most recent of the set of last-modify times for its component parts. For database gateways, it may be the last-update time stamp of the record. For virtual objects, it may be the last time the internal state changed.”
In practice, web pages are very often dynamically created from a Content Management System or otherwise, and in such cases, the Last-Modified
header typically shows a data stamp of creating the response, which is normally very close to the time of the request. This means that the header is practically useless in such cases.
Even in the case of a “static” page (the server simply picks up a file matching the request and sends it), the Last-Modified
date stamp normally indicates just the last write access to the file on the server. This might relate to a time when the file was restored from a backup copy, or a time when the file was edited on the server without making any change to the content, or a time when it was uploaded onto the server, possibly replacing an older identical copy. In these cases, assuming that the time stamp is technically correct, it indicates a time after which the page has not been changed (but not necessarily the time of last change).
If you've loaded jQuery, you can see if the height of the content is greater than the viewport height. If not, then you can make it that height (or a little less). I ran the following code in WVGA800 mode in the Android emulator, and then ran it on my Samsung Galaxy Tab, and in both cases it hid the addressbar.
$(document).ready(function() {
if (navigator.userAgent.match(/Android/i)) {
window.scrollTo(0,0); // reset in case prev not scrolled
var nPageH = $(document).height();
var nViewH = window.outerHeight;
if (nViewH > nPageH) {
nViewH -= 250;
$('BODY').css('height',nViewH + 'px');
}
window.scrollTo(0,1);
}
});
The standard procedures are:
If you are using the local server, run Django shell using python manage.py shell
. It will take you to the Django python environment and you are good to go.
@William You can use NewRow method of the datatable to get a blank datarow and with the schema as that of the datatable. You can populate this datarow and then add the row to the datatable using .Rows.Add(DataRow)
OR .Rows.InsertAt(DataRow, Position)
. The following is a stub code which you can modify as per your convenience.
//Creating dummy datatable for testing
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("col2", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("col3", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("col4", typeof(String));
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr[0] = "coldata1";
dr[1] = "coldata2";
dr[2] = "coldata3";
dr[3] = "coldata4";
dt.Rows.Add(dr);//this will add the row at the end of the datatable
//OR
int yourPosition = 0;
dt.Rows.InsertAt(dr, yourPosition);
ignoreParent() is a pure JavaScript solution.
It works as an intermediary layer that compares the coordinates of the mouse click with the coordinates of the child element/s. Two simple implementation steps:
1. Put the ignoreParent() code on your page.
2. Instead of the parent's original onclick="parentEvent();", write:
onclick="ignoreParent(['parentEvent()', 'child-ID']);"
You may pass IDs of any number of child elements to the function, and exclude others.
If you clicked on one of the child elements, the parent event doesn't fire. If you clicked on parent, but not on any of the child elements [provided as arguments], the parent event is fired.
I was recently looking for a nice solution to this without adding React-Bootstrap to my project (as Bootstrap 4 is about to be released).
This is my solution: https://jsfiddle.net/16j1se1q/1/
let Modal = React.createClass({
componentDidMount(){
$(this.getDOMNode()).modal('show');
$(this.getDOMNode()).on('hidden.bs.modal', this.props.handleHideModal);
},
render(){
return (
<div className="modal fade">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 className="modal-title">Modal title</h4>
</div>
<div className="modal-body">
<p>One fine body…</p>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" className="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
)
},
propTypes:{
handleHideModal: React.PropTypes.func.isRequired
}
});
let App = React.createClass({
getInitialState(){
return {view: {showModal: false}}
},
handleHideModal(){
this.setState({view: {showModal: false}})
},
handleShowModal(){
this.setState({view: {showModal: true}})
},
render(){
return(
<div className="row">
<button className="btn btn-default btn-block" onClick={this.handleShowModal}>Open Modal</button>
{this.state.view.showModal ? <Modal handleHideModal={this.handleHideModal}/> : null}
</div>
);
}
});
React.render(
<App />,
document.getElementById('container')
);
The main idea is to only render the Modal component into the React DOM when it is to be shown (in the App components render function). I keep some 'view' state that indicates whether the Modal is currently shown or not.
The 'componentDidMount' and 'componentWillUnmount' callbacks either hide or show the modal (once it is rendered into the React DOM) via Bootstrap javascript functions.
I think this solution nicely follows the React ethos but suggestions are welcome!
By default mongodb has no enabled access control, so there is no default user or password.
To enable access control, use either the command line option --auth
or security.authorization configuration file setting.
You can use the following procedure or refer to Enabling Auth in the MongoDB docs.
Start MongoDB without access control.
mongod --port 27017 --dbpath /data/db1
Connect to the instance.
mongo --port 27017
Create the user administrator.
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Re-start the MongoDB instance with access control.
mongod --auth --port 27017 --dbpath /data/db1
Authenticate as the user administrator.
mongo --port 27017 -u "myUserAdmin" -p "abc123" \
--authenticationDatabase "admin"
This is my solution in java 8:
public static Boolean isValidCity(String cityCode) {
return Arrays.stream(CITY_ENUM.values())
.map(CITY_ENUM::getCityCode)
.anyMatch(cityCode::equals);
}
Chrome, Safari, and IE 8+ come with built-in consoles (as part of a larger set of development tools). If you're using Firefox, getfirebug.com.
Any operation/function on different data structures is defined for particular actions. Here in your case i.e. removing an element, delete, Pop and remove. (If you consider sets, Add another operation - discard) Other confusing case is while adding. Insert/Append. For Demonstration, Let us Implement deque. deque is a hybrid linear data structure, where you can add elements / remove elements from both ends.(Rear and front Ends)
class Deque(object):
def __init__(self):
self.items=[]
def addFront(self,item):
return self.items.insert(0,item)
def addRear(self,item):
return self.items.append(item)
def deleteFront(self):
return self.items.pop(0)
def deleteRear(self):
return self.items.pop()
def returnAll(self):
return self.items[:]
In here, see the operations:
def deleteFront(self):
return self.items.pop(0)
def deleteRear(self):
return self.items.pop()
Operations have to return something. So, pop - With and without an index. If I don't want to return the value: del self.items[0]
Delete by value not Index:
remove :
list_ez=[1,2,3,4,5,6,7,8]
for i in list_ez:
if i%2==0:
list_ez.remove(i)
print list_ez
let us consider the case of sets.
set_ez=set_ez=set(range(10))
set_ez.remove(11)
# Gives Key Value Error.
##KeyError: 11
set_ez.discard(11)
# Does Not return any errors.
I work on 60-70% zoom vue and my dropdown are unreadable so I made this simple code to overcome the issue
Note that I selected first all my dropdown lsts (CTRL+mouse click), went on formula tab, clicked "define name" and called them "ProduktSelection"
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim KeyCells As Range
Set KeyCells = Range("ProduktSelection")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
ActiveWindow.Zoom = 100
End If
End Sub
I then have another sub
Private Sub Worksheet_Change(ByVal Target As Range)
where I come back to 65% when value is changed.
I once had this problem and solved it by installing mysql-server
, so make sure that you have installed the mysql-server
, not the mysql-client
or something else.
That error means the file /var/run/mysqld/mysqld.sock
doesn't exists, if you didn't install mysql-server
, then the file would not exist. So in that case, install it with
sudo apt-get install mysql-server
But if the mysql-server
is already installed and is running, then you need to check the config files.
The config files are:
/etc/my.cnf
/etc/mysql/my.cnf
/var/lib/mysql/my.cnf
In /etc/my.cnf
, the socket file config may be /tmp/mysql.sock
and in /etc/mysql/my.cnf
the socket file config may be /var/run/mysqld/mysqld.sock
. So, remove or rename /etc/mysql/my.cnf
, let mysql use /etc/my.cnf
, then the problem may solved.
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.text_entry, null);
//text_entry is an Layout XML file containing two text field to display in alert dialog
final EditText input1 = (EditText) textEntryView.findViewById(R.id.EditText1);
final EditText input2 = (EditText) textEntryView.findViewById(R.id.EditText2);
input1.setText("DefaultValue", TextView.BufferType.EDITABLE);
input2.setText("DefaultValue", TextView.BufferType.EDITABLE);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setIcon(R.drawable.icon)
.setTitle("Enter the Text:")
.setView(textEntryView)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog","TextEntry 1 Entered "+input1.getText().toString());
Log.i("AlertDialog","TextEntry 2 Entered "+input2.getText().toString());
/* User clicked OK so do some stuff */
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
Just use a different browser. Follow the steps given below to install Chrome extensions on your Android device.
Step 1: Open Google Play Store and download Yandex Browser. Install the browser on your phone.
Step 2: In the URL box of your new browser, open 'chrome.google.com/webstore’ by entering the same in the URL address.
Step 3: Look for the Chrome extension that you want and once you have it, tap on 'Add to Chrome.’
The added Chrome extension will now be automatically added to the Yandex browser.
Let me give my 2 cents of a real-world example-analogy close to IT.
Lets say you have a subscription site, e.g a wordpress site
Each user has a role, eg admin, subscriber and so on. Many users can be admins, subscribers etc..
So abstraction here is reflected in the fact that any user with admin role can do a set of things, it does not matter which specific user this is (this is an example of abstraction).
On the other hand, subscriber users do not have access to certain settings of the site, thus some internals of the application are encapsulated for plain subscribers (this is an example of encapsulation)
As one can see abstraction and encapsulation are relative concepts, they apply with respect to something specific.
One can follow this line of reasoning and explain polymoprhism and inheritance.
For example super-admin users could do all the things admin users could do, plus some more. Moreover, if admin roles get an update in functionality, super-admins would get the same update. Thus one can see here an example of inheritance, in that super-admin roles inherit all the properties of admin roles and extend them. Note that for most part of the site, admins are interchangeable with super-admins (meaning a super-admin user can easily be used in place of an admin user, but not vice-versa in general).
It's just an anonymous function that is executed right after it's created.
It's just as if you assigned it to a variable, and used it right after, only without the variable:
var f = function () {
};
f();
In jQuery there is a similar construct that you might be thinking of:
$(function(){
});
That is the short form of binding the ready
event:
$(document).ready(function(){
});
But the above two constructs are not IIFEs.
This link should get you started. Long story short, a div that has been styled to look like a scrollbar is used to catch click-and-drag events. Wired up to these events are methods that scroll the contents of another div which is set to an arbitrary height and typically has a css rule of overflow:scroll (there are variants on the css rules but you get the idea).
I'm all about the learning experience -- but after you've learned how it works, I recommend using a library (of which there are many) to do it. It's one of those "don't reinvent" things...
$('#newType option:first').prop('selected', true);
If double-clicking the .jar file in Windows Explorer works, then you should be able to use this:
start myapp.jar
in your batch file.
The Windows start
command does exactly the same thing behind the scenes as double-clicking a file.
As of others have explained how to do it using str_replace
, you can also use regex to achieve this.
$name = preg_replace('/\s+/', '_', $name);
Those are the most common used implementations of Collection.
ArrayList:
insert/delete at the end generally O(1) worst case O(n)
insert/delete in the middle O(n)
retrieve any position O(1)
LinkedList:
insert/delete in any position O(1) (note if you have a reference to the element)
retrieve in the middle O(n)
retrieve first or last element O(1)
Vector: don't use it. It is an old implementation similar to ArrayList but with all methods synchronized. It is not the correct approach for a shared list in a multithreading environment.
HashMap
insert/delete/retrieve by key in O(1)
TreeSet insert/delete/contains in O(log N)
HashSet insert/remove/contains/size in O(1)
Small tip for you. Microsoft frequently has 'launch parties' or 'launch events' in which they frequently distribute licensed, not for resale copies, of that product. I've gotten the last two versions of VS (2005 and 2008) by attending my local .NET user group chapter during those days.
You can do one of the following:
<?php
$data = 'My data';
function menugen() {
global $data;
echo "[" . $data . "]";
}
menugen();
Or
<?php
$data = 'My data';
function menugen() {
echo "[" . $GLOBALS['data'] . "]";
}
menugen();
That being said, overuse of globals can lead to some poor code. It is usually better to pass in what you need. For example, instead of referencing a global database object you should pass in a handle to the database and act upon that. This is called dependency injection. It makes your life a lot easier when you implement automated testing (which you should).
window.location is an object, not a string so you need to use window.location.href to get the actual string url
if (window.location.href.indexOf("?added-to-cart=555") >= 0) {
alert("found it");
}
If you're using the PageFactory pattern or already have a reference to your WebElement, then you probably want to set the attribute, using your existing reference to the WebElement. (Rather than doing a document.getElementById(...)
in your javascript)
The following sample allows you to set the attribute, using your existing WebElement reference.
Code Snippet
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.FindBy;
public class QuickTest {
RemoteWebDriver driver;
@FindBy(id = "foo")
private WebElement username;
public void exampleUsage(RemoteWebDriver driver) {
setAttribute(username, "attr", "10");
setAttribute(username, "value", "bar");
}
public void setAttribute(WebElement element, String attName, String attValue) {
driver.executeScript("arguments[0].setAttribute(arguments[1], arguments[2]);",
element, attName, attValue);
}
}
Thank you to SLaks and jpm for their help. It was a pretty simple error that I simply did not see.
As SLaks pointed out, br.readLine() was being called twice each loop which made the program only get half of the values. Here is the fixed code:
try{
InputStream fis=new FileInputStream(targetsFile);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
String words[]=new String[5];
String line=null;
while((line=br.readLine())!=null){
words=line.split(" ");
int targetX=Integer.parseInt(words[0]);
int targetY=Integer.parseInt(words[1]);
int targetW=Integer.parseInt(words[2]);
int targetH=Integer.parseInt(words[3]);
int targetHits=Integer.parseInt(words[4]);
Target a=new Target(targetX, targetY, targetW, targetH, targetHits);
targets.add(a);
}
br.close();
}
catch(Exception e){
System.err.println("Error: Target File Cannot Be Read");
}
Thanks again! You guys are great!
Try:
CREATE USER 'golden'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'golden'@'localhost';
FLUSH PRIVILEGES;
Or even better use: mysql_setpermission
to create the user
Mongoose 4.4 added a method called insertMany
Shortcut for validating an array of documents and inserting them into MongoDB if they're all valid. This function is faster than .create() because it only sends one operation to the server, rather than one for each document.
Quoting vkarpov15 from issue #723:
The tradeoffs are that insertMany() doesn't trigger pre-save hooks, but it should have better performance because it only makes 1 round-trip to the database rather than 1 for each document.
The method's signature is identical to create
:
Model.insertMany([ ... ], (err, docs) => {
...
})
Or, with promises:
Model.insertMany([ ... ]).then((docs) => {
...
}).catch((err) => {
...
})
Here is an example straight from PHP.net
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
in the foreach you can do a comparison of each key to something that you are looking for
For me:
.ui-jqgrid .ui-jqgrid-bdiv {
position: relative;
margin: 0;
padding: 0;
overflow-y: auto; <------
overflow-x: hidden; <-----
text-align: left;
}
Of course remove the arrows
You should follow the Google guide;
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
} else {
// The toggle is disabled
}
}
});
You can check the documentation here