Using the C# language constructs, you cannot explicitly call the base function from outside the scope of A
or B
. If you really need to do that, then there is a flaw in your design - i.e. that function shouldn't be virtual to begin with, or part of the base function should be extracted to a separate non-virtual function.
You can from inside B.X however call A.X
class B : A
{
override void X() {
base.X();
Console.WriteLine("y");
}
}
But that's something else.
As Sasha Truf points out in this answer, you can do it through IL. You can probably also accomplish it through reflection, as mhand points out in the comments.
We can use ng-src
but when ng-src's value
became null
, ''
or undefined
, ng-src
will not work.
So just use ng-if
for this case:
http://jsfiddle.net/Hx7B9/299/
<div ng-app>
<div ng-controller="AppCtrl">
<a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
<button ng-click="changeLink()">Change Image</button>
</div>
</div>
Another dirty but working workaround. Assumes you are on top level of your package.
import sys
from os.path import dirname, basename
if __package__ is None:
sys.path.append('..')
__package__ = basename(dirname(sys.argv[0]))
from . import your_module
The advantage vs another answer here is that you don't need to change imports which are autogenerated by IDE.
Try this. I purposely broke out various parts so you can move things around.
library(sfsmisc)
#Generate the data
x <- 1:100000
y <- 1:100000
#Setup the plot area
par(pty="m", plt=c(0.1, 1, 0.1, 1), omd=c(0.1,0.9,0.1,0.9))
#Plot a blank graph without completing the x or y axis
plot(x, y, type = "n", xaxt = "n", yaxt="n", xlab="", ylab="", log = "x", col="blue")
mtext(side=3, text="Test Plot", line=1.2, cex=1.5)
#Complete the x axis
eaxis(1, padj=-0.5, cex.axis=0.8)
mtext(side=1, text="x", line=2.5)
#Complete the y axis and add the grid
aty <- seq(par("yaxp")[1], par("yaxp")[2], (par("yaxp")[2] - par("yaxp")[1])/par("yaxp")[3])
axis(2, at=aty, labels=format(aty, scientific=FALSE), hadj=0.9, cex.axis=0.8, las=2)
mtext(side=2, text="y", line=4.5)
grid()
#Add the line last so it will be on top of the grid
lines(x, y, col="blue")
I've been searching for a simpler solution using only loops and if statements, and this is what I came up with. The program also works with negative integers and correctly rejects any mixed inputs that may contain both integers and other characters.
#include <stdio.h>
#include <stdlib.h> // Used for atoi() function
#include <string.h> // Used for strlen() function
#define TRUE 1
#define FALSE 0
int main(void)
{
char n[10]; // Limits characters to the equivalent of the 32 bits integers limit (10 digits)
int intTest;
printf("Give me an int: ");
do
{
scanf(" %s", n);
intTest = TRUE; // Sets the default for the integer test variable to TRUE
int i = 0, l = strlen(n);
if (n[0] == '-') // Tests for the negative sign to correctly handle negative integer values
i++;
while (i < l)
{
if (n[i] < '0' || n[i] > '9') // Tests the string characters for non-integer values
{
intTest = FALSE; // Changes intTest variable from TRUE to FALSE and breaks the loop early
break;
}
i++;
}
if (intTest == TRUE)
printf("%i\n", atoi(n)); // Converts the string to an integer and prints the integer value
else
printf("Retry: "); // Prints "Retry:" if tested FALSE
}
while (intTest == FALSE); // Continues to ask the user to input a valid integer value
return 0;
}
This isn't going to be exactly perfect though I was happy to discover that you can control the horizontal and vertical border-spacing separately:
table
{
border-collapse: separate;
border-spacing: 0 8px;
}
In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:
# Close XAMPP sites here
<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Deny from all
Allow from ::1 127.0.0.0/8
ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
</LocationMatch>
and add
"Allow from all"
after Allow from ::1 127.0.0.0/8 {line}
Restart xampp, and you are done.
In later versions of Xampp
...you can simply remove this part
#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Require local
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
from the same file and it should work over the local network.
You can declare columns/variables as varchar2(n CHAR) and varchar2(n byte).
n CHAR means the variable will hold n characters. In multi byte character sets you don't always know how many bytes you want to store, but you do want to garantee the storage of a certain amount of characters.
n bytes means simply the number of bytes you want to store.
varchar is deprecated. Do not use it. What is the difference between varchar and varchar2?
Declare @fs_e int, @C_Tables CURSOR, @Table varchar(50)
SET @C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN @C_Tables
FETCH @C_Tables INTO @Table
SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'
WHILE ( @fs_e <> -1)
BEGIN
exec('Select * from ' + @Table)
FETCH @C_Tables INTO @Table
SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'
END
Security Notice: Basing the cookie off an MD5 hash of deterministic data is a bad idea; it's better to use a random token derived from a CSPRNG. See ircmaxell's answer to this question for a more secure approach.
Usually I do something like this:
Off course you can use different cookie names etc. also you can change the content of the cookie a bit, just make sure it isn't to easily created. You can for example also create a user_salt when the user is created and also put that in the cookie.
Also you could use sha1 instead of md5 (or pretty much any algorithm)
letsay $infile = a.csv //file needs to be imported.
class blah
{
static public function readJobsFromFile($file)
{
if (($handle = fopen($file, "r")) === FALSE)
{
echo "readJobsFromFile: Failed to open file [$file]\n";
die;
}
$header=true;
$index=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
// ignore header
if ($header == true)
{
$header = false;
continue;
}
if ($data[0] == '' && $data[1] == '' ) //u have oly 2 fields
{
echo "readJobsFromFile: No more input entries\n";
break;
}
$a = trim($data[0]);
$b = trim($data[1]);
if (check_if_exists("SELECT count(*) FROM Db_table WHERE a='$a' AND b='$b'") === true)
{
$index++;
continue;
}
$sql = "INSERT INTO DB_table SET a='$a' , b='$b' ";
@mysql_query($sql) or die("readJobsFromFile: " . mysql_error());
$index++;
}
fclose($handle);
return $index; //no. of fields in database.
}
function
check_if_exists($sql)
{
$result = mysql_query($sql) or die("$sql --" . mysql_error());
if (!$result) {
$message = 'check_if_exists::Invalid query: ' . mysql_error() . "\n";
$message .= 'Query: ' . $sql;
die($message);
}
$row = mysql_fetch_assoc ($result);
$count = $row['count(*)'];
if ($count > 0)
return true;
return false;
}
$infile=a.csv;
blah::readJobsFromFile($infile);
}
hope this helps.
This is a hibernate.cfg.xml for posgresql and it will help you with basic hibernate configurations for posgresql.
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>
<property name="connection_pool_size">1</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping class="org.javabrains.sanjaya.dto.UserDetails"/>
</session-factory>
</hibernate-configuration>
In my case it was the distinction between –
(En dash) and -
(Hyphen) as in:
Add-Type –Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
and:
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Dashes, Hyphens, and Minus signs oh my!
It depends on your requirements, specially volume, users and frequency of search. But, for small or medium office, the best option is to use an application like Apple Photos or Adobe Lighroom. They are specialized to store, catalog, index, and organize this kind of resource. But, for large organizations, with strong requirements of storage and high number of users, it is recommend instantiate an Content Management plataform with a Digital Asset Management, like Nuxeo or Alfresco; both offers very good resources do manage very large volumes of data with simplified methods to retrive them. And, very important: there is an free (open source) option for both platforms.
I know you have a couple good solid answers, but do you know about the # operator in the C preprocessor?
It lets you do this:
#define MACROSTR(k) #k
typedef enum {
kZero,
kOne,
kTwo,
kThree
} kConst;
static char *kConstStr[] = {
MACROSTR(kZero),
MACROSTR(kOne),
MACROSTR(kTwo),
MACROSTR(kThree)
};
static void kConstPrinter(kConst k)
{
printf("%s", kConstStr[k]);
}
Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation
SAX:
Parses node by node
Does not store the XML in memory
We cant insert or delete a node
Top to bottom traversing
DOM
Stores the entire XML document into memory before processing
Occupies more memory
We can insert or delete nodes
Traverse in any direction.
If we need to find a node and does not need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.
Angular 2 Provides a very nice feature called as Opaque Constants. Create a class & Define all the constants there using opaque constants.
import { OpaqueToken } from "@angular/core";
export let APP_CONFIG = new OpaqueToken("my.config");
export interface MyAppConfig {
apiEndpoint: string;
}
export const AppConfig: MyAppConfig = {
apiEndpoint: "http://localhost:8080/api/"
};
Inject it in providers in app.module.ts
You will be able to use it across every components.
EDIT for Angular 4 :
For Angular 4 the new concept is Injection Token & Opaque token is Deprecated in Angular 4.
Injection Token Adds functionalities on top of Opaque Tokens, it allows to attach type info on the token via TypeScript generics, plus Injection tokens, removes the need of adding @Inject
Example Code
Angular 2 Using Opaque Tokens
const API_URL = new OpaqueToken('apiUrl'); //no Type Check
providers: [
{
provide: DataService,
useFactory: (http, apiUrl) => {
// create data service
},
deps: [
Http,
new Inject(API_URL) //notice the new Inject
]
}
]
Angular 4 Using Injection Tokens
const API_URL = new InjectionToken<string>('apiUrl'); // generic defines return value of injector
providers: [
{
provide: DataService,
useFactory: (http, apiUrl) => {
// create data service
},
deps: [
Http,
API_URL // no `new Inject()` needed!
]
}
]
Injection tokens are designed logically on top of Opaque tokens & Opaque tokens are deprecated in Angular 4.
This error shows up when you are treating an array or string as a Hash. In this line myHash.each do |item|
you are assigning item
to a two-element array [key, value]
, so item[:symbol]
throws an error.
If you are here because of the Liquibase error saying:
Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short
and you are using
not {
indexExists()
}
precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342
We can try to execute an above check using bare sqlCheck
(Postgres):
SELECT COUNT(i.relname)
FROM
pg_class t,
pg_class i,
pg_index ix
WHERE
t.oid = ix.indrelid
and i.oid = ix.indexrelid
and t.relkind = 'r'
and t.relname = 'tableName'
and i.relname = 'indexName';
where tableName
- is an index table name and indexName
- is an index name
Make sure you verify your setting for "Prefer 32-bit". In my case Visual Studio 2012 had this setting checked by default. Trying to use anything from an external DLL failed until I unchecked "Prefer 32-bit".
In short:
getPath()
gets the path string that the File
object was constructed with, and it may be relative current directory.getAbsolutePath()
gets the path string after resolving it against the current directory if it's relative, resulting in a fully qualified path.getCanonicalPath()
gets the path string after resolving any relative path against current directory, and removes any relative pathing (.
and ..
), and any file system links to return a path which the file system considers the canonical means to reference the file system object to which it points.Also, each of these has a File equivalent which returns the corresponding File
object.
Note that IMO, Java got the implementation of an "absolute" path wrong; it really should remove any relative path elements in an absolute path. The canonical form would then remove any FS links or junctions in the path.
I've used the below before, and it has worked. It isn't very pretty, but you can alter it to suit your needs.
The following JavaScript function grabs the location.href
& document.title
for the sharer, and you can ultimately change these.
function fbs_click() {
u=location.href;
t=document.title;
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),
'sharer',
'toolbar=0,status=0,width=626,height=436');
return false;
}
Usage:
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" onclick="return fbs_click()" target="_blank">
Share on Facebook
</a>
It looks like this is what you could possibly be looking for: Facebook sharer title / desc....
Your code works for me. Here is my test case:
mysql> CREATE TABLE carmake (country ENUM('Canada', 'United States'));
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW CREATE TABLE carmake;
+---------+-------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+-------------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
`country` enum('Canada','United States') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+-------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia');
Query OK, 0 rows affected (0.53 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SHOW CREATE TABLE carmake;
+---------+--------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+--------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
`country` enum('Sweden','Malaysia') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+--------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
What error are you seeing?
FWIW this would also work:
ALTER TABLE carmake MODIFY COLUMN country ENUM('Sweden','Malaysia');
I would actually recommend a country table rather than enum column. You may have hundreds of countries which would make for a rather large and awkward enum.
EDIT: Now that I can see your error message:
ERROR 1265 (01000): Data truncated for column 'country' at row 1.
I suspect you have some values in your country column that do not appear in your ENUM
. What is the output of the following command?
SELECT DISTINCT country FROM carmake;
ANOTHER EDIT: What is the output of the following command?
SHOW VARIABLES LIKE 'sql_mode';
Is it STRICT_TRANS_TABLES
or STRICT_ALL_TABLES
? That could lead to an error, rather than the usual warning MySQL would give you in this situation.
YET ANOTHER EDIT: Ok, I now see that you definitely have values in the table that are not in the new ENUM
. The new ENUM
definition only allows 'Sweden'
and 'Malaysia'
. The table has 'USA'
, 'India'
and several others.
LAST EDIT (MAYBE): I think you're trying to do this:
ALTER TABLE carmake CHANGE country country ENUM('Italy', 'Germany', 'England', 'USA', 'France', 'South Korea', 'Australia', 'Spain', 'Czech Republic', 'Sweden', 'Malaysia') DEFAULT NULL;
I slightly modified the printer example to make it more explainable
1 document which had 2 pages content was sent to printer
Transaction - document sent to printer
Hope this helps someone to get the hang of the concept of ACID
ActiveSheet.UsedRange.Rows.Count + ActiveSheet.UsedRange.Rows(1).Row -1
Short. Safe. Fast. Will return the last non-empty row even if there are blank lines on top of the sheet, or anywhere else. Works also for an empty sheet (Excel reports 1 used row on an empty sheet so the expression will be 1). Tested and working on Excel 2002 and Excel 2010.
Add this to your web config and change the catalog name which is your database name:
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True;"/></connectionStrings>
Reference System.Configuration assembly in your project.
Here is how you retrieve connection string from the config file:
System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Click here to see full program
Sample code:
public static void main(String args[]) {
int number = 333;
int sum = 0;
int num = number;
while (num > 0) {
int lastDigit = num % 10;
sum += lastDigit;
num /= 10;
}
System.out.println("Sum of digits : "+sum);
}
You might use Osync: http://www.netpower.fr/osync , which is rsync based with intelligent deletion propagation. it has also multiple options like resuming a halted execution, soft deletion, and time control.
try to fix type="JavaScript"
to type="text/javascript"
in you vue.js srcipt tag, or just remove it.
Modern browsers will take script tag as javascript as default.
In python there are no arrays, lists are used instead. There are various ways to delete an object from a list:
my_list = [1,2,4,6,7]
del my_list[1] # Removes index 1 from the list
print my_list # [1,4,6,7]
my_list.remove(4) # Removes the integer 4 from the list, not the index 4
print my_list # [1,6,7]
my_list.pop(2) # Removes index 2 from the list
In your case the appropriate method to use is pop, because it takes the index to be removed:
x = object()
y = object()
array = [x, y]
array.pop(0)
# Using the del statement
del array[0]
You should be using @RequestParam
instead of @ModelAttribute
, e.g.
@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id,
@RequestParam String someAttr) {
}
You can even omit @RequestParam
altogether if you choose, and Spring will assume that's what it is:
@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id,
String someAttr) {
}
org.json.simple.JSONObject.escape()
escapes quotes,, /, \r, \n, \b, \f, \t and other control characters.
import org.json.simple.JSONValue;
JSONValue.escape("test string");
Add pom.xml when using maven
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<scope>test</scope>
</dependency>
To select data in numerical range you can use BETWEEN
which is inclusive.
SELECT JOB FROM MYTABLE WHERE ID BETWEEN 10 AND 15;
An extension to Florian Winter answer for people looking to generate ready to execute query.
drop
and insertMany
query using cursor
:
{
// collection name
var collection_name = 'foo';
// query
var cursor = db.getCollection(collection_name).find({});
// drop collection and insert script
print('db.' + collection_name + '.drop();');
print('db.' + collection_name + '.insertMany([');
// print documents
while(cursor.hasNext()) {
print(tojson(cursor.next()));
if (cursor.hasNext()) // add trailing "," if not last item
print(',');
}
// end script
print(']);');
}
Its output will be like:
db.foo.drop();
db.foo.insertMany([
{
"_id" : ObjectId("abc"),
"name" : "foo"
}
,
{
"_id" : ObjectId("xyz"),
"name" : "bar"
}
]);
You can use DateFormat
from intl package.
import 'package:intl/intl.dart';
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);
Summing up what the others have suggested, and adding a third way
You can:
df.assign(Name='abc')
access the new column series (it will be created) and set it:
df['Name'] = 'abc'
insert(loc, column, value, allow_duplicates=False)
df.insert(0, 'Name', 'abc')
where the argument loc ( 0 <= loc <= len(columns) ) allows you to insert the column where you want.
'loc' gives you the index that your column will be at after the insertion. For example, the code above inserts the column Name as the 0-th column, i.e. it will be inserted before the first column, becoming the new first column. (Indexing starts from 0).
All these methods allow you to add a new column from a Series as well (just substitute the 'abc' default argument above with the series).
Or 4. Put them in the class that contains the logic that uses the constants the most
... sorry, couldn't resist ;-)
The accepted (and correct) answer says that "you can include this [Constants.h] file... in the pre-compiled header for the project."
As a novice, I had difficulty doing this without further explanation -- here's how: In your YourAppNameHere-Prefix.pch file (this is the default name for the precompiled header in Xcode), import your Constants.h inside the #ifdef __OBJC__
block.
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "Constants.h"
#endif
Also note that the Constants.h and Constants.m files should contain absolutely nothing else in them except what is described in the accepted answer. (No interface or implementation).
The questioner actually asked about int16 (etc) rather than (ugly) int16_t (etc).
There are no standard headers - nor any in Linux's /usr/include/ folder that define them without the "_t".
fun rotateArrow(view: View): Boolean {
return if (view.rotation == 0F) {
view.animate().setDuration(200).rotation(180F)
true
} else {
view.animate().setDuration(200).rotation(0F)
false
}
}
I found a new way to do it without interfaces. You only need to add the below code to the Fragment’s onCreate() method:
//overriding the fragment's oncreate
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//calling onBackPressedDispatcher and adding call back
requireActivity().onBackPressedDispatcher.addCallback(this) {
//do stuff here
}
}
you can get List value without using Type object.
EvalClassName[] evalClassName;
ArrayList<EvalClassName> list;
evalClassName= new Gson().fromJson(JSONArrayValue.toString(),EvalClassName[].class);
list = new ArrayList<>(Arrays.asList(evalClassName));
I have tested it and it is working.
I found the solution by @ShripadK most helpful, but it does not work, if there is more than one iframe. My fix is:
function autoResizeIFrame() {
$('iframe').height(
function() {
return $(this).contents().find('body').height() + 20;
}
)
}
$('iframe').contents().find('body').css(
{"min-height": "100", "overflow" : "hidden"});
setTimeout(autoResizeIFrame, 2000);
setTimeout(autoResizeIFrame, 10000);
$('iframe').height($('iframe').contents().find('body').height() + 20)
would set
the height of every frame to the same value, namely the height of the content of the first frame.
So I am using jquery's height()
with a function instead of a value. That way the individual
heights are calculated+ 20
is a hack to work around iframe scrollbar problems. The number must be bigger than the size of a scrollbar. The hack can probably
be avoided but disabling the scrollbars for the iframe.setTimeout
instead of setInterval(..., 1)
to reduce CPU load in my caseI also like using qdapTools::lookup
or shorthand binary operator %l%
. It works identically to an Excel vlookup, but it accepts name arguments opposed to column numbers
## Replicate Ben's data:
hous <- structure(list(HouseType = c("Semi", "Single", "Row", "Single",
"Apartment", "Apartment", "Row"), HouseTypeNo = c(1L, 2L, 3L,
2L, 4L, 4L, 3L)), .Names = c("HouseType", "HouseTypeNo"),
class = "data.frame", row.names = c(NA, -7L))
largetable <- data.frame(HouseType = as.character(sample(unique(hous$HouseType),
1000, replace = TRUE)), stringsAsFactors = FALSE)
## It's this simple:
library(qdapTools)
largetable[, 1] %l% hous
Try this:
java.util.Arrays.toString(anArray).replaceAll(", ", ",")
.replaceFirst("^\\[","").replaceFirst("\\]$","");
Use ipcs -a
: it gives detailed information of all resources [semaphore, shared-memory etc]
Here is the image of the output:
#!/bin/bash
echo Please, enter your name
read NAME
echo "Hi $NAME!"
if [ "x$NAME" = "xyes" ] ; then
# do something
fi
I s a short script to read in bash and echo back results.
A solution for the related case where you have an include file A that you can edit and want to override some of its functions in an include file B (or the main file):
Main File:
<?php
$Override=true; // An argument used in A.php
include ("A.php");
include ("B.php");
F1();
?>
Include File A:
<?php
if (!@$Override) {
function F1 () {echo "This is F1() in A";}
}
?>
Include File B:
<?php
function F1 () {echo "This is F1() in B";}
?>
Browsing to the main file displays "This is F1() in B".
For Swift 4.2 and above
if let phoneCallURL = URL(string: "tel://\(01234567)"), UIApplication.shared.canOpenURL(phoneCallURL)
{
UIApplication.shared.open(phoneCallURL, options: [:], completionHandler: nil)
}
If you just want the two branches 'email' and 'staging' to be the same, you can tag the 'email' branch, then reset the 'email' branch to the 'staging' one:
$ git checkout email
$ git tag old-email-branch
$ git reset --hard staging
You can also rebase the 'staging' branch on the 'email' branch. But the result will contains the modification of the two branches.
Expanding on this method, applied to finding the mode of the data where you may need the index of the actual array to see how far away the value is from the center of the distribution.
(_, idx, counts) = np.unique(a, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
mode = a[index]
Remember to discard the mode when len(np.argmax(counts)) > 1, also to validate if it is actually representative of the central distribution of your data you may check whether it falls inside your standard deviation interval.
If you want to return some value then wrap your statement in function
function my_function(){
return my_thing;
}
Problem is with the statement on the 1st line if you are trying to use PHP
var ask = confirm ('".$message."');
IF you are trying to use PHP you should use
var ask = confirm (<?php echo "'".$message."'" ?>); //now message with be the javascript string!!
Javascript has push and pop methods, which operate on ordinary Javascript array objects.
For queues, look here:
http://safalra.com/web-design/javascript/queues/
Queues can be implemented in JavaScript using either the push and shift methods or unshift and pop methods of the array object. Although this is a simple way to implement queues, it is very inefficient for large queues — because of the methods operate on arrays, the shift and unshift methods move every element in the array each time they are called.
Queue.js is a simple and efficient queue implementation for JavaScript whose dequeue function runs in amortized constant time. As a result, for larger queues, it can be significantly faster than using arrays.
One liner to get local time information: struct tm *tinfo = localtime(&(time_t){time(NULL)});
Another solution could be:
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference).AsEnumerable()
.Where(x => x.DateTimeStart.Date == currentDate.Date).AsQueryable();
Have you tried setting the selection properties of your tableView like this:
tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES;
If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
in your UITableView delegate. The documentation states:
Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
You can have this method return nil in cases where you don't want the selection to happen.
$str = preg_replace('/[\s]+/', ' ', $str);
There's no guaranteed way to force the user to clear the DNS cache, and it is often done by their ISP on top of their OS. It shouldn't take more than 24 hours for the updated DNS to propagate. Your best option is to make the transition seamless to the user by using something like mod_proxy with Apache to create a reverse proxy to your new server. That would cause all queries to the old server to still return the proper results and after a few days you would be free to remove the reverse proxy.
In my rails (rails 4.2)
project, I use
Model.last(10) # get the last 10 record order by id
and it works.
@niutech I was having the similar issue which is caused by Rocket Loader Module by Cloudflare. Just disable it for the website and it will sort out all your related issues.
Difference between split and partition is split returns the list without delimiter and will split where ever it gets delimiter in string i.e.
x = 'http://test.com/lalala-134-431'
a,b,c = x.split(-)
print(a)
"http://test.com/lalala"
print(b)
"134"
print(c)
"431"
and partition will divide the string with only first delimiter and will only return 3 values in list
x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala"
print(b)
"-"
print(c)
"134-431"
so as you want last value you can use rpartition it works in same way but it will find delimiter from end of string
x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala-134"
print(b)
"-"
print(c)
"431"
The following statement is not entirely accurate:
"So if you are calling other functionality, including static classes, from your page, you should be fine"
I am calling a static method that references the session through HttpContext.Current.Session and it is null. However, I am calling the method via a webservice method through ajax using jQuery.
As I found out here you can fix the problem with a simple attribute on the method, or use the web service session object:
There’s a trick though, in order to access the session state within a web method, you must enable the session state management like so:
[WebMethod(EnableSession = true)]
By specifying the EnableSession value, you will now have a managed session to play with. If you don’t specify this value, you will get a null Session object, and more than likely run into null reference exceptions whilst trying to access the session object.
Thanks to Matthew Cosier for the solution.
Just thought I'd add my two cents.
Ed
It depends where exactly you want to get the information from. You have a bunch of options:
<manifest>
element will have a package
attribute.adb
, you can launch adb shell
and execute pm list packages -f
, which shows the package name for each installed apk.PackageManager
Once you've got the package name, you simply link to market://search?q=pname:<package_name>
or http://market.android.com/search?q=pname:<package_name>
. Both will open the market on an Android device; the latter obviously has the potential to work on other hardware as well (it doesn't at the minute).
In my case to get my debug build - I have to turn off Instant Run option :
File ? Settings ? Build, Execution, Deployment ? Instant Run and uncheck Enable Instant Run.
Then after run project - I found my build into Application\app\build\outputs\appDebug\apk directory
1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.
1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.
C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.
You can specify a format string if you don't want to use the e-notation.
You may run:
git log <SHA1>..HEAD --ancestry-path --merges
From comment of last commit in the output you may find original branch name
Example:
c---e---g--- feature
/ \
-a---b---d---f---h---j--- master
git log e..master --ancestry-path --merges
commit h
Merge: g f
Author: Eugen Konkov <>
Date: Sat Oct 1 00:54:18 2016 +0300
Merge branch 'feature' into master
The issue is that, even though you removed the files, they are still present in previous revisions. That's the whole point of git, is that even if you delete something, you can still get it back by accessing the history.
What you are looking to do is called rewriting history, and it involved the git filter-branch
command.
GitHub has a good explanation of the issue on their site. https://help.github.com/articles/remove-sensitive-data
To answer your question more directly, what you basically need to run is this command with unwanted_filename_or_folder
replaced accordingly:
git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch unwanted_filename_or_folder' --prune-empty
This will remove all references to the files from the active history of the repo.
Next step, to perform a GC cycle to force all references to the file to be expired and purged from the packfile. Nothing needs to be replaced in these commands.
git for-each-ref --format='delete %(refname)' refs/original | git update-ref --stdin
# or, for older git versions (e.g. 1.8.3.1) which don't support --stdin
# git update-ref $(git for-each-ref --format='delete %(refname)' refs/original)
git reflog expire --expire=now --all
git gc --aggressive --prune=now
In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value)
no add(value)
.
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)
Just run the following simple command on Raspberry Pi 3 running Raspbian Jessie.
run terminal and type
sudo raspi-config
Go to: >Advanced Option > Resolution > just set your resolution compatible fit with your screen.
then
reboot
If you didn't found the menu on configuration, please update your raspberry pi software configuration tool (raspi-config).
That's all TQ.
Most examples on the web (and some presented above) show how to load an XML from a file in a browser compatible manner. This proves easy, except in the case of Google Chrome which does not support the document.implementation.createDocument()
method. When using Chrome, in order to load an XML file into a XmlDocument object, you need to use the inbuilt XmlHttp object and then load the file by passing it's URI.
In your case, the scenario is different, because you want to load the XML from a string variable, not a URL. For this requirement however, Chrome supposedly works just like Mozilla (or so I've heard) and supports the parseFromString() method.
Here is a function I use (it's part of the Browser compatibility library I'm currently building):
function LoadXMLString(xmlString)
{
// ObjectExists checks if the passed parameter is not null.
// isString (as the name suggests) checks if the type is a valid string.
if (ObjectExists(xmlString) && isString(xmlString))
{
var xDoc;
// The GetBrowserType function returns a 2-letter code representing
// ...the type of browser.
var bType = GetBrowserType();
switch(bType)
{
case "ie":
// This actually calls into a function that returns a DOMDocument
// on the basis of the MSXML version installed.
// Simplified here for illustration.
xDoc = new ActiveXObject("MSXML2.DOMDocument")
xDoc.async = false;
xDoc.loadXML(xmlString);
break;
default:
var dp = new DOMParser();
xDoc = dp.parseFromString(xmlString, "text/xml");
break;
}
return xDoc;
}
else
return null;
}
This is because Oracle internally changes empty string to NULL values. Oracle simply won't let insert an empty string.
On the other hand, SQL Server would let you do what you are trying to achieve.
There are 2 workarounds here:
Both are, of course, stupid workarounds :)
I recently had this same problem. Unfortunately, NotifyIcon is only a Windows.Forms control at the moment, if you want to use it you are going to have to include that part of the framework. I guess that depends how much of a WPF purist you are.
If you want a quick and easy way of getting started check out this WPF NotifyIcon control on the Code Project which does not rely on the WinForms NotifyIcon at all. A more recent version seems to be available on the author's website and as a NuGet package. This seems like the best and cleanest way to me so far.
- Rich ToolTips rather than text
- WPF context menus and popups
- Command support and routed events
- Flexible data binding
- Rich balloon messages rather than the default messages provides by the OS
Check it out. It comes with an amazing sample app too, very easy to use, and you can have great looking Windows Live Messenger style WPF popups, tooltips, and context menus. Perfect for displaying an RSS feed, I am using it for a similar purpose.
Many answers provided for this question. Just wanted to add one more which uses bashism-
#! /bin/bash
while read -r || [[ -n "$REPLY" ]]; do
[[ "$REPLY" =~ ^(-rwx|drwx).*[[:digit:]]+$ ]] && echo "Got one -> $REPLY"
done <"$1"
@kurumi answer for bash, which uses case is also correct but it will not read last line of file if there is no newline sequence at the end(Just save the file without pressing 'Enter/Return' at the last line).
If you want to revert changes made to your working copy, do this:
git checkout .
If you want to revert changes made to the index (i.e., that you have added), do this. Warning this will reset all of your unpushed commits to master!:
git reset
If you want to revert a change that you have committed, do this:
git revert <commit 1> <commit 2>
If you want to remove untracked files (e.g., new files, generated files):
git clean -f
Or untracked directories (e.g., new or automatically generated directories):
git clean -fd
You'll have to resort to XHTML or HTML 4.01 for this. Although iframe
is still there in HTML5, its use is not recommended for embedding content meant for the user.
And be sure to tell your teacher that frames haven't been state-of-the-art since the late nineties. They have no place in any kind of education at all, except possibly for historical reasons.
Because you are passing a string as the second argument to the date function, which should be an integer.
string date ( string $format [, int $timestamp = time() ] )
Try strtotime which will Parse about any English textual datetime description into a Unix timestamp (integer):
date("d", strtotime($_GET['start_date']));
I'm used it and worked perfectly...
startActivity(new Intent(getApplicationContext(),MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
because Finish() use for 2 activities, not for multiple activities
class Countries < ActiveRecord::Base
self.table_name = "cc"
end
class Countries < ActiveRecord::Base
self.set_table_name "cc"
...
end
For those who are using web servers make sure that the bcprov-jdk16-145.jar has been installed in you servers lib, for weblogic had to put the jar in:
<weblogic_jdk_home>\jre\lib\ext
You can just add an empty footer at the end then it will hide the empty cells but it will also look quite ugly:
tableView.tableFooterView = UIView()
There is a better approach: add a 1 point line at the end of the table view as the footer and the empty cells will also not been shown anymore.
let footerView = UIView()
footerView.frame = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 1)
footerView.backgroundColor = tableView.separatorColor
tableView.tableFooterView = footerView
This answer applies to this question if
path below can be relative
PYTHONPATH=/path/to/dir python script.py
If you're OK with not using <p>
s (only <div>
s and <span>
s), this solution might even allow you to align your inline-block
s center or right, if you want to (or just keep them left, the way you originally asked for). While the solution might still work with <p>
s, I don't think the resulting HTML code would be quite correct, but it's up to you anyways.
The trick is to wrap each one of your <span>
s with a corresponding <div>
. This way we're taking advantage of the line break caused by the <div>
's display: block
(default), while still keeping the visual green box tight to the limits of the text (with your display: inline-block
declaration).
.text span {_x000D_
background:rgba(165, 220, 79, 0.8);_x000D_
display:inline-block;_x000D_
padding:7px 10px;_x000D_
color:white;_x000D_
}_x000D_
.large { font-size:80px }
_x000D_
<div class="text">_x000D_
<div><span class="medium">We</span></div>_x000D_
<div><span class="large">build</span></div>_x000D_
<div><span class="medium">the</span></div>_x000D_
<div><span class="large">Internet</span></div>_x000D_
</div>
_x000D_
Use logging module (http://docs.python.org/library/logging.html):
import logging
logger = logging.getLogger('scope.name')
file_log_handler = logging.FileHandler('logfile.log')
logger.addHandler(file_log_handler)
stderr_log_handler = logging.StreamHandler()
logger.addHandler(stderr_log_handler)
# nice output format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_log_handler.setFormatter(formatter)
stderr_log_handler.setFormatter(formatter)
logger.info('Info message')
logger.error('Error message')
Example: Read json from file
/* test.json */
{
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}
void readJson()
{
QString val;
QFile file;
file.setFileName("test.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
qWarning() << val;
QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
QJsonObject sett2 = d.object();
QJsonValue value = sett2.value(QString("appName"));
qWarning() << value;
QJsonObject item = value.toObject();
qWarning() << tr("QJsonObject of description: ") << item;
/* in case of string value get value and convert into string*/
qWarning() << tr("QJsonObject[appName] of description: ") << item["description"];
QJsonValue subobj = item["description"];
qWarning() << subobj.toString();
/* in case of array get array and convert into string*/
qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"];
QJsonArray test = item["imp"].toArray();
qWarning() << test[1].toString();
}
OUTPUT
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) )
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
Example: Read json from string
Assign json to string as below and use the readJson()
function shown before:
val =
' {
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}';
OUTPUT
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) )
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
This
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"¶m2="+lon);
must work. For whatever strange reason1, you need ?
before the first parameter and &
before the following ones.
Using a compound parameter like
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"_"+lon);
would work, too, but is surely not nice. You can't use a space there as it's prohibited in an URL, but you could encode it as %20
or +
(but this is even worse style).
1 Stating that ?
separates the path and the parameters and that &
separates parameters from each other does not explain anything about the reason. Some RFC says "use ? there and & there", but I can't see why they didn't choose the same character.
You can make api calls by choosing the HTTP method and setting optional parameters:
$facebook->api('/me/feed/', 'post', array(
'message' => 'I want to display this message on my wall'
));
Submit Post to Facebook Wall :
Include the fbConfig.php file to connect Facebook API and get the access token.
Post message, name, link, description, and the picture will be submitted to Facebook wall. Post submission status will be shown.
If FB access token ($accessToken) is not available, the Facebook Login URL will be generated and the user would be redirected to the FB login page.
<?php
//Include FB config file
require_once 'fbConfig.php';
if(isset($accessToken)){
if(isset($_SESSION['facebook_access_token'])){
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}else{
// Put short-lived access token in session
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler helps to manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// Set default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
//FB post content
$message = 'Test message from CodexWorld.com website';
$title = 'Post From Website';
$link = 'http://www.codexworld.com/';
$description = 'CodexWorld is a programming blog.';
$picture = 'http://www.codexworld.com/wp-content/uploads/2015/12/www-codexworld-com-programming-blog.png';
$attachment = array(
'message' => $message,
'name' => $title,
'link' => $link,
'description' => $description,
'picture'=>$picture,
);
try{
//Post to Facebook
$fb->post('/me/feed', $attachment, $accessToken);
//Display post submission status
echo 'The post was submitted successfully to Facebook timeline.';
}catch(FacebookResponseException $e){
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}catch(FacebookSDKException $e){
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}else{
//Get FB login URL
$fbLoginURL = $helper->getLoginUrl($redirectURL, $fbPermissions);
//Redirect to FB login
header("Location:".$fbLoginURL);
}
Refrences:
https://github.com/facebookarchive/facebook-php-sdk
https://developers.facebook.com/docs/pages/publishing/
https://developers.facebook.com/docs/php/gettingstarted
http://www.pontikis.net/blog/auto_post_on_facebook_with_php
https://www.codexworld.com/post-to-facebook-wall-from-website-php-sdk/
Both are effectively the same class (you can look at the disassembly). HashTable was created first before .Net had generics. Dictionary, however is a generic class and gives you strong typing benefits. I would never use HashTable since Dictionary costs you nothing to use.
You have to create a symlink to your mysql installation if it is not the most recent version of mysql.
$ brew link --force [email protected]
$('#signup').on("submit", function(event) {
$form = $(this); //wrap this in jQuery
alert('the action is: ' + $form.attr('action'));
});
Try adding ?wsdl
to the string.
public enum MyEnum
{
ONE(1),
TWO(2);
private int value;
private MyEnum(int val){
value = val;
}
public int getValue(){
return value;
}
}
You can also use some existing API's like GroupDocs.Viewer which can convert your document into image or html and then you will be able to display it in your own application.
I had to use the install
function instead:
conda install pandas=0.13.1
Use SimpleDateFormat
to convert between a date string and a real Date
object. with a Date
as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat
(click the blue code link for the Javadoc).
Here's a kickoff example:
String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00
Using current browsers you can use it like this:
img {
-webkit-filter: grayscale(100%); /* Chrome, Safari, Opera */
filter: grayscale(100%);
}
and to remedy it:
img:hover{
-webkit-filter: grayscale(0%); /* Chrome, Safari, Opera */
filter: grayscale(0%);
}
worked with me and is much shorter. There is even more one can do within the CSS:
filter: none | blur() | brightness() | contrast() | drop-shadow() | grayscale() |
hue-rotate() | invert() | opacity() | saturate() | sepia() | url();
For more information and supporting browsers see this: http://www.w3schools.com/cssref/css3_pr_filter.asp
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
Time: <input type="time" id="myTime" value="16:32:55">_x000D_
_x000D_
<p>Click the button to get the time of the time field.</p>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<p id="demo"></p>_x000D_
_x000D_
<script>_x000D_
function myFunction() {_x000D_
var x = document.getElementById("myTime").value;_x000D_
document.getElementById("demo").innerHTML = x;_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
I found that by setting value field (not just what is given below) time input will be internally converted into the 24hr format.
Apache/HTTPD tends to be around in most enterprises or if you're using Centos/etc at home. So, if you have that around, you can do a proxy very easily to add the necessary CORS headers.
I have a blog post on this here as I suffered with it quite a few times recently. But the important bit is just adding this to your /etc/httpd/conf/httpd.conf file and ensuring you are already doing "Listen 80":
<VirtualHost *:80>
<LocationMatch "/SomePath">
ProxyPass http://target-ip:8080/SomePath
Header add "Access-Control-Allow-Origin" "*"
</LocationMatch>
</VirtualHost>
This ensures that all requests to URLs under your-server-ip:80/SomePath route to http://target-ip:8080/SomePath (the API without CORS support) and that they return with the correct Access-Control-Allow-Origin header to allow them to work with your web-app.
Of course you can change the ports and target the whole server rather than SomePath if you like.
As far as I can tell, you don't necessarily need to specify the axis when using the filter function.
new = old.filter(['A','B','D'])
returns the same dataframe as
new = old.filter(['A','B','D'], axis=1)
If you use form.close() in your form and set the FormClosing Event of your form and either use form.close() in this Event ,you fall in unlimited loop and Argument out of range happened and the solution is that change the form.close() with form.dispose() in Event of FormClosing. I hope this little tip help you!!!
When compiling memcached under Centos 5.x i got the same problem.
The solution is to upgrade gcc and g++ to version 4.4 at least.
Make sure your CC/CXX is set (exported) to right binaries before compiling.
The nice thing about iterator is that later on if you wanted to switch your vector to a another STD container. Then the forloop will still work.
The problem lies on your proxy. Because the location provider of your install package creates its own certificate and does not buy a verified one from an accepted authority, your proxy does not allow access to the targeted host. I assume that you bypass the proxy when using the Chrome Browser. So there is no checking.
There are some solutions to this problem. But all imply that you trust the package provider.
Possible solutions:
http://
access which
may bypass your proxy. That's a bit dangerous, because the man in the middle can inject malware into you downloads.wget
suggests you to use a flag --no-check-certificate
. This will add a proxy directive to your request. The proxy, if it understands the directive, does not check if the servers certificate is verified by an authority and passes the request. Perhaps there is a config with npm that does the same as the wget flag.Check out this directive: https://github.com/samu/angular-table
It automates sorting and pagination a lot and gives you enough freedom to customize your table/list however you want.
Both of them uses TCP as a transport protocol, but HTTP uses a persistent connection, which makes the performance of the TCP better.
As required in Question::
var string1= "foo/bar/test.html";
if(string1.contains("/"))
{
var string_parts = string1.split("/");
var result = string_parts[string_parts.length - 1];
console.log(result);
}
and for question asked on url (asked for one occurence of '=' )::
[http://stackoverflow.com/questions/24156535/how-to-split-a-string-after-a-particular-character-in-jquery][1]
var string1= "Hello how are =you";
if(string1.contains("="))
{
var string_parts = string1.split("=");
var result = string_parts[string_parts.length - 1];
console.log(result);
}
Looking at the source code for dumpsys and service, you can get the list of services available by executing the following:
adb shell service -l
You can then supply the service name you are interested in to dumpsys to get the specific information. For example (note that not all services provide dump info):
adb shell dumpsys activity
adb shell dumpsys cpuinfo
adb shell dumpsys battery
As you can see in the code (and in K_Anas's answer), if you call dumpsys without any service name, it will dump the info on all services in one big dump:
adb shell dumpsys
Some services can receive additional arguments on what to show which normally is explained if you supplied a -h
argument, for example:
adb shell dumpsys activity -h
adb shell dumpsys window -h
adb shell dumpsys meminfo -h
adb shell dumpsys package -h
adb shell dumpsys batteryinfo -h
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
In some languages like JAVA you define an array using curly braces as following but in python it has a different meaning:
Java:
int[] myIntArray = {1,2,3};
String[] myStringArray = {"a","b","c"};
However, in Python, curly braces are used to define dictionaries, which needs a key:value
assignment as {'a':1, 'b':2}
To actually define an array (which is actually called list in python) you can do:
Python:
mylist = [1,2,3]
or other examples like:
mylist = list()
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist)
>>> [1,2,3]
to pass the event
object:
<p id="p" onclick="doSomething(event)">
to get the clicked child element
(should be used with event
parameter:
function doSomething(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
to pass the element
itself (DOMElement):
<p id="p" onclick="doThing(this)">
see live example on jsFiddle.
You can specify the name of the event
as above, but alternatively your handler can access the event
parameter as described here: "When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters". There's much more additional documentation at the link.
This is my example.
https://github.com/luisnicg/jQuery-Sortable-and-PHP
You need to catch the order in the update event
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight",
update: function( event, ui ) {
var sorted = $( "#sortable" ).sortable( "serialize", { key: "sort" } );
$.post( "form/order.php",{ 'choices[]': sorted});
}
});
I found that my dfs both had the same type column (str
) but switching from join
to merge
solved the issue.
You can use ARG variable defaultValue
and during the run command you can even update this value using --build-arg variable=value
. To use these variables in the docker file you can refer them as $variable
in run command.
Note: These variables would be available for Linux commands like RUN echo $variable
and they wouldn't persist in the image.
python <main module>.py
does not work with relative importThe problem is relative import does not work when you run a __main__
module from the command line
python <main_module>.py
It is clearly stated in PEP 338.
The release of 2.5b1 showed a surprising (although obvious in retrospect) interaction between this PEP and PEP 328 - explicit relative imports don't work from a main module. This is due to the fact that relative imports rely on
__name__
to determine the current module's position in the package hierarchy. In a main module, the value of__name__
is always'__main__'
, so explicit relative imports will always fail (as they only work for a module inside a package).
The issue isn't actually unique to the -m switch. The problem is that relative imports are based on
__name__
, and in the main module,__name__
always has the value__main__
. Hence, relative imports currently can't work properly from the main module of an application, because the main module doesn't know where it really fits in the Python module namespace (this is at least fixable in theory for the main modules executed through the -m switch, but directly executed files and the interactive interpreter are completely out of luck).
To understand further, see Relative imports in Python 3 for the detailed explanation and how to get it over.
EXP (export) and IMP (import) are the two tools you need. It's is better to try to run these on the command line and on the same machine.
It can be run from remote, you just need to setup you TNSNAMES.ORA
correctly and install all the developer tools with the same version as the database. Without knowing the error message you are experiencing then I can't help you to get exp/imp to work.
The command to export a single user:
exp userid=dba/dbapassword OWNER=username DIRECT=Y FILE=filename.dmp
This will create the export dump file.
To import the dump file into a different user schema, first create the newuser in SQLPLUS:
SQL> create user newuser identified by 'password' quota unlimited users;
Then import the data:
imp userid=dba/dbapassword FILE=filename.dmp FROMUSER=username TOUSER=newusername
If there is a lot of data then investigate increasing the BUFFERS
or look into expdp/impdp
Most common errors for exp and imp are setup. Check your PATH
includes $ORACLE_HOME/bin
, check $ORACLE_HOME
is set correctly and check $ORACLE_SID
is set
Try to create a function which uses recursion. Your DateTime object is an input and function returns a new DateTime object which stands for the beginning of the week.
DateTime WeekBeginning(DateTime input)
{
do
{
if (input.DayOfWeek.ToString() == "Monday")
return input;
else
return WeekBeginning(input.AddDays(-1));
} while (input.DayOfWeek.ToString() == "Monday");
}
C++ does not have the for_each
loop feature in its syntax. You have to use c++11 or use the template function std::for_each
.
struct Function {
int input;
Function(int input): input(input) {}
void operator()(Attack& attack) {
if(attack->m_num == input) attack->makeDamage();
}
};
Function f(input);
std::for_each(m_attack.begin(), m_attack.end(), f);
You're over-complicating it - it just needs to be:
void generateArray(int *a, int si)
{
for (int j = 0; j < si; j++)
a[j] = rand() % 9;
}
int main()
{
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}
When you pass an array as a parameter to a function it decays to a pointer to the first element of the array. So there is normally never a need to pass a pointer to an array.
I tried all the suggestions and nothing works for me.
Imagine the situation: you need a 2-way binding and you have a lookup with NUMBER values and you want to fill your SELECT with the values from this lookup and highlight the chosen option.
Using [value] or (ngModelChange) is a no-go, because you won't be able to select the chosen option after user initiated the change: [value] considers everything a string, as to (ngModelChange) - it obviously should not be used when user initiates the change, so it ruins the proper selection. Using [ngModel] guarantees the fixed format of received VALUE as INDEX: VALUE and it's easy to parse it correspondingly, HOWEVER once again - it ruins the selected option.
So we go with [ngValue] (which will take care of proper types), (change) and... [value], which guarantees the handler receives VALUE, not a DISPLAYED VALUE or INDEX: VALUE :) Below is my working clumsy solution:
<select
class="browser-default custom-select"
(change)="onEdit($event.target.value)"
>
<option [value]="">{{
'::Licences:SelectLicence' | abpLocalization
}}</option>
<ng-container *ngIf="licencesLookupData$ | async">
<option
*ngFor="let l of licencesLookupData$ | async"
[ngValue]="l.id"
[value]="l.id"
[selected]="l.id == selected.id"
>
{{ l.id }} {{ l.displayName | defaultValue }}
</option>
</ng-container>
</select>
onEdit(idString: string) {
const id = Number(idString);
if (isNaN(id)) {
this.onAdd();
return;
}
this.licencesLoading = true;
this.licencesService
.getById(id)
.pipe(finalize(() => (this.licencesLoading = false)), takeUntil(this.destroy))
.subscribe((state: Licences.LicenceWithFlatProperties) => {
this.selected = state;
this.buildForm();
this.get();
});
}
If you have filename.py
in the same folder, you can easily import it like this:
import filename
I am using python3.7
Because async functions are promises, you can create a static function on your class which executes an async function which returns the instance of the class:
class Yql {
constructor () {
// Set up your class
}
static init () {
return (async function () {
let yql = new Yql()
// Do async stuff
await yql.build()
// Return instance
return yql
}())
}
async build () {
// Do stuff with await if needed
}
}
async function yql () {
// Do this instead of "new Yql()"
let yql = await Yql.init()
// Do stuff with yql instance
}
yql()
Call with let yql = await Yql.init()
from an async function.
as @PhilHarvey said, you can use mysqld --verbose --help | grep datadir
In Java, a String is a reference to heap-allocated storage. Returning "ans" only returns the reference so there is no need for stack-allocated storage. In fact, there is no way in Java to allocate objects in stack storage.
I would change to this, though. You don't need "ans" at all.
return String.format("%d:%d", mins, secs);
After reading the above answers, here adding my interpretations.
Suppose browsing online, web browser is your frame
which decides where and how big to show webpage. Scroller of browser is your bounds.origin
that decides which part of webpage will be shown. bounds.origin
is hard to understand. The best way to learn is creating Single View Application, trying modify these parameters and see how subviews change.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100.0f, 200.0f, 200.0f, 400.0f)];
[view1 setBackgroundColor:[UIColor redColor]];
UIView *view2 = [[UIView alloc] initWithFrame:CGRectInset(view1.bounds, 20.0f, 20.0f)];
[view2 setBackgroundColor:[UIColor yellowColor]];
[view1 addSubview:view2];
[[self view] addSubview:view1];
NSLog(@"Old view1 frame %@, bounds %@, center %@", NSStringFromCGRect(view1.frame), NSStringFromCGRect(view1.bounds), NSStringFromCGPoint(view1.center));
NSLog(@"Old view2 frame %@, bounds %@, center %@", NSStringFromCGRect(view2.frame), NSStringFromCGRect(view2.bounds), NSStringFromCGPoint(view2.center));
// Modify this part.
CGRect bounds = view1.bounds;
bounds.origin.x += 10.0f;
bounds.origin.y += 10.0f;
// incase you need width, height
//bounds.size.height += 20.0f;
//bounds.size.width += 20.0f;
view1.bounds = bounds;
NSLog(@"New view1 frame %@, bounds %@, center %@", NSStringFromCGRect(view1.frame), NSStringFromCGRect(view1.bounds), NSStringFromCGPoint(view1.center));
NSLog(@"New view2 frame %@, bounds %@, center %@", NSStringFromCGRect(view2.frame), NSStringFromCGRect(view2.bounds), NSStringFromCGPoint(view2.center));
You should use some background image to your radio buttons and flip it with another image on change
.radio {
background: url(customButton.png) no-repeat;
}
Change the loading order of your scripts so that function1
was defined before using it in ready
callback.
Plus I always found it better to define ready
callback as an anonymous method then named one.
If you know the kernel file is installed on your machine, then problem is getting emulator.exe to find it.
My fix was based on the post by user2789389. I could launch the AVD from the AVD Manager, but not from the command line. So, using AVD Manager, I selected the avd I wanted to run and clicked "Details". That showed me the path to the avd definition file. Within a folder of the same name, next to this .avd file, I found a config.ini file. In the ini, I found the following line:
image.sysdir.1=system-images\android-19\default\armeabi-v7a\
I looked in the folder C:\Users\XXXX\android-sdks\system-images\android-19, and found that the image.sysdir.1 path was invalid. I had to remove the "default" sub folder, thus changing it to the following:
image.sysdir.1=system-images\android-19\armeabi-v7a\
I saved the ini and tried again to launch the AVD. That fixed the problem!
Here is a portable module ( ANSI-C ) which can benchmark each of your algorithms on any architecture.
Your CPU has 9 bit bytes? No problem :-) At the moment it implements 2 algorithms, the K&R algorithm and a byte wise lookup table. The lookup table is on average 3 times faster than the K&R algorithm. If someone can figure a way to make the "Hacker's Delight" algorithm portable feel free to add it in.
#ifndef _BITCOUNT_H_
#define _BITCOUNT_H_
/* Return the Hamming Wieght of val, i.e. the number of 'on' bits. */
int bitcount( unsigned int );
/* List of available bitcount algorithms.
* onTheFly: Calculate the bitcount on demand.
*
* lookupTalbe: Uses a small lookup table to determine the bitcount. This
* method is on average 3 times as fast as onTheFly, but incurs a small
* upfront cost to initialize the lookup table on the first call.
*
* strategyCount is just a placeholder.
*/
enum strategy { onTheFly, lookupTable, strategyCount };
/* String represenations of the algorithm names */
extern const char *strategyNames[];
/* Choose which bitcount algorithm to use. */
void setStrategy( enum strategy );
#endif
.
#include <limits.h>
#include "bitcount.h"
/* The number of entries needed in the table is equal to the number of unique
* values a char can represent which is always UCHAR_MAX + 1*/
static unsigned char _bitCountTable[UCHAR_MAX + 1];
static unsigned int _lookupTableInitialized = 0;
static int _defaultBitCount( unsigned int val ) {
int count;
/* Starting with:
* 1100 - 1 == 1011, 1100 & 1011 == 1000
* 1000 - 1 == 0111, 1000 & 0111 == 0000
*/
for ( count = 0; val; ++count )
val &= val - 1;
return count;
}
/* Looks up each byte of the integer in a lookup table.
*
* The first time the function is called it initializes the lookup table.
*/
static int _tableBitCount( unsigned int val ) {
int bCount = 0;
if ( !_lookupTableInitialized ) {
unsigned int i;
for ( i = 0; i != UCHAR_MAX + 1; ++i )
_bitCountTable[i] =
( unsigned char )_defaultBitCount( i );
_lookupTableInitialized = 1;
}
for ( ; val; val >>= CHAR_BIT )
bCount += _bitCountTable[val & UCHAR_MAX];
return bCount;
}
static int ( *_bitcount ) ( unsigned int ) = _defaultBitCount;
const char *strategyNames[] = { "onTheFly", "lookupTable" };
void setStrategy( enum strategy s ) {
switch ( s ) {
case onTheFly:
_bitcount = _defaultBitCount;
break;
case lookupTable:
_bitcount = _tableBitCount;
break;
case strategyCount:
break;
}
}
/* Just a forwarding function which will call whichever version of the
* algorithm has been selected by the client
*/
int bitcount( unsigned int val ) {
return _bitcount( val );
}
#ifdef _BITCOUNT_EXE_
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Use the same sequence of pseudo random numbers to benmark each Hamming
* Weight algorithm.
*/
void benchmark( int reps ) {
clock_t start, stop;
int i, j;
static const int iterations = 1000000;
for ( j = 0; j != strategyCount; ++j ) {
setStrategy( j );
srand( 257 );
start = clock( );
for ( i = 0; i != reps * iterations; ++i )
bitcount( rand( ) );
stop = clock( );
printf
( "\n\t%d psudoe-random integers using %s: %f seconds\n\n",
reps * iterations, strategyNames[j],
( double )( stop - start ) / CLOCKS_PER_SEC );
}
}
int main( void ) {
int option;
while ( 1 ) {
printf( "Menu Options\n"
"\t1.\tPrint the Hamming Weight of an Integer\n"
"\t2.\tBenchmark Hamming Weight implementations\n"
"\t3.\tExit ( or cntl-d )\n\n\t" );
if ( scanf( "%d", &option ) == EOF )
break;
switch ( option ) {
case 1:
printf( "Please enter the integer: " );
if ( scanf( "%d", &option ) != EOF )
printf
( "The Hamming Weight of %d ( 0x%X ) is %d\n\n",
option, option, bitcount( option ) );
break;
case 2:
printf
( "Please select number of reps ( in millions ): " );
if ( scanf( "%d", &option ) != EOF )
benchmark( option );
break;
case 3:
goto EXIT;
break;
default:
printf( "Invalid option\n" );
}
}
EXIT:
printf( "\n" );
return 0;
}
#endif
This is really fast and dirty, but it gets the job done: jsFiddle
#img1, #img2, #img3, #img4 {
width:100%;
height:100%;
position:fixed;
z-index:-1;
animation-name: test;
animation-duration: 5s;
opacity:0;
}
#img2 {
animation-delay:5s;
-webkit-animation-delay:5s
}
#img3 {
animation-delay:10s;
-webkit-animation-delay:10s
}
#img4 {
animation-delay:15s;
-webkit-animation-delay:15s
}
@-webkit-keyframes test {
0% {
opacity: 0;
}
50% {
opacity: 1;
}
100% {
}
}
@keyframes test {
0% {
opacity: 0;
}
50% {
opacity: 1;
}
100% {
}
}
I'm working on something similar for my site using jQuery, but the transition is triggered when the user scrolls down the page - jsFiddle
Based on the warning message, the component ReactTooltip renders an HTML that might look like this:
<p>
<div>...</div>
</p>
According to this document, a <p></p>
tag can only contain inline elements. That means putting a <div></div>
tag inside it should be improper, since the div
tag is a block element. Improper nesting might cause glitches like rendering extra tags, which can affect your javascript and css.
If you want to get rid of this warning, you might want to customize the ReactTooltip component, or wait for the creator to fix this warning.
You apply the background color as transparent(light gray)
when you click the button.
ButtonName.setOnClickListener()
In the above method you set the background color of the button.
If you use node.js 0.12 or above / typescript 1.4 or above, just add compiler options like:
tsc a.ts --target es6 --module commonjs
More info: https://github.com/Microsoft/TypeScript/wiki/Compiler-Options
If you use tsconfig.json
, then like this:
{
"compilerOptions": {
"module": "commonjs",
"target": "es6"
}
}
More info: https://github.com/Microsoft/TypeScript/wiki/tsconfig.json
There is a very simple way in which you can do this. It involves injecting a javascript code to a label control from code behind. here is sample code:
<head runat="server">
<title>Calling javascript function from code behind example</title>
<script type="text/javascript">
function showDialogue() {
alert("this dialogue has been invoked through codebehind.");
}
</script>
</head>
..........
lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";
Check out the full code here: http://softmate-technologies.com/javascript-from-CodeBehind.htm (dead)
Link from Internet Archive: https://web.archive.org/web/20120608053720/http://softmate-technologies.com/javascript-from-CodeBehind.htm
I found this:
Full
An easy to use, full page image background template for Bootstrap 3 websites
http://startbootstrap.com/template-overviews/full/
or
using in your main div container:
html
<div class="container-fluid full">
</div>
css:
.full {
background: url('http://placehold.it/1920x1080') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
height:100%;
}
Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.
For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".
Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html
Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
There can be another way which saves the day. Just init a new Dialog with desired layout and just show it. I need it for showing a loadingView over a DialogFragment and this was the only way I succeed.
Dialog topDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
topDialog.setContentView(R.layout.dialog_top);
topDialog.show();
bringToFront() might not work in some cases like mine. But content of dialog_top layout must override anything on the ui layer. But anyway, this is an ugly workaround.
Your empList
is object type but you are trying to push strings
Try this
this.empList.push({this.name,this.empoloyeeID});
The following worked for me
import java.time.*;
import java.time.format.*;
public class Times {
public static void main(String[] args) {
final String dateTime = "2012-02-22T02:06:58.147Z";
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter.withZone(ZoneId.of("UTC")));
System.out.println(parsed.toLocalDateTime());
}
}
and gave me output as
2012-02-22T02:06:58.147
This answer may be late reply but it will be useful for seeing this topic in future.
The features of .NET framework 4.5 can be seen in the following link.
To summarize:
Installation
.NET Framework 4.5 does not support Windows XP or Windows Server 2003, and therefore, if you have to create applications that target these operating systems, you will need to stay with .NET Framework 4.0. In contrast, Windows 8 and Windows Server 2012 in all of their editions include .NET Framework 4.5.
- Support for Arrays Larger than 2 GB on 64-bit Platforms
- Enhanced Background Server Garbage Collection
- Support for Timeouts in Regular Expression Evaluations
- Support for Unicode 6.0.0 in Culture-Sensitive Sorting and Casing Rules on Windows 8
- Simple Default Culture Definition for an Application Domain
- Internationalized Domain Names in Windows 8 Apps
.val()
always works with textarea
elements.
.text()
works sometimes and fails other times! It's not reliable (tested in Chrome 33)
What's best is that .val()
works seamlessly with other form elements too (like input
) whereas .text()
fails.
use the pair long t = now.Ticks
and DateTime Today = new DateTime(t)
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.
I'd use a recursive function with a list of apis
var APIs = [ '/api_1.php', '/api_2.php', '/api_3.php' ];
var host = 'www.example.com';
function callAPIs ( host, APIs ) {
var API = APIs.shift();
http.get({ host: host, path: API }, function(res) {
var body = '';
res.on('data', function (d) {
body += d;
});
res.on('end', function () {
if( APIs.length ) {
callAPIs ( host, APIs );
}
});
});
}
callAPIs( host, APIs );
edit: request version
var request = require('request');
var APIs = [ '/api_1.php', '/api_2.php', '/api_3.php' ];
var host = 'www.example.com';
var APIs = APIs.map(function (api) {
return 'http://' + host + api;
});
function callAPIs ( host, APIs ) {
var API = APIs.shift();
request(API, function(err, res, body) {
if( APIs.length ) {
callAPIs ( host, APIs );
}
});
}
callAPIs( host, APIs );
edit: request/async version
var request = require('request');
var async = require('async');
var APIs = [ '/api_1.php', '/api_2.php', '/api_3.php' ];
var host = 'www.example.com';
var APIs = APIs.map(function (api) {
return 'http://' + host + api;
});
async.eachSeries(function (API, cb) {
request(API, function (err, res, body) {
cb(err);
});
}, function (err) {
//called when all done, or error occurs
});
One approach is to combine the search strings into a regex pattern as in this answer.
The Standard Library provides an input function called ws
, which consumes whitespace from an input stream. You can use it like this:
std::string s;
std::getline(std::cin >> std::ws, s);
I tend to use JAX-RS using Jersey (you can write nice resource beans in Scala, Java or Groovy) to write RESTul web applications. Then I use Scalate for the rendering the views using one of the various template languages (JADE, Scaml, Ssp (Scala Server Pages), Mustache, etc.).
When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.
Ubuntu 14 and lower does not have "systemctl
" Source: https://docs.docker.com/install/linux/linux-postinstall/#configure-docker-to-start-on-boot
Configure Docker to start on boot:
Most current Linux distributions (RHEL, CentOS, Fedora, Ubuntu 16.04 and higher) use systemd to manage which services start when the system boots. Ubuntu 14.10 and below use upstart.
1) systemd (Ubuntu 16 and above):
$ sudo systemctl enable docker
To disable this behavior, use disable instead.
$ sudo systemctl disable docker
2) upstart (Ubuntu 14 and below):
Docker is automatically configured to start on boot using upstart. To disable this behavior, use the following command:
$ echo manual | sudo tee /etc/init/docker.override
chkconfig
$ sudo chkconfig docker on
Done.
I've been asking myself related questions over and over again, then got lost in formal languages... but just to help you out a little I'd like to share some findings:
I recommend to give a look at advanced CMS
Typo3
for PHP
(I know there is a lot of stuff but thats the one I think is most mature)
Plone
in Python
If you find out that the web in 2013 should work different then, start from scratch. That would mean to put together a team of highly skilled/experienced people to build a new CMS. May be you'd like to give a look at polymer for that purpose.
If it comes to coding and multilingual websites / native language support, I think every programmer should have a clue about unicode. If you don't know unicode you'll most certainly mess up your data. Do not go with the thousands of ISO codes. They'll only save you some memory. But you can do literally everything with UTF-8 even store chinese chars. But for that you'd need to store either 2 or 4 byte chars that makes it basically a utf-16 or utf-32.
If it's about URL encoding, again there you shouldn't mix encodings and be aware that at least for the domainname there are rules defined by different lobbies that provide applications like a browser. e.g. a Domain could be very similar like:
?ankofamerica.com or bankofamerica.com samesamebutdifferent ;)
Of course you need the filesystem to work with all encodings. Another plus for unicode using utf-8 filesystem.
If its about translations, think about the structure of documents. e.g. a book or an article. You have the docbook
specifications to understand about those structures. But in HTML its just about content blocks. So you'd like to have a translation on that level, also on webpage level or domain level.
So if a block doesn't exist its just not there, if a webpage doesn't exist you'll get redirected to the upper navigation level. If a domain should be completely different in navigation structure, then.. its a complete different structure to manage.
This can already be done with Typo3.
If its about frameworks, the most mature ones I know, to do the general stuff like MVC(buzzword I really hate it! Like "performance" If you want to sell something, use the word performance and featurerich and you sell... what the hell) is Zend
. It has proven to be a good thing to bring standards to php chaos coders. But, typo3 also has a Framework besides the CMS. Recently it has been redeveloped and is called flow3 now. The frameworks of course cover database abstraction, templating and concepts for caching, but have individual strengths.
If its about caching... that can be awefully complicated / multilayered. In PHP you'll think about accellerator, opcode, but also html, httpd, mysql, xml, css, js ... any kinds of caches. Of course some parts should be cached and dynamic parts like blog answers shouldn't. Some should be requested over AJAX with generated urls. JSON, hashbangs etc.
Then, you'd like to have any little component on your website to be accessed or managed only by certain users, so conceptually that plays a big role.
Also you'd like to make statistics, maybe have distributed system / a facebook of facebooks etc. any software to be built on top of your over the top cms ... so you need different type of databases inmemory, bigdata, xml, whatsoever.
well, I think thats enough for now. If you haven't heard of either typo3 / plone or mentioned frameworks, you have enough to study. On that path you'll find a lot of solutions for questions you haven't asked yet.
If then you think, lets make a new CMS because its 2013 and php is about to die anyway, then you r welcome to join any other group of developers hopefully not getting lost.
Good luck!
And btw. how about people will not having any websites anymore in the future? and we'll all be on google+? I hope developers become a little more creative and do something usefull(to not be assimilated by the borgle)
//// Edit /// Just a little thought for your existing application:
If you have a php mysql CMS and you wanted to embed multilang support. you could either use your table with an aditional column for any language or insert the translation with an object id and a language id in the same table or create an identical table for any language and insert objects there, then make a select union if you want to have them all displayed. For the database use utf8 general ci and of course in the front/backend use utf8 text/encoding. I have used url path segments for urls in the way you already explaned like
domain.org/en/about you can map the lang ID to your content table. anyway you need to have a map of parameters for your urls so you'd like to define a parameter to be mapped from a pathsegment in your URL that would be e.g.
domain.org/en/about/employees/IT/administrators/
lookup configuration
pageid| url
1 | /about/employees/../..
1 | /../about/employees../../
map parameters to url pathsegment ""
$parameterlist[lang] = array(0=>"nl",1=>"en"); // default nl if 0
$parameterlist[branch] = array(1=>"IT",2=>"DESIGN"); // default nl if 0
$parameterlist[employertype] = array(1=>"admin",1=>"engineer"); //could be a sql result
$websiteconfig[]=$userwhatever;
$websiteconfig[]=$parameterlist;
$someparameterlist[] = array("branch"=>$someid);
$someparameterlist[] = array("employertype"=>$someid);
function getURL($someparameterlist){
// todo foreach someparameter lookup pathsegment
return path;
}
per say, thats been covered already in upper post.
And to not forget, you'd need to "rewrite" the url to your generating php file that would in most cases be index.php
IntVar = int("".join(filter(str.isdigit, StringVar)))
It comes from the era of Line Printers and green-striped fan-fold paper.
Trust me, you ain't gonna need it...
@Christian Ullenboom' explanation is correct.
I'm surmising that the OBD2nerForm
code you posted is a static initializer block and that it is all generated. Based on that and on the stack trace, it seems likely that generated code is tripping up because it has found some component of your form that doesn't have the type that it is expecting.
I'd do the following to try and diagnose this:
My suspicion is that the root cause is a combination of something a bit unusual (or incorrect) with your form design, and bugs in the NetBeans form generator that is not coping with your form. If you can figure it out, a workaround may reveal itself.
You can also enable live-logging by setting the following in pytest.ini
or tox.ini
in your project root.
[pytest]
log_cli = True
Or specify it directly on cli
pytest -o log_cli=True
public enum DataFilters
{
[Display(Name= "Equals")]
Equals = 1,// Display Name and Enum Name are same
[Display(Name= "Does Not Equal")]
DoesNotEqual = 2, // Display Name and Enum Name are different
}
Now it will produce error in this case 1 "Equals"
public static string GetDisplayName(this Enum enumValue)
{
var enumMember = enumValue.GetType().GetMember(enumValue.ToString()).First();
return enumMember.GetCustomAttribute<DisplayAttribute>() != null ? enumMember.GetCustomAttribute<DisplayAttribute>().Name : enumMember.Name;
}
so if it is same return enum name rather than display name because enumMember.GetCustomAttribute() gets null if displayname and enum name are same.....
For Intellij IDEA version 11.0.2
File | Project Structure | Artifacts then you should press alt+insert or click the plus icon and create new artifact choose --> jar --> From modules with dependencies.
Next goto Build | Build artifacts --> choose your artifact.
source: http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/
thanks to Jim Petkus that did gave me a wonderful answer . but i was trying to solve my own script not to changing it to another plugin . My main focus was not using an independent plugin and do what i wanted just by using the jquery core !
and guess what i did find the problem .
var title = $("em").attr("title");
$("div").text(title);
this is what i add to my script and the blew codes to my html part :
<td> <em title=\"$weight\">$weight</em></td>
and found each row $weight value
thanks again to Jim Petkus
You could avoid hardcoding the full path by setting a JS variable in the header of your template, before wp_head()
is called, holding the template URL. Like:
<script type="text/javascript">
var templateUrl = '<?= get_bloginfo("template_url"); ?>';
</script>
And use that variable to set the background (I realize you know how to do this, I only include these details in case they helps others):
Reset.style.background = " url('"+templateUrl+"/images/searchfield_clear.png') ";
Didn't see an example of both in one query. So this example might help.
/**
INTERNATIONAL_ORDERS - table of orders by company by location by day
companyId, country, city, total, date
**/
SELECT country, city, sum(total) totalCityOrders
FROM INTERNATIONAL_ORDERS with (nolock)
WHERE companyId = 884501253109
GROUP BY country, city
HAVING country = 'MX'
ORDER BY sum(total) DESC
This filters the table first by the companyId, then groups it (by country and city) and additionally filters it down to just city aggregations of Mexico. The companyId was not needed in the aggregation but we were able to use WHERE to filter out just the rows we wanted before using GROUP BY.
Another way:
md5=$(md5sum ${my_iso_file} | sed '/ .*//' )
no lambda method
# sort dictionary by value
d = {'a1': 'fsdfds', 'g5': 'aa3432ff', 'ca':'zz23432'}
def getkeybyvalue(d,i):
for k, v in d.items():
if v == i:
return (k)
sortvaluelist = sorted(d.values())
sortresult ={}
for i1 in sortvaluelist:
key = getkeybyvalue(d,i1)
sortresult[key] = i1
print ('=====sort by value=====')
print (sortresult)
print ('=======================')
Set a default value for people
with ngInit
<div ng-app>
<div ng-init="people=1" />
<input type="radio" ng-model="people" value="1"><label>1</label>
<input type="radio" ng-model="people" value="2"><label>2</label>
<input type="radio" ng-model="people" value="3"><label>3</label>
<ul>
<li>{{10*people}}€</li>
<li>{{8*people}}€</li>
<li>{{30*people}}€</li>
</ul>
</div>
Demo: Fiddle
I've found the answer regarding how to do this myself. Inside the model code, just put:
For Rails <= 2:
include ActionController::UrlWriter
For Rails 3:
include Rails.application.routes.url_helpers
This magically makes thing_path(self)
return the URL for the current thing, or other_model_path(self.association_to_other_model)
return some other URL.
In my case (using XCode 10.0) nothing worked but this:
File > Project Settings... > Shared Project Settings: > Build System --> Selected "Legacy Build System" instead of the default "New Build System (Default)".
There are three scenarios (that I can think of) where you would call a method in a subclass where the method exits in the parent class:
Method is not overwritten by subclass, only exists in parent.
This is the same as your example, and generally it's better to use $this -> get_species();
You are right that in this case the two are effectively the same, but the method has been inherited by the subclass, so there is no reason to differentiate. By using $this
you stay consistent between inherited methods and locally declared methods.
Method is overwritten by the subclass and has totally unique logic from the parent.
In this case, you would obviously want to use $this -> get_species();
because you don't want the parent's version of the method executed. Again, by consistently using $this
, you don't need to worry about the distinction between this case and the first.
Method extends parent class, adding on to what the parent method achieves.
In this case, you still want to use `$this -> get_species();
when calling the method from other methods of the subclass. The one place you will call the parent method would be from the method that is overwriting the parent method. Example:
abstract class Animal {
function get_species() {
echo "I am an animal.";
}
}
class Dog extends Animal {
function __construct(){
$this->get_species();
}
function get_species(){
parent::get_species();
echo "More specifically, I am a dog.";
}
}
The only scenario I can imagine where you would need to call the parent method directly outside of the overriding method would be if they did two different things and you knew you needed the parent's version of the method, not the local. This shouldn't be the case, but if it did present itself, the clean way to approach this would be to create a new method with a name like get_parentSpecies()
where all it does is call the parent method:
function get_parentSpecies(){
parent::get_species();
}
Again, this keeps everything nice and consistent, allowing for changes/modifications to the local method rather than relying on the parent method.
You dont need this line: setContentView(txtCambiado);
You probably want to use the assets_base_urls
configuration.
framework:
templating:
assets_base_urls:
http: [http://www.website.com]
ssl: [https://www.website.com]
http://symfony.com/doc/current/reference/configuration/framework.html#assets
Note that the configuration is different since Symfony 2.7:
framework:
# ...
assets:
base_urls:
- 'http://cdn.example.com/'
Facebook has indeed added the SDK to the Maven Central repositories. To configure your project using the maven repo's instance, you'll need to do 2 things:
In your projects top-level build.gradle file, add the Maven Central repositories. Mine looks like this:
repositories {
jcenter() // This is the default repo
mavenCentral() // This is the Maven Central repo
}
In the app-level build.grade file, add the Facebook sdk dependency:
dependencies {
compile 'com.facebook.android:facebook-android-sdk:4.5.0' // Adjust the version accordingly
// All your other dependencies.
}
You can also adjust the specific Facebook SDK version as well. For a list of available versions in the maven repository click this link.
You can create a new file, setenv.sh (or setenv.bat) inside tomcats bin directory and add following line there
export CLASSPATH=$CLASSPATH:/XX/xx/PATH_TO_DIR
If you are using Windows try out the following:
and check if it's status is 'Running'. In case not, right click >> start.
Hope this helps!
If you have removed WAMP from boot services, it won't work – try the following:
wampapache
and wampmysqld
, Click 'properties'Manual
or automatic
This will work!
const data = [{
name: 'BMW',
value: '25641'
}, {
name: 'Apple',
value: '45876'
},
{
name: 'Benz',
value: '65784'
},
{
name: 'Toyota',
value: '254'
}
]
const obj = {
carsList: [{
name: 'Ford',
value: '47563'
}, {
name: 'Toyota',
value: '254'
}],
pastriesList: [],
fruitsList: [{
name: 'Apple',
value: '45876'
}, {
name: 'Pineapple',
value: '84523'
}]
}
let keys = Object.keys(obj);
result = {};
for(key of keys){
let a = [...data,...obj[key]];
result[key] = a;
}
The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.
CONTIGUOUS NON-PRINTING Ruby Code
This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml
, etc.
This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>
DETAILS:
Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:
<%# if flash[:myErrors] %>
<%# if flash[:myErrors].any? %>
<%# if @post.id.nil? %>
<%# if @myPost!=-1 %>
<%# @post = @myPost %>
<%# else %>
<%# @post = Post.new %>
<%# end %>
<%# end %>
<%# end %>
<%# end %>
YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:
<%#
if flash[:myErrors] then
if flash[:myErrors].any? then
if @post.id.nil? then
if @myPost!=-1 then
@post = @myPost
else
@post = Post.new
end
end
end
end
%>
All the answers so far are incorrect. The Registry normally uses port 1099, but you can change it. But that's not the end of the story. Remote objects also use ports, and not necessarily 1099.
If you don't specify a port when exporting, RMI uses a random port. The solution is therefore to specify a port number when exporting. And this is a port that needs opening in the firewall, if any.
In the case where your remote object extends UnicastRemoteObject
, have its constructor call super(port)
with some non-zero port number.
In the case where it doesn't extend UnicastRemoteObject
, provide a non-zero port number to UnicastRemoteObject.exportObject()
.
There are several wrinkles to this.
If you aren't using socket factories, and you provide a non-zero port number when exporting your first remote object, RMI will automatically share that port with subsequently exported remote objects without specified port numbers, or specifying zero. That first remote object includes a Registry created with LocateRegistry.createRegistry().
So if you create a Registry
on port 1099, all other objects exported from that JVM can share port 1099.
If you are using socket factories, your RMIServerSocketFactory
must have a sensible implementation of equals()
for port sharing to work, i.e. one that doesn't just rely on object identity via ==
or Object.equals()
.
If either you don't provide a server socket factory, or you do provide one with a sensible equals()
method, but not both, you can use the same non-zero explicit port number for all remote objects, e.g. createRegistry(1099)
followed by any number of super(1099)
or exportObject(..., 1099)
calls.
window.location.search.slice(1).split('&').reduce((res, val) => ({...res, [val.split('=')[0]]: val.split('=')[1]}), {})
Sometimes you may be running code on a virtual server elsewhere - That can get muddy when running NODEJS or other flavors.
Here is a fix that will allow you to use any timezone easily.
Check here for list of timezones
Just put your time zone phrase within the brackets of your FORMAT line.
In this case - I am converting EPOCH to Eastern.
//RE: https://www.npmjs.com/package/date-and-time
const date = require('date-and-time');
let unixEpochTime = (seconds * 1000);
const dd=new Date(unixEpochTime);
let myFormattedDateTime = date.format(dd, 'YYYY/MM/DD HH:mm:ss A [America/New_York]Z');
let myFormattedDateTime24 = date.format(dd, 'YYYY/MM/DD HH:mm:ss [America/New_York]Z');
I don't if it is best or not but you can use it also
List<string> data = new List<string>
(new string[] { "Computer", "A", "B", "Computer", "B", "A" });
int[] indexes = Enumerable.Range(0, data.Count).Where
(i => data[i] == "Computer").ToArray();
Array.ForEach(indexes, i => data[i] = "Calculator");
var payeeCountry = document.getElementById( "payeeCountry" );
alert( payeeCountry.options[ yourSelect.selectedIndex ].value );
time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);
First of all, add the System.Text
namespace
using System.Text;
Then use this code
string input = "some text";
byte[] array = Encoding.ASCII.GetBytes(input);
Hope to fix it!
I make another solution for dropdown. Hope this is helpfull Just add this js script
<script type="text/javascript"> jQuery("document").ready(function() {
jQuery("ul.dropdown-menu > .dropdown.parent").click(function(e) {
e.preventDefault();
e.stopPropagation();
if (jQuery(this).hasClass('open2'))
jQuery(this).removeClass('open2');
else {
jQuery(this).addClass('open2');
}
});
}); < /script>
<style type="text/css">.open2{display:block; position:relative;}</style>
You first create the filter with fspecial and then convolve the image with the filter using imfilter (which works on multidimensional images as in the example).
You specify sigma
and hsize
in fspecial
.
%%# Read an image
I = imread('peppers.png');
%# Create the gaussian filter with hsize = [5 5] and sigma = 2
G = fspecial('gaussian',[5 5],2);
%# Filter it
Ig = imfilter(I,G,'same');
%# Display
imshow(Ig)
You can run the passwd command and send it piped input. So, do something like:
echo thePassword | passwd theUsername --stdin
Just center the div in HTML:
#test {
width: 100px;
height:100px;
margin: 0px auto;
border: 1px solid red;
}
<div id="test">
<canvas width="100" height="100"></canvas>
</div>
Just change the height and width to whatever and you've got a centered div
You can call fs.unlink(path, callback)
for Asynchronous unlink(2) or fs.unlinkSync(path)
for Synchronous unlink(2).
Where path
is file-path which you want to remove.
For example we want to remove discovery.docx
file from c:/book
directory. So my file-path is c:/book/discovery.docx
. So code for removing that file will be,
var fs = require('fs');
var filePath = 'c:/book/discovery.docx';
fs.unlinkSync(filePath);
I found this on the MySQL support page for the Visual Studio connectors.
It appears that they do not support the MySQL to Visual Studio EXPRESS editions.
So to answer your question, yes you may need the ultimate version or professional edition - just not Express to be able to use MySQL with VS.
http://forums.mysql.com/read.php?38,546265,564533#msg-564533
Another alternative would be JasperReports: JasperReports Library. It uses iText itself and is more than a PDF library you asked for, but if it fits your needs I'd go for it.
Simply put, it allows you to design reports that can be filled during runtime. If you use a custom datasource, you might be able to integrate JasperReports easily into the existing system. It would save you the whole layouting troubles, e.g. when invoices span over more sites where each side should have a footer and so on.
Try to Use Flex as that is the new standard of html5.
http://jsfiddle.net/maxspan/1b431hxm/
<div id="row1">
<div id="column1">I am column one</div>
<div id="column2">I am column two</div>
</div>
#row1{
display:flex;
flex-direction:row;
justify-content: space-around;
}
#column1{
display:flex;
flex-direction:column;
}
#column2{
display:flex;
flex-direction:column;
}
You can use the Logical NOT !
operator:
if (!$(this).parent().next().is('ul')){
Or equivalently (see comments below):
if (! ($(this).parent().next().is('ul'))){
For more information, see the Logical Operators section of the MDN docs.
<?php if( $_product->getTypeId() == 'simple' ): ?>
//your code for simple products only
<?php endif; ?>
<?php if( $_product->getTypeId() == 'grouped' ): ?>
//your code for grouped products only
<?php endif; ?>
So on. It works! Magento 1.6.1, place in the view.phtml
A year or so has passed since the question was asked, but I thought a substantial improvement of the answers was possible. I find this the easiest and most versatile script, because it checks whether a button has been checked, and if so, what its value is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check radio checked and its value</title>
</head>
<body>
<form name="theFormName">
<input type="radio" name="theRadioGroupName" value="10">
<input type="radio" name="theRadioGroupName" value="20">
<input type="radio" name="theRadioGroupName" value="30">
<input type="radio" name="theRadioGroupName" value="40">
<input type="button" value="Check" onclick="getRadioValue('theRadioGroupName')">
</form>
<script>
function getRadioValue(groupName) {
var radios = theFormName.elements[groupName];
window.rdValue; // declares the global variable 'rdValue'
for (var i=0; i<radios.length; i++) {
var someRadio = radios[i];
if (someRadio.checked) {
rdValue = someRadio.value;
break;
}
else rdValue = 'noRadioChecked';
}
if (rdValue == '10') {
alert('10'); // or: console.log('10')
}
else if (rdValue == 'noRadioChecked') {
alert('no radio checked');
}
}
</script>
</body>
</html>
You can also call the function within another function, like this:
function doSomething() {
getRadioValue('theRadioGroupName');
if (rdValue == '10') {
// do something
}
else if (rdValue == 'noRadioChecked') {
// do something else
}
}
everyone comment about SQL, but what hapend in EntityFramework? I spent reading the whole post and no one solved EF. So after a few days a found solution:
EF Core in the context to create the model there is an instruction like this: modelBuilder.Entity<Cliente>(entity => { entity.Property(e => e.Id).ValueGeneratedNever();
this produces the error too, solution: you have to change by ValueGeneratedOnAdd() and its works!
ZoneId z = ZoneId.of( "America/Montreal" ); // A date only has meaning within a specific time zone. At any given moment, the date varies around the globe by zone.
LocalDate ld =
givenJavaUtilDate.toInstant() // Convert from legacy class `Date` to modern class `Instant` using new methods added to old classes.
.atZone( z ) // Adjust into the time zone in order to determine date.
.toLocalDate(); // Extract date-only value.
LocalDate today = LocalDate.now( z ); // Get today’s date for specific time zone.
LocalDate kwanzaaStart = today.withMonth( Month.DECEMBER ).withDayOfMonth( 26 ); // Kwanzaa starts on Boxing Day, day after Christmas.
LocalDate kwanzaaStop = kwanzaaStart.plusWeeks( 1 ); // Kwanzaa lasts one week.
Boolean isDateInKwanzaaThisYear = (
( ! today.isBefore( kwanzaaStart ) ) // Short way to say "is equal to or is after".
&&
today.isBefore( kwanzaaStop ) // Half-Open span of time, beginning inclusive, ending is *exclusive*.
)
Date-time work commonly employs the "Half-Open" approach to defining a span of time. The beginning is inclusive while the ending is exclusive. So a week starting on a Monday runs up to, but does not include, the following Monday.
Java 8 and later comes with the java.time
framework built-in. Supplants the old troublesome classes including java.util.Date/.Calendar
and SimpleDateFormat
. Inspired by the successful Joda-Time library. Defined by JSR 310. Extended by the ThreeTen-Extra project.
An Instant
is a moment on the timeline in UTC with nanosecond resolution.
Instant
Convert your java.util.Date
objects to Instant objects.
Instant start = myJUDateStart.toInstant();
Instant stop = …
If getting java.sql.Timestamp
objects through JDBC from a database, convert to java.time.Instant in a similar way. A java.sql.Timestamp
is already in UTC so no need to worry about time zones.
Instant start = mySqlTimestamp.toInstant() ;
Instant stop = …
Get the current moment for comparison.
Instant now = Instant.now();
Compare using the methods isBefore, isAfter, and equals.
Boolean containsNow = ( ! now.isBefore( start ) ) && ( now.isBefore( stop ) ) ;
LocalDate
Perhaps you want to work with only the date, not the time-of-day.
The LocalDate
class represents a date-only value, without time-of-day and without time zone.
LocalDate start = LocalDate.of( 2016 , 1 , 1 ) ;
LocalDate stop = LocalDate.of( 2016 , 1 , 23 ) ;
To get the current date, specify a time zone. At any given moment, today’s date varies by time zone. For example, a new day dawns earlier in Paris than in Montréal.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
We can use the isEqual
, isBefore
, and isAfter
methods to compare. In date-time work we commonly use the Half-Open approach where the beginning of a span of time is inclusive while the ending is exclusive.
Boolean containsToday = ( ! today.isBefore( start ) ) && ( today.isBefore( stop ) ) ;
Interval
If you chose to add the ThreeTen-Extra library to your project, you could use the Interval
class to define a span of time. That class offers methods to test if the interval contains, abuts, encloses, or overlaps other date-times/intervals.
The Interval
class works on Instant
objects. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
We can adjust the LocalDate
into a specific moment, the first moment of the day, by specifying a time zone to get a ZonedDateTime
. From there we can get back to UTC by extracting a Instant
.
ZoneId z = ZoneId.of( "America/Montreal" );
Interval interval =
Interval.of(
start.atStartOfDay( z ).toInstant() ,
stop.atStartOfDay( z ).toInstant() );
Instant now = Instant.now();
Boolean containsNow = interval.contains( now );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time
classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time
classes?
java.time
functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.The ThreeTen-Extra project extends java.time
with additional classes. This project is a proving ground for possible future additions to java.time
. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Because my edits to the above were rejected (did any of you actually try?), here's what you really need to make this work:
Windows (And Mac Office 2011+):
(Excel Timestamp - 25569) * 86400
(Unix Timestamp / 86400) + 25569
MAC OS X (pre Office 2011):
(Excel Timestamp - 24107) * 86400
(Unix Timestamp / 86400) + 24107
I've done this in the past.
Either do it manually, (build a nice gui that helps the user do it quickly) or have it automated and check against a recent address database (you have to buy that) and manually handle errors.
Manual handling will take about 10 seconds each, meaning you can do 3600/10 = 360 per hour, so 4000 should take you approximately 11-12 hours. This will give you a high rate of accuracy.
For automation, you need a recent US address database, and tweak your rules against that. I suggest not going fancy on the regex (hard to maintain long-term, so many exceptions). Go for 90% match against the database, do the rest manually.
Do get a copy of Postal Addressing Standards (USPS) at http://pe.usps.gov/cpim/ftp/pubs/Pub28/pub28.pdf and notice it is 130+ pages long. Regexes to implement that would be nuts.
For international addresses, all bets are off. US-based workers would not be able to validate.
Alternatively, use a data service. I have, however, no recommendations.
Furthermore: when you do send out the stuff in the mail (that's what it's for, right?) make sure you put "address correction requested" on the envelope (in the right place) and update the database. (We made a simple gui for the front desk person to do that; the person who actually sorts through the mail)
Finally, when you have scrubbed data, look for duplicates.
var query = from a in d.tbl_Usuarios
from b in d.tblComidaPreferidas
from c in d.tblLugarNacimientoes
select new
{
_nombre = a.Nombre,
_comida = b.ComidaPreferida,
_lNacimiento = c.Ciudad
};
foreach (var i in query)
{
Console.WriteLine($"{i._nombre } le gusta {i._comida} y nació en {i._lNacimiento}");
}
You should implement Comparable <Person>
. Assuming all fields will not be null (for simplicity sake), that age is an int, and compare ranking is first, last, age, the compareTo
method is quite simple:
public int compareTo(Person other) {
int i = firstName.compareTo(other.firstName);
if (i != 0) return i;
i = lastName.compareTo(other.lastName);
if (i != 0) return i;
return Integer.compare(age, other.age);
}
int is a binary representation of a whole number, double is a double-precision floating point number.