A couple of things to enhance the other answers. First, you should never return a HashMap
, which is a specific implementation. Return instead a plain old java.util.Map
. But that's actually not right for this example, anyway. Your code only returns the last row of the ResultSet as a (Hash)Map. You instead want to return a List<Map<String,Object>>
. Think about how you should modify your code to do that. (Or you could take Dave Newton's suggestion).
You just can put your query as a subquery:
SELECT avg(count)
FROM
(
SELECT COUNT (*) AS Count
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time )
FROM Table B
WHERE (B.Id = T.Id))
GROUP BY T.Grouping
) as counts
Edit: I think this should be the same:
SELECT count(*) / count(distinct T.Grouping)
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time)
FROM Table B
WHERE (B.Id = T.Id))
For reference, cursor.rowcount
will only return on CREATE
, UPDATE
and DELETE
statements:
| rowcount
| This read-only attribute specifies the number of rows the last DML statement
| (INSERT, UPDATE, DELETE) affected. This is set to -1 for SELECT statements.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import com.google.gson.Gson;
public class ObjectMapper {
//generic method to convert JDBC resultSet into respective DTo class
@SuppressWarnings("unchecked")
public static Object mapValue(List<Map<String, Object>> rows,Class<?> className) throws Exception
{
List<Object> response=new ArrayList<>();
Gson gson=new Gson();
for(Map<String, Object> row:rows){
org.json.simple.JSONObject jsonObject = new JSONObject();
jsonObject.putAll(row);
String json=jsonObject.toJSONString();
Object actualObject=gson.fromJson(json, className);
response.add(actualObject);
}
return response;
}
public static void main(String args[]) throws Exception{
List<Map<String, Object>> rows=new ArrayList<Map<String, Object>>();
//Hardcoded data for testing
Map<String, Object> row1=new HashMap<String, Object>();
row1.put("name", "Raja");
row1.put("age", 22);
row1.put("location", "India");
Map<String, Object> row2=new HashMap<String, Object>();
row2.put("name", "Rani");
row2.put("age", 20);
row2.put("location", "India");
rows.add(row1);
rows.add(row2);
@SuppressWarnings("unchecked")
List<Dto> res=(List<Dto>) mapValue(rows, Dto.class);
}
}
public class Dto {
private String name;
private Integer age;
private String location;
//getters and setters
}
Try the above code .This can be used as a generic method to map JDBC result to respective DTO class.
Just for the fun, I'm offering an alternative solution using jOOQ and Java 8. Instead of using jOOQ, you could be using any other API that maps JDBC ResultSet
to List
, such as Spring JDBC or Apache DbUtils, or write your own ResultSetIterator
:
List<Object> list =
DSL.using(connection)
.fetch("SELECT col1, col2, col3, ...")
.stream()
.flatMap(r -> Arrays.stream(r.intoArray()))
.collect(Collectors.toList());
List<Object> list =
DSL.using(connection)
.fetch("SELECT col1, col2, col3, ...")
.stream()
.flatMap(Record::intoStream)
.collect(Collectors.toList());
(Disclaimer, I work for the company behind jOOQ)
This answer may not be the most efficient, but it sure is dynamic. Pairing native JDBC with Google's Gson library, I easily can convert from an SQL result to a JSON stream.
I have included the converter, example DB properties file, SQL table generation, and a Gradle build file (with dependencies used).
import java.io.PrintWriter;
import com.oracle.jdbc.ResultSetConverter;
public class QueryApp {
public static void main(String[] args) {
PrintWriter writer = new PrintWriter(System.out);
String dbProps = "/database.properties";
String indent = " ";
writer.println("Basic SELECT:");
ResultSetConverter.queryToJson(writer, dbProps, "SELECT * FROM Beatles", indent, false);
writer.println("\n\nIntermediate SELECT:");
ResultSetConverter.queryToJson(writer, dbProps, "SELECT first_name, last_name, getAge(date_of_birth) as age FROM Beatles", indent, true);
}
}
package com.oracle.jdbc;
import java.io.*;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.*;
import com.google.common.reflect.TypeToken;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonWriter;
public class ResultSetConverter {
public static final Type RESULT_TYPE = new TypeToken<List<Map<String, Object>>>() {
private static final long serialVersionUID = -3467016635635320150L;
}.getType();
public static void queryToJson(Writer writer, String connectionProperties, String query, String indent, boolean closeWriter) {
Connection conn = null;
Statement stmt = null;
GsonBuilder gson = new GsonBuilder();
JsonWriter jsonWriter = new JsonWriter(writer);
if (indent != null) jsonWriter.setIndent(indent);
try {
Properties props = readConnectionInfo(connectionProperties);
Class.forName(props.getProperty("driver"));
conn = openConnection(props);
stmt = conn.createStatement();
gson.create().toJson(QueryHelper.select(stmt, query), RESULT_TYPE, jsonWriter);
if (closeWriter) jsonWriter.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
try {
if (closeWriter && jsonWriter != null) jsonWriter.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
private static Properties readConnectionInfo(String resource) throws IOException {
Properties properties = new Properties();
InputStream in = ResultSetConverter.class.getResourceAsStream(resource);
properties.load(in);
in.close();
return properties;
}
private static Connection openConnection(Properties connectionProperties) throws IOException, SQLException {
String database = connectionProperties.getProperty("database");
String username = connectionProperties.getProperty("username");
String password = connectionProperties.getProperty("password");
return DriverManager.getConnection(database, username, password);
}
}
package com.oracle.jdbc;
import java.sql.*;
import java.text.*;
import java.util.*;
import com.google.common.base.CaseFormat;
public class QueryHelper {
static DateFormat DATE_FORMAT = new SimpleDateFormat("YYYY-MM-dd");
public static List<Map<String, Object>> select(Statement stmt, String query) throws SQLException {
ResultSet resultSet = stmt.executeQuery(query);
List<Map<String, Object>> records = mapRecords(resultSet);
resultSet.close();
return records;
}
public static List<Map<String, Object>> mapRecords(ResultSet resultSet) throws SQLException {
List<Map<String, Object>> records = new ArrayList<Map<String, Object>>();
ResultSetMetaData metaData = resultSet.getMetaData();
while (resultSet.next()) {
records.add(mapRecord(resultSet, metaData));
}
return records;
}
public static Map<String, Object> mapRecord(ResultSet resultSet, ResultSetMetaData metaData) throws SQLException {
Map<String, Object> record = new HashMap<String, Object>();
for (int c = 1; c <= metaData.getColumnCount(); c++) {
String columnType = metaData.getColumnTypeName(c);
String columnName = formatPropertyName(metaData.getColumnName(c));
Object value = resultSet.getObject(c);
if (columnType.equals("DATE")) {
value = DATE_FORMAT.format(value);
}
record.put(columnName, value);
}
return record;
}
private static String formatPropertyName(String property) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, property);
}
}
driver=com.mysql.jdbc.Driver
database=jdbc:mysql://localhost/JDBC_Tutorial
username=root
password=
-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jan 12, 2016 at 07:40 PM
-- Server version: 10.1.8-MariaDB
-- PHP Version: 5.6.14
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `jdbc_tutorial`
--
CREATE DATABASE IF NOT EXISTS `jdbc_tutorial` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `jdbc_tutorial`;
DELIMITER $$
--
-- Functions
--
DROP FUNCTION IF EXISTS `getAge`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `getAge` (`in_dob` DATE) RETURNS INT(11) NO SQL
BEGIN
DECLARE l_age INT;
IF DATE_FORMAT(NOW(),'00-%m-%d') >= DATE_FORMAT(in_dob,'00-%m-%d') THEN
-- This person has had a birthday this year
SET l_age=DATE_FORMAT(NOW(),'%Y')-DATE_FORMAT(in_dob,'%Y');
ELSE
-- Yet to have a birthday this year
SET l_age=DATE_FORMAT(NOW(),'%Y')-DATE_FORMAT(in_dob,'%Y')-1;
END IF;
RETURN(l_age);
END$$
DELIMITER ;
-- --------------------------------------------------------
--
-- Table structure for table `beatles`
--
DROP TABLE IF EXISTS `beatles`;
CREATE TABLE IF NOT EXISTS `beatles` (
`id` int(11) NOT NULL,
`first_name` varchar(255) DEFAULT NULL,
`last_name` varchar(255) DEFAULT NULL,
`date_of_birth` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Truncate table before insert `beatles`
--
TRUNCATE TABLE `beatles`;
--
-- Dumping data for table `beatles`
--
INSERT INTO `beatles` (`id`, `first_name`, `last_name`, `date_of_birth`) VALUES(100, 'John', 'Lennon', '1940-10-09');
INSERT INTO `beatles` (`id`, `first_name`, `last_name`, `date_of_birth`) VALUES(101, 'Paul', 'McCartney', '1942-06-18');
INSERT INTO `beatles` (`id`, `first_name`, `last_name`, `date_of_birth`) VALUES(102, 'George', 'Harrison', '1943-02-25');
INSERT INTO `beatles` (`id`, `first_name`, `last_name`, `date_of_birth`) VALUES(103, 'Ringo', 'Starr', '1940-07-07');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'
mainClassName = 'com.oracle.jdbc.QueryApp'
repositories {
maven {
url "http://repo1.maven.org/maven2"
}
}
jar {
baseName = 'jdbc-tutorial'
version = '1.0.0'
}
sourceCompatibility = 1.7
targetCompatibility = 1.7
dependencies {
compile 'mysql:mysql-connector-java:5.1.16'
compile 'com.google.guava:guava:18.0'
compile 'com.google.code.gson:gson:1.7.2'
}
task wrapper(type: Wrapper) {
gradleVersion = '2.9'
}
[
{
"firstName": "John",
"lastName": "Lennon",
"dateOfBirth": "1940-10-09",
"id": 100
},
{
"firstName": "Paul",
"lastName": "McCartney",
"dateOfBirth": "1942-06-18",
"id": 101
},
{
"firstName": "George",
"lastName": "Harrison",
"dateOfBirth": "1943-02-25",
"id": 102
},
{
"firstName": "Ringo",
"lastName": "Starr",
"dateOfBirth": "1940-07-07",
"id": 103
}
]
[
{
"firstName": "John",
"lastName": "Lennon",
"age": 75
},
{
"firstName": "Paul",
"lastName": "McCartney",
"age": 73
},
{
"firstName": "George",
"lastName": "Harrison",
"age": 72
},
{
"firstName": "Ringo",
"lastName": "Starr",
"age": 75
}
]
Since Result Set is an interface, When you obtain a reference to a ResultSet through a JDBC call, you are getting an instance of a class that implements the ResultSet interface. This class provides concrete implementations of all of the ResultSet methods.
Interfaces are used to divorce implementation from, well, interface. This allows the creation of generic algorithms and the abstraction of object creation. For example, JDBC drivers for different databases will return different ResultSet implementations, but you don't have to change your code to make it work with the different drivers
In very short, if your ResultSet contains result, then using rs.next return true if you have recordset else it returns false.
Following two options worked for me:
1) A function that returns the number of rows in your ResultSet.
private int resultSetCount(ResultSet resultSet) throws SQLException{
try{
int i = 0;
while (resultSet.next()) {
i++;
}
return i;
} catch (Exception e){
System.out.println("Error getting row count");
e.printStackTrace();
}
return 0;
}
2) Create a second SQL statement with the COUNT option.
package all.is.well;_x000D_
import java.io.IOException;_x000D_
import java.io.RandomAccessFile;_x000D_
import java.util.concurrent.ExecutorService;_x000D_
import java.util.concurrent.Executors;_x000D_
import junit.framework.TestCase;_x000D_
_x000D_
/**_x000D_
* @author Naresh Bhabat_x000D_
* _x000D_
Following implementation helps to deal with extra large files in java._x000D_
This program is tested for dealing with 2GB input file._x000D_
There are some points where extra logic can be added in future._x000D_
_x000D_
_x000D_
Pleasenote: if we want to deal with binary input file, then instead of reading line,we need to read bytes from read file object._x000D_
_x000D_
_x000D_
_x000D_
It uses random access file,which is almost like streaming API._x000D_
_x000D_
_x000D_
* ****************************************_x000D_
Notes regarding executor framework and its readings._x000D_
Please note :ExecutorService executor = Executors.newFixedThreadPool(10);_x000D_
_x000D_
* for 10 threads:Total time required for reading and writing the text in_x000D_
* :seconds 349.317_x000D_
* _x000D_
* For 100:Total time required for reading the text and writing : seconds 464.042_x000D_
* _x000D_
* For 1000 : Total time required for reading and writing text :466.538 _x000D_
* For 10000 Total time required for reading and writing in seconds 479.701_x000D_
*_x000D_
* _x000D_
*/_x000D_
public class DealWithHugeRecordsinFile extends TestCase {_x000D_
_x000D_
static final String FILEPATH = "C:\\springbatch\\bigfile1.txt.txt";_x000D_
static final String FILEPATH_WRITE = "C:\\springbatch\\writinghere.txt";_x000D_
static volatile RandomAccessFile fileToWrite;_x000D_
static volatile RandomAccessFile file;_x000D_
static volatile String fileContentsIter;_x000D_
static volatile int position = 0;_x000D_
_x000D_
public static void main(String[] args) throws IOException, InterruptedException {_x000D_
long currentTimeMillis = System.currentTimeMillis();_x000D_
_x000D_
try {_x000D_
fileToWrite = new RandomAccessFile(FILEPATH_WRITE, "rw");//for random write,independent of thread obstacles _x000D_
file = new RandomAccessFile(FILEPATH, "r");//for random read,independent of thread obstacles _x000D_
seriouslyReadProcessAndWriteAsynch();_x000D_
_x000D_
} catch (IOException e) {_x000D_
// TODO Auto-generated catch block_x000D_
e.printStackTrace();_x000D_
}_x000D_
Thread currentThread = Thread.currentThread();_x000D_
System.out.println(currentThread.getName());_x000D_
long currentTimeMillis2 = System.currentTimeMillis();_x000D_
double time_seconds = (currentTimeMillis2 - currentTimeMillis) / 1000.0;_x000D_
System.out.println("Total time required for reading the text in seconds " + time_seconds);_x000D_
_x000D_
}_x000D_
_x000D_
/**_x000D_
* @throws IOException_x000D_
* Something asynchronously serious_x000D_
*/_x000D_
public static void seriouslyReadProcessAndWriteAsynch() throws IOException {_x000D_
ExecutorService executor = Executors.newFixedThreadPool(10);//pls see for explanation in comments section of the class_x000D_
while (true) {_x000D_
String readLine = file.readLine();_x000D_
if (readLine == null) {_x000D_
break;_x000D_
}_x000D_
Runnable genuineWorker = new Runnable() {_x000D_
@Override_x000D_
public void run() {_x000D_
// do hard processing here in this thread,i have consumed_x000D_
// some time and eat some exception in write method._x000D_
writeToFile(FILEPATH_WRITE, readLine);_x000D_
// System.out.println(" :" +_x000D_
// Thread.currentThread().getName());_x000D_
_x000D_
}_x000D_
};_x000D_
executor.execute(genuineWorker);_x000D_
}_x000D_
executor.shutdown();_x000D_
while (!executor.isTerminated()) {_x000D_
}_x000D_
System.out.println("Finished all threads");_x000D_
file.close();_x000D_
fileToWrite.close();_x000D_
}_x000D_
_x000D_
/**_x000D_
* @param filePath_x000D_
* @param data_x000D_
* @param position_x000D_
*/_x000D_
private static void writeToFile(String filePath, String data) {_x000D_
try {_x000D_
// fileToWrite.seek(position);_x000D_
data = "\n" + data;_x000D_
if (!data.contains("Randomization")) {_x000D_
return;_x000D_
}_x000D_
System.out.println("Let us do something time consuming to make this thread busy"+(position++) + " :" + data);_x000D_
System.out.println("Lets consume through this loop");_x000D_
int i=1000;_x000D_
while(i>0){_x000D_
_x000D_
i--;_x000D_
}_x000D_
fileToWrite.write(data.getBytes());_x000D_
throw new Exception();_x000D_
} catch (Exception exception) {_x000D_
System.out.println("exception was thrown but still we are able to proceeed further"_x000D_
+ " \n This can be used for marking failure of the records");_x000D_
//exception.printStackTrace();_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
}
_x000D_
The answer by Leos Literak is correct but now outdated, using one of the troublesome old date-time classes, java.sql.Timestamp
.
it is really a DATETIME in the DB
Nope, it is not. No such data type as DATETIME
in Oracle database.
I was looking for a getDateTime method.
Use java.time classes in JDBC 4.2 and later rather than troublesome legacy classes seen in your Question. In particular, rather than java.sql.TIMESTAMP
, use Instant
class for a moment such as the SQL-standard type TIMESTAMP WITH TIME ZONE
.
Contrived code snippet:
if(
JDBCType.valueOf(
myResultSetMetaData.getColumnType( … )
)
.equals( JDBCType.TIMESTAMP_WITH_TIMEZONE )
) {
Instant instant = myResultSet.getObject( … , Instant.class ) ;
}
Oddly enough, the JDBC 4.2 specification does not require support for the two most commonly used java.time classes, Instant
and ZonedDateTime
. So if your JDBC does not support the code seen above, use OffsetDateTime
instead.
OffsetDateTime offsetDateTime = myResultSet.getObject( … , OffsetDateTime.class ) ;
I would like to get the DATETIME column from an Oracle DB Table with JDBC.
According to this doc, there is no column data type DATETIME
in the Oracle database. That terminology seems to be Oracle’s word to refer to all their date-time types as a group.
I do not see the point of your code that detects the type and branches on which data-type. Generally, I think you should be crafting your code explicitly in the context of your particular table and particular business problem. Perhaps this would be useful in some kind of generic framework. If you insist, read on to learn about various types, and to learn about the extremely useful new java.time classes built into Java 8 and later that supplant the classes used in your Question.
valueToInsert = aDate.toString();
You appear to trying to exchange date-time values with your database as text, as String
objects. Don’t.
To exchange date-time values with your database, use date-time objects. Now in Java 8 and later, that means java.time objects, as discussed below.
You may be confusing three sets of date-time related data types:
The SQL standard defines five types:
DATE
TIME WITHOUT TIME ZONE
TIME WITH TIME ZONE
TIMESTAMP WITHOUT TIME ZONE
TIMESTAMP WITH TIME ZONE
DATE
TIME
or TIME WITHOUT TIME ZONE
TIME WITH TIME ZONE
(or TIMETZ
)TIMESTAMP
or TIMESTAMP WITHOUT TIME ZONE
TIMESTAMP WITH TIME ZONE
(or TIMESTAMPTZ
)Many database offer their own date-time related types. The proprietary types vary widely. Some are old, legacy types that should be avoided. Some are believed by the vendor to offer certain benefits; you decide whether to stick with the standard types only or not. Beware: Some proprietary types have a name conflicting with a standard type; I’m looking at you Oracle DATE
.
The Java platform's handles the internal details of date-time differently than does the SQL standard or specific databases. The job of a JDBC driver is to mediate between these differences, to act as a bridge, translating the types and their actual implemented data values as needed. The java.sql.* package is that bridge.
Prior to Java 8, the JDBC spec defined 3 types for date-time work. The first two are hacks as before Version 8, Java lacked any classes to represent a date-only or time-only value.
So that answers your question regarding no "getDateTime" method in the ResultSet interface. That interface offers getter methods for the three bridging data types defined in JDBC:
getDate
for java.sql.DategetTime
for java.sql.TimegetTimestamp
for java.sql.TimestampNote that the first lack any concept of time zone or offset-from-UTC. The last one, java.sql.Timestamp
is always in UTC despite what its toString
method tells you.
You should avoid those poorly-designed JDBC classes listed above. They are supplanted by the java.time types.
java.sql.Date
, use LocalDate
. Suits SQL-standard DATE
type.java.sql.Time
, use LocalTime
. Suits SQL-standard TIME WITHOUT TIME ZONE
type.java.sql.Timestamp
, use Instant
. Suits SQL-standard TIMESTAMP WITH TIME ZONE
type. As of JDBC 4.2 and later, you can directly exchange java.time objects with your database. Use setObject
/getObject
methods.
Insert/update.
myPreparedStatement.setObject( … , instant ) ;
Retrieval.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
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).
If you want to see the moment of an Instant
as viewed through the wall-clock time used by the people of a particular region (a time zone) rather than as UTC, adjust by applying a ZoneId
to get a ZonedDateTime
object.
ZoneId zAuckland = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdtAuckland = instant.atZone( zAuckland ) ;
The resulting ZonedDateTime
object is the same moment, the same simultaneous point on the timeline. A new day dawns earlier to the east, so the date and time-of-day will differ. For example, a few minutes after midnight in New Zealand is still “yesterday” in UTC.
You can apply yet another time zone to either the Instant
or ZonedDateTime
to see the same simultaneous moment through yet another wall-clock time used by people in some other region.
ZoneId zMontréal = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdtMontréal = zdtAuckland.withZoneSameInstant( zMontréal ) ; // Or, for the same effect: instant.atZone( zMontréal )
So now we have three objects (instant
, zdtAuckland
, zMontréal
) all representing the same moment, same point on the timeline.
To get back to the code in Question about detecting the data-type of the databases: (a) not my field of expertise, (b) I would avoid this as mentioned up top, and (c) if you insist on this, beware that as of Java 8 and later, the java.sql.Types
class is outmoded. That class is now replaced by a proper Java Enum
of JDBCType
that implements the new interface SQLType
. See this Answer to a related Question.
This change is listed in JDBC Maintenance Release 4.2, sections 3 & 4. To quote:
Addition of the java.sql.JDBCType Enum
An Enum used to identify generic SQL Types, called JDBC Types. The intent is to use JDBCType in place of the constants defined in Types.java.
The enum has the same values as the old class, but now provides type-safety.
A note about syntax: In modern Java, you can use a switch
on an Enum
object. So no need to use cascading if-then statements as seen in your Question. The one catch is that the enum object’s name must be used unqualified when switching for some obscure technical reason, so you must do your switch
on TIMESTAMP_WITH_TIMEZONE
rather than the qualified JDBCType.TIMESTAMP_WITH_TIMEZONE
. Use a static import
statement.
So, all that is to say that I guess (I’ve not tried yet) you can do something like the following code example.
final int columnType = myResultSetMetaData.getColumnType( … ) ;
final JDBCType jdbcType = JDBCType.valueOf( columnType ) ;
switch( jdbcType ) {
case DATE : // FYI: Qualified type name `JDBCType.DATE` not allowed in a switch, because of an obscure technical issue. Use a `static import` statement.
…
break ;
case TIMESTAMP_WITH_TIMEZONE :
…
break ;
default :
…
break ;
}
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
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.
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes. This section left intact as history.
Prior to Java 8 (java.time.* package), the date-time classes bundled with java (java.util.Date & Calendar, java.text.SimpleDateFormat) are notoriously troublesome, confusing, and flawed.
A better practice is to take what your JDBC driver gives you and from that create Joda-Time objects, or in Java 8, java.time.* package. Eventually, you should see new JDBC drivers that automatically use the new java.time.* classes. Until then some methods have been added to classes such as java.sql.Timestamp to interject with java.time such as toInstant
and fromInstant
.
As for the latter part of the question, rendering a String… A formatter object should be used to generate a string value.
The old-fashioned way is with java.text.SimpleDateFormat. Not recommended.
Joda-Time provide various built-in formatters, and you may also define your own. But for writing logs or reports as you mentioned, the best choice may be ISO 8601 format. That format happens to be the default used by Joda-Time and java.time.
//java.sql.Timestamp timestamp = resultSet.getTimestamp(i);
// Or, fake it
// long m = DateTime.now().getMillis();
// java.sql.Timestamp timestamp = new java.sql.Timestamp( m );
//DateTime dateTimeUtc = new DateTime( timestamp.getTime(), DateTimeZone.UTC );
DateTime dateTimeUtc = new DateTime( DateTimeZone.UTC ); // Defaults to now, this moment.
// Convert as needed for presentation to user in local time zone.
DateTimeZone timeZone = DateTimeZone.forID("Europe/Paris");
DateTime dateTimeZoned = dateTimeUtc.toDateTime( timeZone );
Dump to console…
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeZoned: " + dateTimeZoned );
When run…
dateTimeUtc: 2014-01-16T22:48:46.840Z
dateTimeZoned: 2014-01-16T23:48:46.840+01:00
rs.last();
int rows = rs.getRow();
rs.beforeFirst();
If you use rs.next() you will move the cursor, than you should to move first() why don't check using first() directly?
public void fetchData(ResultSet res, JTable table) throws SQLException{
ResultSetMetaData metaData = res.getMetaData();
int fieldsCount = metaData.getColumnCount();
for (int i = 1; i <= fieldsCount; i++)
((DefaultTableModel) table.getModel()).addColumn(metaData.getColumnLabel(i));
if (!res.first())
JOptionPane.showMessageDialog(rootPane, "no data!");
else
do {
Vector<Object> v = new Vector<Object>();
for (int i = 1; i <= fieldsCount; i++)
v.addElement(res.getObject(i));
((DefaultTableModel) table.getModel()).addRow(v);
} while (res.next());
res.close();
}
theStatement=theConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet theResult=theStatement.executeQuery(query);
//Get the size of the data returned
theResult.last();
int size = theResult.getRow() * theResult.getMetaData().getColumnCount();
theResult.beforeFirst();
After establising the connection and executing the query try this:
ResultSet resultSet;
int columnCount = resultSet.getMetaData().getColumnCount();
System.out.println("column count : "+columnCount);
AFAIK you can simply use
iVal = rs.getInt("ID_PARENT");
if (rs.wasNull()) {
// do somthing interesting to handle this situation
}
even if it is NULL.
Try this method:
public static Dictionary<string, string> ParseIniDataWithSections(string[] iniData)
{
var dict = new Dictionary<string, string>();
var rows = iniData.Where(t =>
!String.IsNullOrEmpty(t.Trim()) && !t.StartsWith(";") && (t.Contains('[') || t.Contains('=')));
if (rows == null || rows.Count() == 0) return dict;
string section = "";
foreach (string row in rows)
{
string rw = row.TrimStart();
if (rw.StartsWith("["))
section = rw.TrimStart('[').TrimEnd(']');
else
{
int index = rw.IndexOf('=');
dict[section + "-" + rw.Substring(0, index).Trim()] = rw.Substring(index+1).Trim().Trim('"');
}
}
return dict;
}
It creates the dictionary where the key is "-". You can load it like this:
var dict = ParseIniDataWithSections(File.ReadAllLines(fileName));
SQL Workbench has such a feature.
After running a query, right click on the query results and choose "Copy Data As SQL > SQL Insert"
I am using XAMPP and came across the same error. I had done all those steps, added environmental variables path, copied the dll's every directory possible, to /php, /apache/bin, /system32, /syswow64, etc.. but still got this error.
Then after checking the apache error log, I noticed the issue with using brackets in path.
PHP: syntax error, unexpected '(' in C:\Program Files (other)\xampp\php\php.ini on line 707 0 server certificate does NOT include an ID which matches the server name
If you have installed the server in "Program Files (x86)" directory, the same error might occur due to the non-escaped brackets.
To fix this, open php.ini file and locate the line containing "include_path" and enclose the path with double quotes to fix this error.
include_path="C:\Program Files (other)\xampp\php\PEAR"
This error can get thrown if your data frame has sf
geometry columns.
The solution for me (openSUSE Leap 42.3, KDE) was to rename the folder ~/.gnupg
which apparently contained the cached keys and profiles.
After KDE logout/logon the ssh-add/agent is running again and the folder is created from scratch, but the old keys are all gone.
I didn't have success with the other approaches.
For OS X Yosemite and above, and Xcode 6+
Open Xcode > Window > Devices
Choose your device. You can see the installed application list and add a new one by hitting +
Your code was compiled with Java 8.
Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.
Hope this helps...
I know this is a question regarding the CSS.Tooltips library. However, for anyone else came here resulting from google search "tooltip for input box" like I did, here is the simplest way:
<input title="This is the text of the tooltip" value="44"/>
This is what worked for me:
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
try {
keyStore.load(instream, "password".toCharArray());
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, "password".toCharArray())
//.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
CloseableHttpClient httpclient = HttpClients.custom()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
.setSSLSocketFactory(sslsf)
.build();
try {
HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
This code is a modified version of http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java
Note that if you are using a Portable Class Library, HttpClient will not have PostAsJsonAsync method. To post a content as JSON using a Portable Class Library, you will have to do this:
HttpClient client = new HttpClient();
HttpContent contentPost = new StringContent(argsAsJson, Encoding.UTF8,
"application/json");
await client.PostAsync(new Uri(wsUrl), contentPost).ContinueWith(
(postTask) => postTask.Result.EnsureSuccessStatusCode());
How about using explode
:
$input = 'Posted On April 6th By Some Dude';
$result = explode(' By',$input);
return $result[0];
Advantages:
$result[1]
would return Some Dude
in this example)This works for me on Chrome 53. Haven't tested anywhere else:
function navigate(href, newTab) {
var a = document.createElement('a');
a.href = href;
if (newTab) {
a.setAttribute('target', '_blank');
}
a.click();
}
Sorry, no reputation to add this as a comment. So it goes as an complementary answer.
Depending on how often you will call clock_gettime()
, you should keep in mind that only some of the "clocks" are provided by Linux in the VDSO (i.e. do not require a syscall with all the overhead of one -- which only got worse when Linux added the defenses to protect against Spectre-like attacks).
While clock_gettime(CLOCK_MONOTONIC,...)
, clock_gettime(CLOCK_REALTIME,...)
, and gettimeofday()
are always going to be extremely fast (accelerated by the VDSO), this is not true for, e.g. CLOCK_MONOTONIC_RAW or any of the other POSIX clocks.
This can change with kernel version, and architecture.
Although most programs don't need to pay attention to this, there can be latency spikes in clocks accelerated by the VDSO: if you hit them right when the kernel is updating the shared memory area with the clock counters, it has to wait for the kernel to finish.
Here's the "proof" (GitHub, to keep bots away from kernel.org): https://github.com/torvalds/linux/commit/2aae950b21e4bc789d1fc6668faf67e8748300b7
The simplest way to do this is as follows:
save_results_to = '/Users/S/Desktop/Results/'
plt.savefig(save_results_to + 'image.png', dpi = 300)
The image is going to be saved in the save_results_to
directory with name image.png
A small snippet I use very often to create map from other maps:
static public <K, V> Map<K, V> merge(Map<K, V>... args) {
final Map<K, V> buffer = new HashMap<>();
for (Map m : args) {
buffer.putAll(m);
}
return buffer;
}
DateTime
doesn't have a default key as an input. The default key should be an input to the Column
function. Try this:
import datetime
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
created_date = Column(DateTime, default=datetime.datetime.utcnow)
You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.
declare @TableVar table
(
firstCol varchar(50) NOT NULL,
secondCol varchar(50) NOT NULL
)
BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO
INSERT INTO dbo.ExistingTable
(
firstCol,
secondCol
)
SELECT firstCol,
secondCol
FROM @TableVar
GO
I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.
Did you try this tip?
Or better still, use ipython, and call:
from IPython.Debugger import Tracer; debug_here = Tracer()
then you can just use
debug_here()
whenever you want to set a breakpoint
Can't you use JOIN like this one?
SELECT
a.x , b.y, b.z
FROM a
LEFT OUTER JOIN b ON b.v = a.v
(I don't know Oracle Syntax. So I wrote SQL syntax)
use chomp
or strip
functions from Ruby:
"abcd\n".chomp => "abcd"
"abcd\n".strip => "abcd"
We got this issue when a developer on Mac created a branch with a greater than ">" symbol in the branch name.
That caused problems in TeamCity, and on local Windows based computers running SourceTree. BitBucket let it through without any problems.
To resolve the user removed the branch and recreated it. Which was nice and easy.
In one script
#! /bin/sh
# Save git data
cp -r .git gitold
# Remove all empty git object files
find .git -type f -empty -delete -print
# Get current branch name
branchname=$(git branch --show-current)
# Get latest commit hash
commit=$(tail -2 .git/logs/refs/heads/jwt | awk '{ print $2 }' | tr -d '[:space:]')
# Set HEAD to this latest commit
git update-ref HEAD $commit
# Pull latest changes on the current branch (consifering remote is origin)
git pull origin $branchname
echo "If everything looks fine you remove the git backup running :\n\
$ rm -rf gitold\n\
Otherwise restore it with:\n\
$ rm -rf .git; mv gitold .git"
Serial sends data 8 bits at a time, that translates to 1 byte and 1 byte means 1 character.
You need to implement your own method that can read characters into a buffer until some sentinel is reached. The convention is to send a message like 12431\n
indicating one line.
So what you need to do is to implement a buffer that will store X number of characters and as soon as you reach that \n
, perform your operation on the line and proceed to read the next line into the buffer.
Note you will have to take care of buffer overflow cases i.e. when a line is received that is longer than your buffer etc...
EDIT
import serial
ser = serial.Serial(
port='COM5',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
print("connected to: " + ser.portstr)
#this will store the line
line = []
while True:
for c in ser.read():
line.append(c)
if c == '\n':
print("Line: " + ''.join(line))
line = []
break
ser.close()
If anyone came here to replace a character for the first occurrence in all lines (like myself), use this:
sed '/old/s/old/new/1' file
-bash-4.2$ cat file
123a456a789a
12a34a56
a12
-bash-4.2$ sed '/a/s/a/b/1' file
123b456a789a
12b34a56
b12
By changing 1 to 2 for example, you can replace all the second a's only instead.
Table is the obvious choice, but it returns an object of class table
which takes a few annoying steps to transform back into a data.frame
So, if you're OK using dplyr, you use the command tally
:
library(dplyr)
df = data.frame(sex=sample(c("M", "F"), 100000, replace=T), occupation=sample(c('Analyst', 'Student'), 100000, replace=T)
df %>% group_by_all() %>% tally()
# A tibble: 4 x 3
# Groups: sex [2]
sex occupation `n()`
<fct> <fct> <int>
1 F Analyst 25105
2 F Student 24933
3 M Analyst 24769
4 M Student 25193
Provided both machines are in the same workgroup, open cmd.exe
on the machine you want to connect to, type ipconfig
and note the IP at the IPv4 Address
line.
Then, on the machine you want to connect with, use http:// + the IP of the target machine
.
That should do it.
import pandas as pd
Date_Time = pd.to_datetime(df.NameOfColumn, unit='ms')
I've run into issues with Webclient.Downloadstring before. If you do, you can try this:
WebRequest request = WebRequest.Create("http://www.google.com");
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
"Stack Me 123 Heppa1 oeu".toCharArray()
?
Working plunk here.
To add the new input just once, use the following code:
$(document).ready(function()
{
$("#insertAfterBtn").one("click", function(e)
{
var r = $('<input/>', { type: "button", id: "field", value: "I'm a button" });
$("body").append(r);
});
});
[... source stripped here ...]
<body>
<button id="insertAfterBtn">Insert after</button>
</body>
[... source stripped here ...]
To make it work in w3 editor, copy/paste the code below into 'source code' section inside w3 editor and then hit 'Submit Code':
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<button id="insertAfterBtn">Insert only one button after</button>
<div class="myClass"></div>
<div id="myId"></div>
</body>
<script type="text/javascript">
$(document).ready(function()
{
// when dom is ready, call this method to add an input to 'body' tag.
addInputTo($("body"));
// when dom is ready, call this method to add an input to a div with class=myClass
addInputTo($(".myClass"));
// when dom is ready, call this method to add an input to a div with id=myId
addInputTo($("#myId"));
$("#insertAfterBtn").one("click", function(e)
{
var r = $('<input/>', { type: "button", id: "field", value: "I'm a button" });
$("body").append(r);
});
});
function addInputTo(container)
{
var inputToAdd = $("<input/>", { type: "button", id: "field", value: "I was added on page load" });
container.append(inputToAdd);
}
</script>
</html>
This is not an answer, really and I would have entered it as a comment had the question not been locked. This answers the question:
Why would you want it?
Assume you have a table with the sequence as the primary key and the sequence is generated by an insert trigger. If you wanted to have the sequence available for subsequent updates to the record, you need to have a way to extract that value.
In order to make sure you get the right one, you might want to wrap the INSERT and RonK's query in a transaction.
RonK's Query:
select MY_SEQ_NAME.currval from DUAL;
In the above scenario, RonK's caveat does not apply since the insert and update would happen in the same session.
getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.
#include <iostream>
using namespace std;
int main() {
string a, b, c;
cin >> a >> b >> c;
//now you have your three words
return 0;
}
I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.
dd()
dumps the variable and ends the execution of the script (1), so surrounding it with <pre>
tags will leave it broken. Just use good ol' var_dump()
(or print_r()
if you know it's an array)
Route::get('/', function()
{
echo '<pre>';
var_dump(User::all());
echo '</pre>';
//exit; <--if you want
});
Update:
I think you could format down what's shown by having Laravel convert the model object to array:
Route::get('/', function()
{
echo '<pre>';
$user = User::where('person_id', '=', 1);
var_dump($user->toArray()); // <---- or toJson()
echo '</pre>';
//exit; <--if you want
});
(1) For the record, this is the implementation of dd():
function dd()
{
array_map(function($x) { var_dump($x); }, func_get_args()); die;
}
Web application context, specified by the WebApplicationContext
interface, is a Spring application context for a web applications. It has all the properties of a regular Spring application context, given that the WebApplicationContext
interface extends the ApplicationContext
interface, and add a method for retrieving the standard Servlet API ServletContext
for the web application.
In addition to the standard Spring bean scopes singleton
and prototype
, there are three additional scopes available in a web application context:
request
- scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definitionsession
- scopes a single bean definition to the lifecycle of an HTTP Sessionapplication
- scopes a single bean definition to the lifecycle of a ServletContext
Arduino (c++) version based on Valentinos answer
unsigned long timeNow = 0;
unsigned long mSecInHour = 3600000;
unsigned long TimeNow =0;
int millisecs =0;
int seconds = 0;
byte minutes = 0;
byte hours = 0;
void setup() {
Serial.begin(9600);
Serial.println (""); // because arduino monitor gets confused with line 1
Serial.println ("hours:minutes:seconds.milliseconds:");
}
void loop() {
TimeNow = millis();
hours = TimeNow/mSecInHour;
minutes = (TimeNow-(hours*mSecInHour))/(mSecInHour/60);
seconds = (TimeNow-(hours*mSecInHour)-(minutes*(mSecInHour/60)))/1000;
millisecs = TimeNow-(hours*mSecInHour)-(minutes*(mSecInHour/60))- (seconds*1000);
Serial.print(hours);
Serial.print(":");
Serial.print(minutes);
Serial.print(":");
Serial.print(seconds);
Serial.print(".");
Serial.println(millisecs);
}
I wonder if you could write a custom rule for Fiddler to do what you want? IE uses no proxy, Firefox points to Fiddler, Fiddler uses custom rule to direct requests to the dev server...
Immediately following your <body> tag add something like this...
<style> body {opacity:0;}</style>
And for the very first thing in your <head> add something like...
<script>
window.onload = function() {setTimeout(function(){document.body.style.opacity="100";},500);};
</script>
As far as this being good practice or bad depends on your visitors, and the time the wait takes.
The question that is stil left open and I am not seeing any answers here is how to be sure the page has stabilized. For example if you are loading fonts the page may reflow a bit until all the fonts are loaded and displayed. I would like to know if there is an event that tells me the page is done rendering.
I found an alternative that works.
None of these answers worked for me (currently testing in FireFox 22.0), and after a lot of research I found, what seems to be, a much cleaner and straight forward solution.
Implemented solution:
function IsScrollbarAtBottom() {
var documentHeight = $(document).height();
var scrollDifference = $(window).height() + $(window).scrollTop();
return (documentHeight == scrollDifference);
}
Regards
On your own system, try
install.packages("foo", dependencies=...)
with the dependencies=
argument is documented as
dependencies: logical indicating to also install uninstalled packages
which these packages depend on/link to/import/suggest (and so
on recursively). Not used if ‘repos = NULL’. Can also be a
character vector, a subset of ‘c("Depends", "Imports",
"LinkingTo", "Suggests", "Enhances")’.
Only supported if ‘lib’ is of length one (or missing), so it
is unambiguous where to install the dependent packages. If
this is not the case it is ignored, with a warning.
The default, ‘NA’, means ‘c("Depends", "Imports",
"LinkingTo")’.
‘TRUE’ means (as from R 2.15.0) to use ‘c("Depends",
"Imports", "LinkingTo", "Suggests")’ for ‘pkgs’ and
‘c("Depends", "Imports", "LinkingTo")’ for added
dependencies: this installs all the packages needed to run
‘pkgs’, their examples, tests and vignettes (if the package
author specified them correctly).
so you probably want a value TRUE
.
In your package, list what is needed in Depends:
, see the
Writing R Extensions manual which is pretty clear on this.
N.B. - this question and answer relate to the 2000 version of SQL Server. In later versions, the restriction on INSERT INTO @table_variable ... EXEC ...
were lifted and so it doesn't apply for those later versions.
You'll have to switch to a temp table:
CREATE TABLE #tmp (code varchar(50), mount money)
DECLARE @q nvarchar(4000)
SET @q = 'SELECT coa_code, amount FROM T_Ledger_detail'
INSERT INTO #tmp (code, mount)
EXEC sp_executesql (@q)
SELECT * from #tmp
From the documentation:
A table variable behaves like a local variable. It has a well-defined scope, which is the function, stored procedure, or batch in which it is declared.
Within its scope, a table variable may be used like a regular table. It may be applied anywhere a table or table expression is used in SELECT, INSERT, UPDATE, and DELETE statements. However, table may not be used in the following statements:
INSERT INTO table_variable EXEC stored_procedure
SELECT select_list INTO table_variable statements.
I got it working for me in ReactJS using create-react-app
by putting this in my App.css
:
@-moz-document url-prefix() {
html,
body {
scrollbar-width: none;
}
}
Also, the body
element has overflow: auto
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
From changing tabs to spaces in eclipse:
Window » Preferences » Java » Code Style » Formatter » Edit » Indentation
(choose "Spaces Only")
For iOS 8
static NSString *_myCustomFontName;
+ (NSString *)myCustomFontName:(NSString*)fontName
{
if ( !_myCustomFontName )
{
NSArray *arr = [UIFont fontNamesForFamilyName:fontName];
// I know I only have one font in this family
if ( [arr count] > 0 )
_myCustomFontName = arr[0];
}
return _myCustomFontName;
}
In CSharp, If you create the method/function outline with it's Parms, then when you add the three forward slashes it will auto generate the summary and parms section.
So I put in:
public string myMethod(string sImput1, int iInput2)
{
}
I then put the three /// before it and Visual Studio's gave me this:
/// <summary>
///
/// </summary>
/// <param name="sImput1"></param>
/// <param name="iInput2"></param>
/// <returns></returns>
public string myMethod(string sImput1, int iInput2)
{
}
In addition to running
php -m
to get the list of installed php modules, you will probably find it helpful to get the list of the currently installed php packages in Ubuntu:
sudo dpkg --get-selections | grep -v deinstall | grep php
This is helpful since Ubuntu makes php modules available via packages.
You can then install the needed modules by selecting from the available Ubuntu php packages, which you can view by running:
sudo apt-cache search php | grep "^php5-"
Or, for Ubuntu 16.04 and higher:
sudo apt-cache search php | grep "^php7"
As you have mentioned, there is plenty of information available on the actual installation of the packages that you might require, so I won't go into detail about that here.
It is possible that an installed module has been disabled. In that case, it won't show up when running php -m
, but it will show up in the list of installed Ubuntu packages.
Modules can be enabled/disabled via the php5enmod
tool (phpenmod
on later distros) which is part of the php-common
package.
Ubuntu 12.04:
Enabled modules are symlinked in /etc/php5/conf.d
Ubuntu 12.04: (with PHP 5.4+)
To enable an installed module:
php5enmod <modulename>
To disable an installed module:
php5dismod <modulename>
Ubuntu 16.04 (php7) and higher:
To enable an installed module:
phpenmod <modulename>
To disable an installed module:
phpdismod <modulename>
Reload Apache
Remember to reload Apache2 after enabling/disabling:
service apache2 reload
In Bash (and ksh, zsh, dash, etc.), you can use parameter expansion with %
which will remove characters from the end of the string or #
which will remove characters from the beginning of the string. If you use a single one of those characters, the smallest matching string will be removed. If you double the character, the longest will be removed.
$ a='hello:world'
$ b=${a%:*}
$ echo "$b"
hello
$ a='hello:world:of:tomorrow'
$ echo "${a%:*}"
hello:world:of
$ echo "${a%%:*}"
hello
$ echo "${a#*:}"
world:of:tomorrow
$ echo "${a##*:}"
tomorrow
<head>_x000D_
_x000D_
_x000D_
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">_x000D_
<script src="//code.jquery.com/jquery-1.10.2.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>_x000D_
_x000D_
<script type="text/javascript">_x000D_
_x000D_
_x000D_
$(function() {_x000D_
$( "#dialog" ).dialog({_x000D_
autoOpen: false,_x000D_
show: {_x000D_
effect: "blind",_x000D_
duration: 1000_x000D_
},_x000D_
hide: {_x000D_
effect: "explode",_x000D_
duration: 1000_x000D_
}_x000D_
});_x000D_
_x000D_
$( "#opener" ).click(function() {_x000D_
$( "#dialog" ).dialog( "open" );_x000D_
});_x000D_
});_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<div id="dialog" title="Basic dialog">_x000D_
<p>This is an animated dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
</div>_x000D_
_x000D_
<button id="opener">Open Dialog</button>_x000D_
_x000D_
</body>
_x000D_
Apple hand three categories of certificates: Trusted
, Always Ask
and Blocked
. You'll encounter the issue if your certificate's type on the Blocked
and Always Ask
list. On Safari it show’s like:
And you can find the type of Always Ask
certificates on Settings > General > About > Certificate Trust Setting
There is the List of available trusted root certificates in iOS 11
uint
and ulong
are the unsigned versions of int
and long
. That means they can't be negative. Instead they have a larger maximum value.
Type Min Max CLS-compliant int -2,147,483,648 2,147,483,647 Yes uint 0 4,294,967,295 No long –9,223,372,036,854,775,808 9,223,372,036,854,775,807 Yes ulong 0 18,446,744,073,709,551,615 No
To write a literal unsigned int in your source code you can use the suffix u
or U
for example 123U
.
You should not use uint and ulong in your public interface if you wish to be CLS-Compliant.
Read the documentation for more information:
By the way, there is also short and ushort and byte and sbyte.
I know this is an old question, but if you encounter this problem in MVC 3 then you can decorate your ActionMethod
with [ValidateInput(false)]
and just switch off request validation for a single ActionMethod
, which is handy. And you don't need to make any changes to the web.config
file, so you can still use the .NET 4 request validation everywhere else.
e.g.
[ValidateInput(false)]
public ActionMethod Edit(int id, string value)
{
// Do your own checking of value since it could contain XSS stuff!
return View();
}
I did this on Mac OSX Sierra. I had Node 6.1 installed but Puppetter required Node 6.4. This is what I did:
brew upgrade node
brew unlink node
brew link --overwrite node@8
echo 'export PATH="/usr/local/opt/node@8/bin:$PATH"' >> ~/.bash_profile
And then open a new terminal window and run:
node -v
v8.11.2
The --overwrite is necessary to override conflicting files between node6 and node8
Tim Bray presented a concise step-by-step, stating that openConnection() does not establish an actual connection. Rather, an actual HTTP connection is not established until you call methods such as getInputStream() or getOutputStream().
http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection
Unfortunately, all of your assumptions seem correct, and I don't think there's a way to do this. In order to save battery life, the iPhone's location services are based on movement. If the phone sits in one spot, it's invisible to location services.
The CLLocationManager
will only call locationManager:didUpdateToLocation:fromLocation:
when the phone receives a location update, which only happens if one of the three location services (cell tower, gps, wifi) perceives a change.
A few other things that might help inform further solutions:
Starting & Stopping the services causes the didUpdateToLocation
delegate method to be called, but the newLocation
might have an old timestamp.
When running in the background, be aware that it may be difficult to get "full" LocationServices support approved by Apple. From what I've seen, they've specifically designed startMonitoringSignificantLocationChanges
as a low power alternative for apps that need background location support, and strongly encourage developers to use this unless the app absolutely needs it.
Good Luck!
UPDATE: These thoughts may be out of date by now. Looks as though people are having success with @wjans answer, above.
There are extensions of Word2Vec intended to solve the problem of comparing longer pieces of text like phrases or sentences. One of them is paragraph2vec or doc2vec.
"Distributed Representations of Sentences and Documents" http://cs.stanford.edu/~quocle/paragraph_vector.pdf
i.e. <div tooltip={{ obj.somePropertyThatMayChange }} ...></div>
I had an issue with dynamic tooltips that were not always updating with the view. For example, I was doing something like this:
<div ng-repeat="person in people">
<span data-toggle="tooltip" data-placement="top" title="{{ person.tooltip }}">
{{ person.name }}
</span>
</div>
And activating it as so:
$timeout(function() {
$(document).tooltip({ selector: '[data-toggle="tooltip"]'});
}, 1500)
However, as my people array would change my tooltips wouldn't always update. I tried every fix in this thread and others with no luck. The glitch seemed to only be happening around 5% of the time, and was nearly impossible to repeat.
Unfortunately, these tooltips are mission critical for my project, and showing an incorrect tooltip could be very bad.
Bootstrap was copying the value of the title
property to a new attribute, data-original-title
and removing the title
property (sometimes) when I would activate the toooltips. However, when my title={{ person.tooltip }}
would change the new value would not always be updated into the property data-original-title
. I tried deactivating the tooltips and reactivating them, destroying them, binding to this property directly... everything. However each of these either didn't work or created new issues; such as the title
and data-original-title
attributes both being removed and un-bound from my object.
Perhaps the most ugly code I've ever pushed, but it solved this small but substantial problem for me. I run this code each time the tooltip is update with new data:
$timeout(function() {
$('[data-toggle="tooltip"]').each(function(index) {
// sometimes the title is blank for no apparent reason. don't override in these cases.
if ($(this).attr("title").length > 0) {
$( this ).attr("data-original-title", $(this).attr("title"));
}
});
$timeout(function() {
// finally, activate the tooltips
$(document).tooltip({ selector: '[data-toggle="tooltip"]'});
}, 500);
}, 1500);
What's happening here in essence is:
title
s to be updated. title
property that is not empty (i.e. it has changed), copy it to the data-original-title
property so it will be picked up by Bootstrap's toolips.Hope this long answer helps someone who may have been struggling as I was.
Check this fiddle. You are going to need to take a look at using border-collapse and border-spacing. There are some quirks for IE (as usual). This is based on an answer to this question.
table.test td {
background-color: lime;
margin: 12px 12px 12px 12px;
padding: 12px 12px 12px 12px;
}
table.test {
border-collapse: separate;
border-spacing: 10px;
*border-collapse: expression('separate', cellSpacing='10px');
}
_x000D_
<table class="test">
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
</table>
_x000D_
Just to make this thread more complete i am adding my version of answer:
What i wanted to achieve: The surface view shouldn't be stretched, and it should cover the whole screen, Moreover, there was only a landscape mode in my app.
Solution:
The solution is an extremely small extension to F1sher's solution:
=> First step is to integrate F1sher's solution.
=> Now, there might arise a scenario in F1sher's solution when the surface view doesn't covers the whole screen, The solution is to make the surface view greater than the screen dimensions so that it covers the whole screen, for that:
size = getOptimalPreviewSize(mCamera.getParameters().getSupportedPreviewSizes(), screenWidth, screenHeight);
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(size.width, size.height);
mCamera.setParameters(parameters);
double screenRatio = (double) screenHeight / screenWidth;
double previewRatio = (double) size.height / size.width;
if (previewRatio > screenRatio) /*if preview ratio is greater than screen ratio then we will have to recalculate the surface height while keeping the surface width equal to the screen width*/
{
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
params1.addRule(RelativeLayout.CENTER_IN_PARENT);
flPreview.setLayoutParams(params1);
flPreview.setClipChildren(false);
LayoutParams surfaceParams = new LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
surfaceParams.gravity = Gravity.CENTER;
mPreview.setLayoutParams(surfaceParams);
}
else /*if preview ratio is smaller than screen ratio then we will have to recalculate the surface width while keeping the surface height equal to the screen height*/
{
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
params1.addRule(RelativeLayout.CENTER_IN_PARENT);
flPreview.setLayoutParams(params1);
flPreview.setClipChildren(false);
LayoutParams surfaceParams = new LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
surfaceParams.gravity = Gravity.CENTER;
mPreview.setLayoutParams(surfaceParams);
}
flPreview.addView(mPreview);
/* The TopMost layout used is the RelativeLayout, flPreview is the FrameLayout in which Surface View is added, mPreview is an instance of a class which extends SurfaceView */
Here's how I did it...
public static ElementDefinitionImpl[] RemoveElementDefAt(
ElementDefinition[] oldList,
int removeIndex
)
{
ElementDefinitionImpl[] newElementDefList = new ElementDefinitionImpl[ oldList.Length - 1 ];
int offset = 0;
for ( int index = 0; index < oldList.Length; index++ )
{
ElementDefinitionImpl elementDef = oldList[ index ] as ElementDefinitionImpl;
if ( index == removeIndex )
{
// This is the one we want to remove, so we won't copy it. But
// every subsequent elementDef will by shifted down by one.
offset = -1;
}
else
{
newElementDefList[ index + offset ] = elementDef;
}
}
return newElementDefList;
}
var myobject = new MyClass1("5678999", "text");
var dto = { MyClass1: myobject };
console.log(JSON.stringify(dto));
EDIT:
JSON.stringify
will stringify all 'properties' of your class. If you want to persist only some of them, you can specify them individually like this:
var dto = { MyClass1: {
property1: myobject.property1,
property2: myobject.property2
}};
Since the Length
property of System.String
is an Int32
, I would guess that that the maximum length would be 2,147,483,647 chars (max Int32
size). If it allowed longer you couldn't check the Length since that would fail.
The Path is the only thing you really have to worry about if you are really new to Java. You need to drag your image into the main project file, and it will show up at the very bottom of the list.
Then the file path is pretty straight forward. This code goes into the constructor for the class.
img = Toolkit.getDefaultToolkit().createImage("/home/ben/workspace/CS2/Background.jpg");
CS2 is the name of my project, and everything before that is leading to the workspace.
If you know a .NET language (C#/VB.NET etc) then checkout VST.NET. This framework allows you to create (unmanaged) VST 2.4 plugins in .NET. It comes with a framework that structures and simplifies the creation of a VST Plugin with support for Parameters, Programs and Persistence.
There are several samples that demonstrate the typical plugin scenarios. There's also documentation that explains how to get started and some of the concepts behind VST.NET.
Hope it helps. Marc Jacobi
String str = new String("SOME")
always create a new object on the heap
String str="SOME"
uses the String pool
Try this small example:
String s1 = new String("hello");
String s2 = "hello";
String s3 = "hello";
System.err.println(s1 == s2);
System.err.println(s2 == s3);
To avoid creating unnecesary objects on the heap use the second form.
In OpenGL you don't create objects, you just draw them. Once they are drawn, OpenGL no longer cares about what geometry you sent it.
glutSolidSphere
is just sending drawing commands to OpenGL. However there's nothing special in and about it. And since it's tied to GLUT I'd not use it. Instead, if you really need some sphere in your code, how about create if for yourself?
#define _USE_MATH_DEFINES
#include <GL/gl.h>
#include <GL/glu.h>
#include <vector>
#include <cmath>
// your framework of choice here
class SolidSphere
{
protected:
std::vector<GLfloat> vertices;
std::vector<GLfloat> normals;
std::vector<GLfloat> texcoords;
std::vector<GLushort> indices;
public:
SolidSphere(float radius, unsigned int rings, unsigned int sectors)
{
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
int r, s;
vertices.resize(rings * sectors * 3);
normals.resize(rings * sectors * 3);
texcoords.resize(rings * sectors * 2);
std::vector<GLfloat>::iterator v = vertices.begin();
std::vector<GLfloat>::iterator n = normals.begin();
std::vector<GLfloat>::iterator t = texcoords.begin();
for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
*t++ = s*S;
*t++ = r*R;
*v++ = x * radius;
*v++ = y * radius;
*v++ = z * radius;
*n++ = x;
*n++ = y;
*n++ = z;
}
indices.resize(rings * sectors * 4);
std::vector<GLushort>::iterator i = indices.begin();
for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
*i++ = r * sectors + s;
*i++ = r * sectors + (s+1);
*i++ = (r+1) * sectors + (s+1);
*i++ = (r+1) * sectors + s;
}
}
void draw(GLfloat x, GLfloat y, GLfloat z)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(x,y,z);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
glNormalPointer(GL_FLOAT, 0, &normals[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &texcoords[0]);
glDrawElements(GL_QUADS, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
glPopMatrix();
}
};
SolidSphere sphere(1, 12, 24);
void display()
{
int const win_width = …; // retrieve window dimensions from
int const win_height = …; // framework of choice here
float const win_aspect = (float)win_width / (float)win_height;
glViewport(0, 0, win_width, win_height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, win_aspect, 1, 10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
#ifdef DRAW_WIREFRAME
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
#endif
sphere.draw(0, 0, -5);
swapBuffers();
}
int main(int argc, char *argv[])
{
// initialize and register your framework of choice here
return 0;
}
You mean a DOS command such as below will do the job displaying installed .NET frameworks:
wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get version
The following may then be displayed:
Version
4.0.30319
WMIC is quite useful once you master using it, much easier than coding WMI in scripts depending on what you want to achieve.
You can use the --prefix
option:
mkdir -p ./install/here/node_modules
npm install --prefix ./install/here <package>
The package(s) will then be installed in ./install/here/node_modules
. The mkdir
is needed since npm might otherwise choose an already existing node_modules
directory higher up in the hierarchy. (See npm documentation on folders.)
http://dev.w3.org/webfonts/WOFF2/spec/#IMT
It seem that w3c switched it to font/woff2
I see there is some discussion about the proper mime type. In the link we read:
This document defines a top-level MIME type "font" ...
... the officially defined IANA subtypes such as "application/font-woff" ...
The members of the W3C WebFonts WG believe the use of "application" top-level type is not ideal.
and later
6.5. WOFF 2.0
Type name:
font
Subtype name:
woff2
So proposition from W3C differs from IANA.
We can see that it also differs from woff type: http://dev.w3.org/webfonts/WOFF/spec/#IMT where we read:
Type name:
application
Subtype name:
font-woff
which is
application/font-woff
Call: call invokes the function and allows you to pass arguments one by one
Apply: Apply invokes the function and allows you to pass arguments as an array
Bind: Bind returns a new function, allowing you to pass in a this array and any number of arguments.
var person1 = {firstName: 'Raju', lastName: 'king'};_x000D_
var person2 = {firstName: 'chandu', lastName: 'shekar'};_x000D_
_x000D_
function greet(greeting) {_x000D_
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);_x000D_
}_x000D_
function greet2(greeting) {_x000D_
console.log( 'Hello ' + this.firstName + ' ' + this.lastName);_x000D_
}_x000D_
_x000D_
_x000D_
greet.call(person1, 'Hello'); // Hello Raju king_x000D_
greet.call(person2, 'Hello'); // Hello chandu shekar_x000D_
_x000D_
_x000D_
_x000D_
greet.apply(person1, ['Hello']); // Hello Raju king_x000D_
greet.apply(person2, ['Hello']); // Hello chandu shekar_x000D_
_x000D_
var greetRaju = greet2.bind(person1);_x000D_
var greetChandu = greet2.bind(person2);_x000D_
_x000D_
greetRaju(); // Hello Raju king_x000D_
greetChandu(); // Hello chandu shekar
_x000D_
Just put context.SaveChanges()
after end of your foreach
(loop).
I think that ignoring the warning might be legitimate if you want to give the child class the ability to set or override a property that the parent constructor will use right away:
internal class Parent
{
public Parent()
{
Console.WriteLine("Parent ctor");
Console.WriteLine(Something);
}
protected virtual string Something { get; } = "Parent";
}
internal class Child : Parent
{
public Child()
{
Console.WriteLine("Child ctor");
Console.WriteLine(Something);
}
protected override string Something { get; } = "Child";
}
The risk here would be for the child class to set the property from its constructor in which case the change in the value would occur after the base class constructor has been called.
My use case is that I want the child class to provide a specific value or a utility class such as a converter and I don't want to have to call an initialization method on the base.
The output of the above when instantiating the child class is:
Parent ctor
Child
Child ctor
Child
The same error during global install (npm install -g mymodule
) for package with a non-existing script.
In package.json:
...
"bin": {
"module": "./bin/module"
},
...
But the ./bin/module
did not exist, as it was named modulejs
.
I think you can do that with:
window.location = "your_url";
For loading weights, you need to have a model first. It must be:
existingModel.save_weights('weightsfile.h5')
existingModel.load_weights('weightsfile.h5')
If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):
model.save_model('filename')
model = load_model('filename')
There's an extension that shows line endings. You can configure the color used, the characters that represent CRLF and LF and a boolean that turns it on and off.
Name: Line endings
Id: jhartell.vscode-line-endings
Description: Display line ending characters in vscode
Version: 0.1.0
Publisher: Johnny Härtell
Great answers and all are correct.I have provided simple example along with simple definition/meaning.
Meaning:
some_variable --? it's public anyone can see this.
_some_variable --? it's public anyone can see this but it's a convention to indicate private...warning no enforcement is done by Python.
__some_varaible --? Python replaces the variable name with _classname__some_varaible (AKA name mangling) and it reduces/hides it's visibility and be more like private variable.
Just to be honest here According to Python documentation
"“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python"
The example:
class A():
here="abc"
_here="_abc"
__here="__abc"
aObject=A()
print(aObject.here)
print(aObject._here)
# now if we try to print __here then it will fail because it's not public variable
#print(aObject.__here)
In Perl 5.14 (it works in now in Perl 5.13), we'll be able to just use keys on the hash reference
use v5.13.7;
foreach my $key (keys $ad_grp_ref) {
...
}
Here is the solution that worked for me
=IF(H14<>"",NOW(),"")
You have three options:
So, to get the 2º one you just need to install syslogd and OpenSSH from Cydia, restart required after to get syslogd going; now just open a ssh session to your device (via terminal or putty on windows), and type "tail -f /var/log/syslog". And there you go, wireless real time system log.
If you would like to try the 3º just search for "dup2" online, it's a system call.
To solve problems like this I'm using CSS - fastest & simplest way I think... Just modify it by your needs...
@media only screen and (max-width: 480px) {
#your_id {width:000px;height:000px;}
}
@media only screen and (min-width: 480px) and (max-width: 768px) {
#your_id {width:000px;height:000px;}
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
#your_id {width:000px;height:000px;}
}
@media only screen and (min-width: 959px) {
#your_id {width:000px;height:000px;}
}
Login to Server as Admin
Go To Security > Logins > New Login
Step 1:
Login Name : SomeName
Step 2:
Select SQL Server / Windows Authentication.
More Info on, what is the differences between sql server authentication and windows authentication..?
Choose Default DB and Language of your choice
Click OK
Try to connect with the New User Credentials, It will prompt you to change the password. Change and login
OR
Try with query :
USE [master] -- Default DB
GO
CREATE LOGIN [Username] WITH PASSWORD=N'123456', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=ON, CHECK_POLICY=ON
GO
--123456 is the Password And Username is Login User
ALTER LOGIN [Username] enable -- Enable or to Disable User
GO
Your collection class could have a method that returns a collection (a sublist) based on criteria passed in to define the filter. Build a new collection with the foreach loop and pass it out.
Or, have the method and loop modify the existing collection by setting a "filtered" or "active" flag (property). This one could work but could also cause poblems in multithreaded code. If other objects deped on the contents of the collection this is either good or bad depending of how you use the data.
In the current version of RestSharp (105.2.3.0) you can add a JSON object to the request body with:
request.AddJsonBody(new { A = "foo", B = "bar" });
This method sets content type to application/json and serializes the object to a JSON string.
I use GNU Cash and it uses Open Financial Exchange (ofx) http://www.ofx.net/ to download complete transactions and balances from each account of each bank.
Let me emphasize that again, you get a huge list of transactions with OFX into the GNU Cash. Depending on the account type these transactions can be very detailed description of your transactions (purchases+paycheques), investments, interests, etc.
In my case, even though I have Chase debit card I had to choose Chase Credit to make it work. But Chase wants you to enable this OFX feature by logging into your online banking and enable Quicken/MS Money/etc. somewhere in your profile or preferences. Don't call Chase customer support because they know nothing about it.
This service for OFX and GNU Cash is free. I have heard that they charge $10 a month for other platforms.
OFX can download transactions from 348 banks so far. http://www.ofxhome.com/index.php/home/directory
Actualy, OFX also supports making bill payments, stop a check, intrabank and interbank transfers etc. It is quite extensive. See it here: http://ofx.net/AboutOFX/ServicesSupported.aspx
int[] nums = new int[100];
int sum = 0;
// Fill it with numbers using a for-loop for (int i = 0; i < nums.length; i++)
{
nums[i] = i + 1;
sum += n;
}
System.out.println(sum);
Try this
<input type="button" onClick="return click();">button text</input>
I solved this problem by set my go env GO111MODULE to off
go env -w GO111MODULE=off
I had the same problem , first I couldn't find those dlls
in the list of .NET components
. but later I figured it out that the solution is :
1- first I changed target framework
from .NET framework 4 client profile
to .NET framework 4
.
2- then scroll down the list of .NET components
, pass first list of system.web.
.. , scroll down , and find the second list of system.web.
.. at the bottom , they're there .
I hope this could help others
For me it worked as I just copied a .nuget folder from a working solution to the existing one, and referenced it's content!
After trying the simple pip install
route for eyeD3, pytaglib, and ID3 modules recommended here, I found this fourth option was the only one to work. The rest had import errors with missing dependencies in C++ or something magic or some other library that pip
missed. So go with this one for basic reading of ID3 tags (all versions):
https://pypi.python.org/pypi/tinytag/0.18.0
from tinytag import TinyTag
tag = TinyTag.get('/some/music.mp3')
List of possible attributes you can get with TinyTag:
tag.album # album as string
tag.albumartist # album artist as string
tag.artist # artist name as string
tag.audio_offset # number of bytes before audio data begins
tag.bitrate # bitrate in kBits/s
tag.disc # disc number
tag.disc_total # the total number of discs
tag.duration # duration of the song in seconds
tag.filesize # file size in bytes
tag.genre # genre as string
tag.samplerate # samples per second
tag.title # title of the song
tag.track # track number as string
tag.track_total # total number of tracks as string
tag.year # year or data as string
It was tiny and self-contained, as advertised.
Surely you just need:
double seconds = milliseconds / 1000.0;
There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0
(as a double
literal) forces. (I'm assuming your milliseconds
value is an integer of some form.)
Note that as usual with double
, you may not be able to represent the result exactly. Consider using BigDecimal
if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double
is probably appropriate, but...)
If you really need to do this, use reverse proxy.
For example, with nginx as reverse proxy
server {
listen api.mydomain.com:80;
server_name api.mydomain.com;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
Since you are saying the webservice is not live right now, you can do it by creating mockservices which will create the sample response format.
I think project size and the number of developers involved are big factors in this. I'm far above this over my career but I've worked alone all that time so there's no loss to working with other programmers.
The only way is to go an underlying level to the JVM.
df.col._jc.toString().encode('utf8')
This is also how it is converted to a str
in the pyspark code itself.
From pyspark/sql/column.py:
def __repr__(self):
return 'Column<%s>' % self._jc.toString().encode('utf8')
IntelliJ IDEA detects errors and warnings in the current file on the fly (unless Power Save Mode is activated in the File
menu).
Errors in other files and in the project view will be shown after Build
| Make
and listed in the Messages tool window.
For Bazel users: Project errors will show on Bazel Problems tool window after running Compile Project
(Ctrl/Cmd+F9)
To navigate between errors use Navigate
| Next Highlighted Error
(F2) / Previous Highlighted Error
(Shift+F2).
Error Stripe Mark color can be changed here:
I had same problem in VB.NET 2013 with Office 2007, and this solved it:
VS 2013 VB.NET Project > Props > Refs > Microsoft Word 12.0 Object Lib > Embed Interop Types: change True to False
Only you want to set default value parameter. This calling third overloading method.
dt.Columns.Add("MyRow", type(System.Int32),0);
I made a tool using Python with some bash to trigger a Jenkins build. Basically you have to collect these two values from post-commit when a commit hits the SVN server:
REPOS="$1"
REV="$2"
Then you use "svnlook dirs-changed $1 -r $2" to get the path which is has just committed. Then from that you can check which repository you want to build. Imagine you have hundred of thousand of projects. You can't check the whole repository, right?
You can check out my script from GitHub.
Without Plugin, we can do this; bootstrap multi-level responsive menu for mobile phone with slide toggle for mobile:
$('[data-toggle="slide-collapse"]').on('click', function() {_x000D_
$navMenuCont = $($(this).data('target'));_x000D_
$navMenuCont.animate({_x000D_
'width': 'toggle'_x000D_
}, 350);_x000D_
$(".menu-overlay").fadeIn(500);_x000D_
});_x000D_
_x000D_
$(".menu-overlay").click(function(event) {_x000D_
$(".navbar-toggle").trigger("click");_x000D_
$(".menu-overlay").fadeOut(500);_x000D_
});_x000D_
_x000D_
// if ($(window).width() >= 767) {_x000D_
// $('ul.nav li.dropdown').hover(function() {_x000D_
// $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
// }, function() {_x000D_
// $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
// });_x000D_
_x000D_
// $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
// $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
// }, function() {_x000D_
// $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
// });_x000D_
_x000D_
_x000D_
// $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
// event.preventDefault();_x000D_
// event.stopPropagation();_x000D_
// $(this).parent().siblings().removeClass('open');_x000D_
// $(this).parent().toggleClass('open');_x000D_
// $('b', this).toggleClass("caret caret-up");_x000D_
// });_x000D_
// }_x000D_
_x000D_
// $(window).resize(function() {_x000D_
// if( $(this).width() >= 767) {_x000D_
// $('ul.nav li.dropdown').hover(function() {_x000D_
// $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
// }, function() {_x000D_
// $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
// });_x000D_
// }_x000D_
// });_x000D_
_x000D_
var windowWidth = $(window).width();_x000D_
if (windowWidth > 767) {_x000D_
// $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
// event.preventDefault();_x000D_
// event.stopPropagation();_x000D_
// $(this).parent().siblings().removeClass('open');_x000D_
// $(this).parent().toggleClass('open');_x000D_
// $('b', this).toggleClass("caret caret-up");_x000D_
// });_x000D_
_x000D_
$('ul.nav li.dropdown').hover(function() {_x000D_
$(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
}, function() {_x000D_
$(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
});_x000D_
_x000D_
$('ul.nav li.dropdown-submenu').hover(function() {_x000D_
$(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
}, function() {_x000D_
$(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
});_x000D_
_x000D_
_x000D_
$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
event.preventDefault();_x000D_
event.stopPropagation();_x000D_
$(this).parent().siblings().removeClass('open');_x000D_
$(this).parent().toggleClass('open');_x000D_
// $('b', this).toggleClass("caret caret-up");_x000D_
});_x000D_
}_x000D_
if (windowWidth < 767) {_x000D_
$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
event.preventDefault();_x000D_
event.stopPropagation();_x000D_
$(this).parent().siblings().removeClass('open');_x000D_
$(this).parent().toggleClass('open');_x000D_
// $('b', this).toggleClass("caret caret-up");_x000D_
});_x000D_
}_x000D_
_x000D_
// $('.dropdown a').append('Some text');
_x000D_
@media only screen and (max-width: 767px) {_x000D_
#slide-navbar-collapse {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 15px;_x000D_
z-index: 999999;_x000D_
width: 280px;_x000D_
height: 100%;_x000D_
background-color: #f9f9f9;_x000D_
overflow: auto;_x000D_
bottom: 0;_x000D_
max-height: inherit;_x000D_
}_x000D_
.menu-overlay {_x000D_
display: none;_x000D_
background-color: #000;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
opacity: 0.5;_x000D_
filter: alpha(opacity=50);_x000D_
/* IE7 & 8 */_x000D_
position: fixed;_x000D_
right: 0;_x000D_
top: 0;_x000D_
z-index: 49;_x000D_
}_x000D_
.navbar-fixed-top {_x000D_
position: initial !important;_x000D_
}_x000D_
.navbar-nav .open .dropdown-menu {_x000D_
background-color: #ffffff;_x000D_
}_x000D_
ul.nav.navbar-nav li {_x000D_
border-bottom: 1px solid #eee;_x000D_
}_x000D_
.navbar-nav .open .dropdown-menu .dropdown-header,_x000D_
.navbar-nav .open .dropdown-menu>li>a {_x000D_
padding: 10px 20px 10px 15px;_x000D_
}_x000D_
}_x000D_
_x000D_
.dropdown-submenu {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu .dropdown-menu {_x000D_
top: 0;_x000D_
left: 100%;_x000D_
margin-top: -1px;_x000D_
}_x000D_
_x000D_
li.dropdown a {_x000D_
display: block;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
content: "\f107";_x000D_
font-family: FontAwesome;_x000D_
position: absolute;_x000D_
right: 6px;_x000D_
top: 5px;_x000D_
font-size: 15px;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a:before {_x000D_
content: "\f107";_x000D_
font-family: FontAwesome;_x000D_
position: absolute;_x000D_
right: 6px;_x000D_
top: 10px;_x000D_
font-size: 15px;_x000D_
}_x000D_
_x000D_
ul.dropdown-menu li {_x000D_
border-bottom: 1px solid #eee;_x000D_
}_x000D_
_x000D_
.dropdown-menu {_x000D_
padding: 0px;_x000D_
margin: 0px;_x000D_
border: none !important;_x000D_
}_x000D_
_x000D_
li.dropdown.open {_x000D_
border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu.open {_x000D_
border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a {_x000D_
font-weight: bold !important;_x000D_
}_x000D_
_x000D_
li.dropdown>a {_x000D_
font-weight: bold !important;_x000D_
}_x000D_
_x000D_
.navbar-default .navbar-nav>li>a {_x000D_
font-weight: bold !important;_x000D_
padding: 10px 20px 10px 15px;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
content: "\f107";_x000D_
font-family: FontAwesome;_x000D_
position: absolute;_x000D_
right: 6px;_x000D_
top: 9px;_x000D_
font-size: 15px;_x000D_
}_x000D_
_x000D_
@media (min-width: 767px) {_x000D_
li.dropdown-submenu>a {_x000D_
padding: 10px 20px 10px 15px;_x000D_
}_x000D_
li.dropdown>a:before {_x000D_
content: "\f107";_x000D_
font-family: FontAwesome;_x000D_
position: absolute;_x000D_
right: 3px;_x000D_
top: 12px;_x000D_
font-size: 15px;_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<nav class="navbar navbar-default navbar-fixed-top">_x000D_
<div class="container-fluid">_x000D_
<!-- Brand and toggle get grouped for better mobile display -->_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="slide-collapse" data-target="#slide-navbar-collapse" aria-expanded="false">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Brand</a>_x000D_
</div>_x000D_
<!-- Collect the nav links, forms, and other content for toggling -->_x000D_
<div class="collapse navbar-collapse" id="slide-navbar-collapse">_x000D_
<ul class="nav navbar-nav">_x000D_
<li><a href="#">Link <span class="sr-only">(current)</span></a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#">Action</a></li>_x000D_
<li><a href="#">Another action</a></li>_x000D_
<li><a href="#">Something else here</a></li>_x000D_
<li><a href="#">Separated link</a></li>_x000D_
<li><a href="#">One more separated link</a></li>_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" data-toggle="dropdown">SubMenu 1</span></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" data-toggle="dropdown">SubMenu 2</span></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
<li><a href="#">3rd level dropdown</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Link</a></li>_x000D_
</ul>_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="#">Link</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#">Action</a></li>_x000D_
<li><a href="#">Another action</a></li>_x000D_
<li><a href="#">Something else here</a></li>_x000D_
<li><a href="#">Separated link</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<!-- /.navbar-collapse -->_x000D_
</div>_x000D_
<!-- /.container-fluid -->_x000D_
</nav>_x000D_
<div class="menu-overlay"></div>_x000D_
<div class="col-md-12">_x000D_
<h1>Resize the window to see the result</h1>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
</p>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
</p>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
</p>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
</p>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
</p>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
The problem you are reporting seems to me caused by the following:
In such situation Eclipse cannot recognize the proper compiler to use.
class of my button is "input-addon btn btn-default fileinput-exists"
below code helped me
document.querySelector('.input-addon.btn.btn-default.fileinput-exists').click();
but I want to click second button, I have two buttons in my screen so I used querySelectorAll
var elem = document.querySelectorAll('.input-addon.btn.btn-default.fileinput-exists');
elem[1].click();
here elem[1] is the second button object that I want to click.
Without your seeing your data (you can use the output of dput(head(survey))
to show us) this is a shot in the dark:
survey <- data.frame(date=c("2012/07/26","2012/07/25"),tx_start=c("2012/01/01","2012/01/01"))
survey$date_diff <- as.Date(as.character(survey$date), format="%Y/%m/%d")-
as.Date(as.character(survey$tx_start), format="%Y/%m/%d")
survey
date tx_start date_diff
1 2012/07/26 2012/01/01 207 days
2 2012/07/25 2012/01/01 206 days
The following works with Java 7/8, secure urls, and shows how to add a cookie to your request as well. Note this is mostly a direct copy of this other great answer on this page, but added the cookie example, and clarification in that it works with secure urls as well ;-)
If you need to connect to a server with an invalid certificate or self signed certificate, this will throw security errors unless you import the certificate. If you need this functionality, you could consider the approach detailed in this answer to this related question on StackOverflow.
String result = getUrlAsString("https://www.google.com");
System.out.println(result);
outputs
<!doctype html><html itemscope="" .... etc
import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static String getUrlAsString(String url)
{
try
{
URL urlObj = new URL(url);
URLConnection con = urlObj.openConnection();
con.setDoOutput(true); // we want the response
con.setRequestProperty("Cookie", "myCookie=test123");
con.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
String newLine = System.getProperty("line.separator");
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine + newLine);
}
in.close();
return response.toString();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
If I understood your question, try something like this
declare @dd varchar(50)='Jan 30 2013 12:00:00:000AM'
Select convert(varchar,(CONVERT(date,@dd,103)),103)
Update
SELECT
PREFIX_TableName.ColumnName1 AS Name,
PREFIX_TableName.ColumnName2 AS E-Mail,
convert(varchar,(CONVERT(date,PREFIX_TableName.ColumnName3,103)),103) AS TransactionDate,
PREFIX_TableName.ColumnName4 AS OrderNumber
You need to begin the session at the top of a page or before you call session code
session_start();
Use DATE_FORMAT()
SELECT
DATE_FORMAT(NOW(), '%d %m %Y') AS your_date;
It didn't work for me when I've tried to add the reference from the .NET Assemblies tab. It worked, though, when I've added the reference with BROWSE to C:\Windows\Microsoft.NET\Framework\v4.0.30319
The key checks for FAST REFRESH includes the following:
1) An Oracle materialized view log must be present for each base table.
2) The RowIDs of all the base tables must appear in the SELECT list of the MVIEW query definition.
3) If there are outer joins, unique constraints must be placed on the join columns of the inner table.
No 3 is easy to miss and worth highlighting here
In jQuery I mostly use:
$("#element").trigger("change");
extension UIImage {
func fixImageOrientation() -> UIImage {
UIGraphicsBeginImageContext(self.size)
self.draw(at: .zero)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage ?? self
}
}
Call it: imageView.image?.fixImageOrientation()
or UIImage(named: "someImage").fixImageOrientation()
Good luck all!
To add class to a element
document.querySelector(elem).className+=' first second third';
UPDATE:
Remove a class
document.querySelector(elem).className=document.querySelector(elem).className.split(class_to_be_removed).join(" ");
You're missing a FROM and you need to give the subquery an alias.
SELECT COUNT(*) FROM
(
SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
FROM dbo.Table_A AS a
INNER JOIN dbo.Table_B AS b
ON a.a_id = b.a_id
) AS subquery;
I know this is an old question, but gracchus's solution doesn't work if file names contain spaces. VonC's solution to file names with spaces is to not remove them utilizing --ignore-unmatch
, then remove them manually, but this will not work well if there are a lot.
Here is a solution that utilizes bash arrays to capture all files.
# Build bash array of the file names
while read -r file; do
rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)
git rm –-cached "${rmlist[@]}"
git commit -m 'ignore update'
If you want this without loops or jquery you could use the following This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.
// Please note that querySelectorAll will return a match for _x000D_
// for the term...if there is more than one then you will _x000D_
// have to loop through the returned object_x000D_
var selectAnimal = function() {_x000D_
var animals = document.getElementById('animal');_x000D_
if (animals) {_x000D_
var x = animals.querySelectorAll('option[value="frog"]');_x000D_
if (x.length === 1) {_x000D_
console.log(x[0].index);_x000D_
animals.selectedIndex = x[0].index;_x000D_
}_x000D_
}_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>Test without loop or jquery</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<label>Animal to select_x000D_
<select id='animal'>_x000D_
<option value='nothing'></option>_x000D_
<option value='dog'>dog</option>_x000D_
<option value='cat'>cat</option>_x000D_
<option value='mouse'>mouse</option>_x000D_
<option value='rat'>rat</option>_x000D_
<option value='frog'>frog</option>_x000D_
<option value='horse'>horse</option>_x000D_
</select>_x000D_
</label>_x000D_
<button onclick="selectAnimal()">Click to select animal</button>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
document.getElementById('Animal').querySelectorAll('option[value="searchterm"]'); in the index object you can now do the following: x[0].index
You can use the command split for this task. For example this command entered into the command prompt
split YourLogFile.txt -b 500m
creates several files with a size of 500 MByte each. This will take several minutes for a file of your size. You can rename the output files (by default called "xaa", "xab",... and so on) to *.txt to open it in the editor of your choice.
Make sure to check the help file for the command. You can also split the log file by number of lines or change the name of your output files.
(tested on Windows 7 64 bit)
You need to select the entire column where you have the dates, so click the "text to columns" button, and select delimited > uncheck all the boxes and go until you click the button finish.
This will make the cell format and then the values will be readed as date.
Hope it will helped.
Simply i have import in appmodule.ts
import { HttpClientModule } from '@angular/common/http';
imports: [
BrowserModule,
FormsModule,
HttpClientModule <<<this
],
My problem resolved
You could use strftime
, but struct tm
doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.
struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%S", &tm);
Arrays are better in performance. ArrayList provides additional functionality such as "remove" at the cost of performance.
i have wasted a lot of time to solve it , But the only solution i find is to rename your word press plugins folder and active theme , and your wp-admin will be visible , so then you can change and check for suspected plugin or theme.
Here is an alternative way to do that.
const conditionsArray = [
condition1,
condition2,
condition3,
]
if (conditionsArray.indexOf(false) === -1) {
"do somthing"
}
Or ES6
if (!conditionsArray.includes(false)) {
"do somthing"
}
Add to the list:
In Emacs mode, hit Esc, followed by R, will delete the whole line.
I don't know why, just happens to find it. Maybe it's not used for delete line but happens to have the same effect. If someone knows, please tell me, thanks :)
Works in Bash, but won't work in Fish.
The nuget commandline tool does not come with the vsix file, it's a separate download
I am giving one exapmle to undersand when do we use @Queryparam
and @pathparam
For example I am taking one resouce is carResource
class
If you want to make the inputs of your resouce method manadatory then use the param type as @pathaparam
, if the inputs of your resource method should be optional then keep that param type as @QueryParam
param
@Path("/car")
class CarResource
{
@Get
@produces("text/plain")
@Path("/search/{carmodel}")
public String getCarSearch(@PathParam("carmodel")String model,@QueryParam("carcolor")String color) {
//logic for getting cars based on carmodel and color
-----
return cars
}
}
For this resouce pass the request
req uri ://address:2020/carWeb/car/search/swift?carcolor=red
If you give req like this the resouce will gives the based car model and color
req uri://address:2020/carWeb/car/search/swift
If you give req like this the resoce method will display only swift model based car
req://address:2020/carWeb/car/search?carcolor=red
If you give like this we will get ResourceNotFound exception because in the car resouce class I declared carmodel as @pathPram
that is you must and should give the carmodel as reQ uri otherwise it will not pass the req to resouce but if you don't pass the color also it will pass the req to resource why because the color is @quetyParam
it is optional in req.
To compare one object to another, I combine a for in loop (used to loop through objects) and some(). You do not have to worry about an array going out of bounds etc, so that saves some code. Documentation on .some can be found here
var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];
var objectsFound = [];
for(let objectNumber in productList){
var currentId = productList[objectNumber].id;
if (theDatabaseList.some(obj => obj.id === currentId)) {
// Do what you need to do with the matching value here
objectsFound.push(currentId);
}
}
console.log(objectsFound);
An alternative way I compare one object to another is to use a nested for loop with Object.keys().length to get the amount of objects in the array. Code below:
var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];
var objectsFound = [];
for(var i = 0; i < Object.keys(productList).length; i++){
for(var j = 0; j < Object.keys(theDatabaseList).length; j++){
if(productList[i].id === theDatabaseList[j].id){
objectsFound.push(productList[i].id);
}
}
}
console.log(objectsFound);
To answer your exact question, if are just searching for a value in an object, you can use a single for in loop.
var vendors = [
{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
}
];
for(var ojectNumbers in vendors){
if(vendors[ojectNumbers].Name === 'Magenic'){
console.log('object contains Magenic');
}
}
From cmd (Windows):
C\Users\You> `vim foo.txt`
Now in Vim, enter command mode by typing: ":" (i.e. Shift + ;)
:tabedit $HOME/.vimrc
I wrote and released a Windows application that specifically solves the problem of comparing and merging XML files.
Project: Merge can perform two and three way comparisons and merges of any XML file (where two of the files are considered to be independent revisions of a common base file). You can instruct it to identify elements within the input files by attribute values, or the content of child elements, among other things.
It is fully controllable via the command line and can also generate text reports containing the differences between the files.
One important thing to note, if you have ANSI on sql_mode:
Equivalent to REAL_AS_FLOAT, PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, and (as of MySQL 5.7.5) ONLY_FULL_GROUP_BY.
See https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_ansi
You started with ManyToOne mapping , then you put OneToMany mapping as well for BiDirectional way. Then at OneToMany side (usually your parent table/class), you have to mention "mappedBy" (mapping is done by and in child table/class), so hibernate will not create EXTRA mapping table in DB (like TableName = parent_child).
loc: only work on index
iloc: work on position
at: get scalar values. It's a very fast loc
iat: Get scalar values. It's a very fast iloc
Also,
at
andiat
are meant to access a scalar, that is, a single element in the dataframe, whileloc
andiloc
are ments to access several elements at the same time, potentially to perform vectorized operations.
http://pyciencia.blogspot.com/2015/05/obtener-y-filtrar-datos-de-un-dataframe.html
Ok, it's not HTTPClient but if u can use it, WebClient is quite easy:
using (var client = new System.Net.WebClient())
{
client.Headers.Add("Accept", "application/json");
client.Headers.Add("Content-Type", "application/json; charset=utf-8");
client.DownloadString(...);
}
Five options:
Use the free jsonutils web tool without installing anything.
If you have Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class.
Use the free jsonclassgenerator.exe
The web tool app.quicktype.io does not require installing anything.
The web tool json2csharp also does not require installing anything.
Pros and Cons:
jsonclassgenerator converts to PascalCase but the others do not.
app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.
I just successfully installed a package for excel. After installing the python 3.6
, you have to download the desired package, then install.
For eg,
python.exe -m pip download openpyxl==2.1.4
python.exe -m pip install openpyxl==2.1.4
From best to worse:
Option 1 (C99 and newer)
#include <stdbool.h>
Option 2
typedef enum { false, true } bool;
Option 3
typedef int bool;
enum { false, true };
Option 4
typedef int bool;
#define true 1
#define false 0
#Explanation
If you are undecided, go with #1!
Try mydatagrid.Items.Refresh()
If you are sure you haven't messed the jar, then please clean the project and perform mvn clean install
. This should solve the problem.
When opening a CSV, you get the text import wizard. At the last step of the wizard, you should be able to import the specific column as text, thereby retaining the '00' prefix. After that you can then format the cell any way that you want.
I tried with with Excel 2007 and it appeared to work.
Yes, but it also means hash(b) == hash(x)
, so equality of the items isn't enough to make them the same.
You can use wait
:
some_command &
P1=$!
other_command &
P2=$!
wait $P1 $P2
It assigns the background program PIDs to variables ($!
is the last launched process' PID), then the wait
command waits for them. It is nice because if you kill the script, it kills the processes too!
besides to titleForHeaderInSection, you can simply change view of header, footer. check my comment here: Change UITable section backgroundColor without loosing section Title
Actually, C# does not really run in a virtual machine like Java does. IL is compiled into assembly language, which is entirely native code and runs at the same speed as native code. You can pre-JIT an .NET application which entirely removes the JIT cost and then you are running entirely native code.
The slowdown with .NET will come not because .NET code is slower, but because it does a lot more behind the scenes to do things like garbage collect, check references, store complete stack frames, etc. This can be quite powerful and helpful when building applications, but also comes at a cost. Note that you could do all these things in a C++ program as well (much of the core .NET functionality is actually .NET code which you can view in ROTOR). However, if you hand wrote the same functionality you would probably end up with a much slower program since the .NET runtime has been optimized and finely tuned.
That said, one of the strengths of managed code is that it can be fully verifiable, ie. you can verify that the code will never access another processes's memory or do unsage things before you execute it. Microsoft has a research prototype of a fully managed operating system that has suprisingly shown that a 100% managed environment can actually perform significantly faster than any modern operating system by taking advantage of this verification to turn off security features that are no longer needed by managed programs (we are talking like 10x in some cases). SE radio has a great episode talking about this project.
The csv file might contain very huge fields, therefore increase the field_size_limit
:
import sys
import csv
csv.field_size_limit(sys.maxsize)
sys.maxsize
works for Python 2.x and 3.x. sys.maxint
would only work with Python 2.x (SO: what-is-sys-maxint-in-python-3)
As Geoff pointed out, the code above might result in the following error: OverflowError: Python int too large to convert to C long
.
To circumvent this, you could use the following quick and dirty code (which should work on every system with Python 2 and Python 3):
import sys
import csv
maxInt = sys.maxsize
while True:
# decrease the maxInt value by factor 10
# as long as the OverflowError occurs.
try:
csv.field_size_limit(maxInt)
break
except OverflowError:
maxInt = int(maxInt/10)
Adding another point of view to above mentioned solutions.
Implicit Wait: When created, is alive until the WebDriver object dies. And is like common for all operations.
Whereas,
Explicit wait, can be declared for a particular operation depending upon the webElement behavior. It has the benefit of customizing the polling time and satisfaction of the condition.
For example, we declared implicit Wait of 10 secs but an element takes more than that, say 20 seconds and sometimes may appears on 5 secs, so in this scenario, Explicit wait is declared.
The correct answer to that is the method lists
, it's very simple like this:
$test=test::select('id')->where('id' ,'>' ,0)->lists('id');
Regards!
To my knowledge, Ejabberd (http://www.ejabberd.im/) is the parent, this is XMPP server which provide quite good features of open source, Whatsapp uses some modified version of this, facebook messaging also uses a modified version of this. Some more chat applications likes Samsung's ChatOn, Nimbuzz messenger all use ejabberd based ones and Erlang solutions also have modified version of this ejabberd which they claim to be highly scalable and well tested with more performance improvements and renamed as MongooseIM.
Ejabberd is the server which has most of the featured implemented when compared to other. Since it is build in Erlang it is highly scalable horizontally.
List<Object> nameOfList = new ArrayList<Object>();
You need to import List
and ArrayList
.
Key/index : A key is an aspect of a LOGICAL database design, an index is an aspect of a PHYSICAL database design. A key corresponds to an integrity constraint, an index is a technique of physically recording values that can be usefully applied when enforcing those constraints.
Primary/foreign : A "primary" key is a set of attributes whose values must form a combination that is unique in the entire table. There can be more than one such set (> 1 key), and the word "primary" is a remnant from the earlier days when the designer was then forced to choose one of those multiple keys as being "the most important/relevant one". The reason for this was primarily in combination with foreign keys :
Like a "primary" key, a "foreign" key is also a set of attributes. The values of these attributes must form a combination that is an existing primary key value in the referenced table. I don't know exactly how strict this rule still applies in SQL today. The terminology has remained anyway.
Unique : keyword used to indicate that an index cannot accept duplicate entries. Unique indexes are obviously an excellent means to enforce primary keys. To the extent that the word 'unique' is used in contexts of LOGICAL design, it is superfluous, sloppy, unnecessary and confusing. Keys (primary keys, that is) are unique by definition.
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
The opensource framework Dynamitey has a static method that does late binding using DLR including cast conversion among others.
dynamic Cast(object obj, Type castTo){
return Dynamic.InvokeConvert(obj, castTo, explict:true);
}
The advantage of this over a Cast<T>
called using reflection, is that this will also work for any IDynamicMetaObjectProvider
that has dynamic conversion operators, ie. TryConvert on DynamicObject
.
I have the same error : ERROR FIX !!!!
I use 'react-router-redux' v4 but she's bad.. After npm install react-router-redux@next I'm on "react-router-redux": "^5.0.0-alpha.9",
AND IT'S WORK
I would suggest you have a look at BackgroundWorker. If you have a loop that large in your WinForm it will block and your app will look like it has hanged.
Look at BackgroundWorker.ReportProgress()
to see how to report progress back to the UI thread.
For example:
private void Calculate(int i)
{
double pow = Math.Pow(i, i);
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Maximum = 100;
progressBar1.Step = 1;
progressBar1.Value = 0;
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var backgroundWorker = sender as BackgroundWorker;
for (int j = 0; j < 100000; j++)
{
Calculate(j);
backgroundWorker.ReportProgress((j * 100) / 100000);
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// TODO: do something with final calculation.
}
#include <iostream>
#include <conio.h>
using namespace std;
double raiseToPow(double ,int) //raiseToPow variable of type double which takes arguments (double, int)
void main()
{
double x; //initializing the variable x and i
int i;
cout<<"please enter the number";
cin>>x;
cout<<"plese enter the integer power that you want this number raised to";
cin>>i;
cout<<x<<"raise to power"<<i<<"is equal to"<<raiseToPow(x,i);
}
//definition of the function raiseToPower
double raiseToPow(double x, int power)
{
double result;
int i;
result =1.0;
for (i=1, i<=power;i++)
{
result = result*x;
}
return(result);
}
And what about it?:
ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);
I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json)
. my_json_object
in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.
The way I ended up solving it: the write_to_file.json
will have everything up to the bytes object that is causing the issue.
In my particular case this was a line obtained through
for line in text:
json_object['line'] = line.strip()
I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:
for line in text:
json_object['line'] = line.strip().decode()
The MOST CORRECT answer to your question is...
#content > div:first-of-type { /* css */ }
This will apply the CSS to the first div that is a direct child of #content (which may or may not be the first child element of #content)
Another option:
#content > div:nth-of-type(1) { /* css */ }
I assume X
and Y
are arrays? If so, there's a very simple way to do this:
x = [1, 1, 2, 4]
y = [1, 2, 2, 2]
# intersection
x & y # => [1, 2]
# union
x | y # => [1, 2, 4]
# difference
x - y # => [4]
There are two ways to delete an application you have uploaded from the Google Play Developer Console based off of the application's status within the Console. An app's status can be viewed from the "All Applications" tab listed in the furthest column. (See below)
Select your app from the list and at the top of the page, underneath your application name, it will say DRAFT in blue with the super low-profile option to delete it just to the right. Observe below:
Click that and you're done! Keep in mind: all of the work you have put into this application so far will be deleted from the Google Play Developer Console.
This method is similar, however it should be noted that it is not possible to permanently delete an app from your Developer Console once it has been published to the Play Store.
1) Select the application you would like to publish from the "All Applications" tab on the right of the screen
2) Below the title of the app, similar to how it was with the DRAFT application, there will be super low-profile text allowing you the option to unpublish your app from the Play Store. This process "may take a few hours to complete" as it is said by the Developer Console.
(Pictures on the way. As you have seen, my example app is still pending publication, lol)
I hope this helps to answer some people's questions.
On python side:
import time, json
from datetime import datetime as dt
your_date = dt.now()
data = json.dumps(time.mktime(your_date.timetuple())*1000)
return data # data send to javascript
On javascript side:
var your_date = new Date(data)
where data is result from python
Line breaks inside double quotes are perfectly fine according to CSV standard. The parsing of line breaks in Excel depends on the OS setting of list separator:
Windows: you need to set the list seperator to comma (Region and language » Formats » Advanced) Source: https://superuser.com/questions/238944/how-to-force-excel-to-open-csv-files-with-data-arranged-in-columns#answer-633302
Mac: Need to change the region to US (then to manually change back other settings to your preference) Source: https://answers.microsoft.com/en-us/mac/forum/macoffice2016-macexcel/line-separator-comma-semicolon-in-excel-2016-for/7db1b1a0-0300-44ba-ab9b-35d1c40159c6 (see NewmanLee's answer)
Don't forget to close Excel completely before trying again.
I've succesfully replicated the issue and was able to fix it using the above in both Max and Windows.
here is more simple way without StartCoroutine:
float t = 0f;
float waittime = 1f;
and inside Update/FixedUpdate:
if (t < 0){
t += Time.deltaTIme / waittime;
yield return t;
}
When I started using json, I was confused and unable to figure it out for some time, but finally I got what I wanted
Here is the simple solution
import json
m = {'id': 2, 'name': 'hussain'}
n = json.dumps(m)
o = json.loads(n)
print(o['id'], o['name'])
Try this:
data=pd.read_csv('C:\Users\Desktop\Data Exploration.csv')
data.head(5)
first=data['1st Gift']
last=data['Last Gift']
maxi=data['Largest Gift']
l_1=np.mean(first)-3*np.std(first)
u_1=np.mean(first)+3*np.std(first)
m=np.abs(data['1st Gift']-np.mean(data['1st Gift']))>3*np.std(data['1st Gift'])
pd.value_counts(m)
l=first[m]
data.loc[:,'1st Gift'][m==True]=np.mean(data['1st Gift'])+3*np.std(data['1st Gift'])
data['1st Gift'].head()
m=np.abs(data['Last Gift']-np.mean(data['Last Gift']))>3*np.std(data['Last Gift'])
pd.value_counts(m)
l=last[m]
data.loc[:,'Last Gift'][m==True]=np.mean(data['Last Gift'])+3*np.std(data['Last Gift'])
data['Last Gift'].head()
(I am developer of SSMSBoost add-in for SSMS)
We have recently added support for this syntax into our SSMSBoost add-in.
--#region [Optional Name]
--#endregion
It has also an option to automatically "recognize" regions when opening scripts.
Object.defineProperty(Results, "Active", {value : 'true',
writable : true,
enumerable : true,
configurable : true});
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
The shortest date format of mm/dd/yy can be obtained with:
Select Convert(varchar(8),getdate(),1)
Fought the same problem for about an hour. I finally realized that I was referencing some image files in an xml file that I did not yet have in my R.drawable folder. As soon as I copied the files into the folder, the problem went away. You need to make sure you have all the necessary files present.
Check your start indexes. Its start from 1 not 0 for Microsoft.Office.Interop.Excel range objects. I had received same error because of my loop start value.
While in 2010, java.util.Date
was the class we all used (toghether with DateFormat
and Calendar
), those classes were always poorly designed and are now long outdated. Today one would use java.time, the modern Java date and time API.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy,HH:mm:ss");
String dateTimeStringFromSqlite = "29-Apr-2010,13:00:14";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeStringFromSqlite, formatter);
System.out.println("output here: " + dateTime);
Output is:
output here: 2010-04-29T13:00:14
The combination of uppercase HH
and aaa
in your format pattern strings does not make much sense since HH
is for hour of day, rendering the AM/PM marker from aaa
superfluous. It should not do any harm, though, and I have been unable to reproduce the exact results you reported. In any case, your comment is to the point no matter if one uses the old-fashioned SimpleDateFormat
or the modern DateTimeFormatter
:
'aaa' should not be used, if you use 'aaa' then specify 'hh'
Lowercase hh
is for hour within AM or PM, from 01 through 12, so would require an AM/PM marker.
Other tips
2010-04-29T07:30:14Z
(the modern Instant
class parses and formats such strings as its default, that is, without any explicit formatter).GMT+05:30
for time zone. Prefer a real time zone, for example Asia/Colombo, Asia/Kolkata or America/New_York.DateFormat
, its parse
method returns a Date
, so you don’t need the cast in Date lNextDate = (Date)lFormatter.parse(lNextDate);
.Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Here is one way of doing it (Thanks to Android Documentation though!):
Add the following into a file (say customshape.xml) and then place it in (res/drawable/customshape.xml)
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#SomeGradientBeginColor"
android:endColor="#SomeGradientEndColor"
android:angle="270"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
Once you are done with creating this file, just set the background in one of the following ways:
Through Code:
listView.setBackgroundResource(R.drawable.customshape);
Through XML, just add the following attribute to the container (ex: LinearLayout or to any fields):
android:background="@drawable/customshape"
Hope someone finds it useful...
You almost had it with Not
. It should be:
if (-Not (Test-Path C:\Code)) {
write "it doesn't exist!"
}
You can also use !
: if (!(Test-Path C:\Code)){}
Just for fun, you could also use bitwise exclusive or, though it's not the most readable/understandable method.
if ((test-path C:\code) -bxor 1) {write "it doesn't exist!"}
SOLVED
This repository needs to be enable for finding Oracle 10.0.3.0 dependecies (this setting needs to be done in Buildconfig.groovy grails.project.dependency.resolver = "ivy" // or ivy
Also use following setting for compile time Oracle driver download
runtime "com.oracle:ojdbc:10.2.0.3.0"
This should solve your issue for not finding the Oracle driver for grails application
I have this which
advanced function in my PowerShell profile:
function which {
<#
.SYNOPSIS
Identifies the source of a PowerShell command.
.DESCRIPTION
Identifies the source of a PowerShell command. External commands (Applications) are identified by the path to the executable
(which must be in the system PATH); cmdlets and functions are identified as such and the name of the module they are defined in
provided; aliases are expanded and the source of the alias definition is returned.
.INPUTS
No inputs; you cannot pipe data to this function.
.OUTPUTS
.PARAMETER Name
The name of the command to be identified.
.EXAMPLE
PS C:\Users\Smith\Documents> which Get-Command
Get-Command: Cmdlet in module Microsoft.PowerShell.Core
(Identifies type and source of command)
.EXAMPLE
PS C:\Users\Smith\Documents> which notepad
C:\WINDOWS\SYSTEM32\notepad.exe
(Indicates the full path of the executable)
#>
param(
[String]$name
)
$cmd = Get-Command $name
$redirect = $null
switch ($cmd.CommandType) {
"Alias" { "{0}: Alias for ({1})" -f $cmd.Name, (. { which $cmd.Definition } ) }
"Application" { $cmd.Source }
"Cmdlet" { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
"Function" { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
"Workflow" { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
"ExternalScript" { $cmd.Source }
default { $cmd }
}
}
It's quite simple, first HTML must be added:
<div id="dialog"></div>
Then, it must be initialized:
<script type="text/javascript">
jQuery( document ).ready( function() {
jQuery( '#dialog' ).dialog( { 'autoOpen': false } );
});
</script>
After this you can show it by code:
jQuery( '#dialog' ).dialog( 'open' );
I'm going to give you an example of how I read REST headers for my controllers. My controllers only accept application/json as a request type if I have data that needs to be read. I suspect that your problem is that you have an application/octet-stream that Spring doesn't know how to handle.
Normally my controllers look like this:
@Controller
public class FooController {
@Autowired
private DataService dataService;
@RequestMapping(value="/foo/", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Data> getData(@RequestHeader String dataId){
return ResponseEntity.newInstance(dataService.getData(dataId);
}
Now there is a lot of code doing stuff in the background here so I will break it down for you.
ResponseEntity is a custom object that every controller returns. It contains a static factory allowing the creation of new instances. My Data Service is a standard service class.
The magic happens behind the scenes, because you are working with JSON, you need to tell Spring to use Jackson to map HttpRequest objects so that it knows what you are dealing with.
You do this by specifying this inside your <mvc:annotation-driven>
block of your config
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
ObjectMapper is simply an extension of com.fasterxml.jackson.databind.ObjectMapper
and is what Jackson uses to actually map your request from JSON into an object.
I suspect you are getting your exception because you haven't specified a mapper that can read an Octet-Stream into an object, or something that Spring can handle. If you are trying to do a file upload, that is something else entirely.
So my request that gets sent to my controller looks something like this simply has an extra header called dataId
.
If you wanted to change that to a request parameter and use @RequestParam String dataId
to read the ID out of the request your request would look similar to this:
contactId : {"fooId"}
This request parameter can be as complex as you like. You can serialize an entire object into JSON, send it as a request parameter and Spring will serialize it (using Jackson) back into a Java Object ready for you to use.
Example In Controller:
@RequestMapping(value = "/penguin Details/", method = RequestMethod.GET)
@ResponseBody
public DataProcessingResponseDTO<Pengin> getPenguinDetailsFromList(
@RequestParam DataProcessingRequestDTO jsonPenguinRequestDTO)
Request Sent:
jsonPengiunRequestDTO: {
"draw": 1,
"columns": [
{
"data": {
"_": "toAddress",
"header": "toAddress"
},
"name": "toAddress",
"searchable": true,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "fromAddress",
"header": "fromAddress"
},
"name": "fromAddress",
"searchable": true,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "customerCampaignId",
"header": "customerCampaignId"
},
"name": "customerCampaignId",
"searchable": true,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "penguinId",
"header": "penguinId"
},
"name": "penguinId",
"searchable": false,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "validpenguin",
"header": "validpenguin"
},
"name": "validpenguin",
"searchable": true,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "",
"header": ""
},
"name": "",
"searchable": false,
"orderable": false,
"search": {
"value": "",
"regex": false
}
}
],
"order": [
{
"column": 0,
"dir": "asc"
}
],
"start": 0,
"length": 10,
"search": {
"value": "",
"regex": false
},
"objectId": "30"
}
which gets automatically serialized back into an DataProcessingRequestDTO object before being given to the controller ready for me to use.
As you can see, this is quite powerful allowing you to serialize your data from JSON to an object without having to write a single line of code. You can do this for @RequestParam
and @RequestBody
which allows you to access JSON inside your parameters or request body respectively.
Now that you have a concrete example to go off, you shouldn't have any problems once you change your request type to application/json
.
I had the same issues when trying to populate a list of all the unique threads a user had with other users. This did the trick for me
Message::where('from_user', $user->id)
->select(['from_user', 'to_user'])
->selectRaw('MAX(created_at) AS last_date')
->groupBy(['from_user', 'to_user'])
->orderBy('last_date', 'DESC')
->get()
If using MVC 5 read this solution!
I know the question specifically called for MVC 3, but I stumbled upon this page with MVC 5 and wanted to post a solution for anyone else in my situation. I tried the above solutions, but they did not work for me, the Action Filter was never reached and I couldn't figure out why. I am using version 5 in my project and ended up with the following action filter:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
namespace SydHeller.Filters
{
public class ValidateJSONAntiForgeryHeader : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
string clientToken = filterContext.RequestContext.HttpContext.Request.Headers.Get(KEY_NAME);
if (clientToken == null)
{
throw new HttpAntiForgeryException(string.Format("Header does not contain {0}", KEY_NAME));
}
string serverToken = filterContext.HttpContext.Request.Cookies.Get(KEY_NAME).Value;
if (serverToken == null)
{
throw new HttpAntiForgeryException(string.Format("Cookies does not contain {0}", KEY_NAME));
}
System.Web.Helpers.AntiForgery.Validate(serverToken, clientToken);
}
private const string KEY_NAME = "__RequestVerificationToken";
}
}
-- Make note of the using System.Web.Mvc
and using System.Web.Mvc.Filters
, not the http
libraries (I think that is one of the things that changed with MVC v5. --
Then just apply the filter [ValidateJSONAntiForgeryHeader]
to your action (or controller) and it should get called correctly.
In my layout page right above </body>
I have @AntiForgery.GetHtml();
Finally, in my Razor page, I do the ajax call as follows:
var formForgeryToken = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
type: "POST",
url: serviceURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: requestData,
headers: {
"__RequestVerificationToken": formForgeryToken
},
success: crimeDataSuccessFunc,
error: crimeDataErrorFunc
});
@media all {
* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
} }
Classes in the default package cannot be imported by classes in packages. This is why you should not use the default package.
I just spent several hours on this stupid problem
First, change permissions using this in terminal
find htdocs -type f -exec chmod 664 {} + -o -type d -exec chmod 775 {} +
I don't know what the difference is between 664 and 775 I did both 775 like this Also htdocs needs the directory path for instance for me it was
/usr/local/apache2/htdocs
find htdocs -type f -exec chmod 775 {} + -o -type d -exec chmod 775 {} +
This is the other dumb thing too
make sure that your image src link is your domain name for instance
src="http://www.fakedomain.com/images/photo.png"
Be sure to have
EnableSendfile off in httpd.conf file
EnableMMAP off in httpd.conf file
You edit those using pico in terminal
I also created a directory for images specifically so that when you type in the browser address bar domainname.com/images, you will get a list of photos which can be downloaded and need to be downloaded successfully to indicate image files that are working properly
<Directory /usr/local/apache2/htdocs/images>
AddType images/png .png
</Directory>
And those are the solutions I have tried, now I have functioning images... yay!!!
Onto the next problem(s)
Change the button to
<button id="search">Search</button>
and add the following script
var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
var keyWord = $('#Keyword').val();
$('#searchResults').load(url, { searchText: keyWord });
})
and modify the controller method to accept the search text
public ActionResult DisplaySearchResults(string searchText)
{
var model = // build list based on parameter searchText
return PartialView("SearchResults", model);
}
The jQuery .load
method calls your controller method, passing the value of the search text and updates the contents of the <div>
with the partial view.
Side note: The use of a <form>
tag and @Html.ValidationSummary()
and @Html.ValidationMessageFor()
are probably not necessary here. Your never returning the Index
view so ValidationSummary
makes no sense and I assume you want a null
search text to return all results, and in any case you do not have any validation attributes for property Keyword
so there is nothing to validate.
Edit
Based on OP's comments that SearchCriterionModel
will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit()
event
<input type="submit" value="Search" />
var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
if (!$(this).valid()) {
return false; // prevent the ajax call if validation errors
}
var form = $(this).serialize();
$('#searchResults').load(url, form);
return false; // prevent the default submit action
})
and the controller method would be
public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
var model = // build list based on the properties of criteria
return PartialView("SearchResults", model);
}
I used this way, and kind liked it , it validates the form before submit also is compatible with safari/google. no jquery n.n.
<module-body>
<form id="testform" method="post">
<label>Input Title</label>
<input name="named1" placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
<alert>No Alerts!</alert>
<label>Input Title</label>
<input placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
<alert>No Alerts!</alert>
<label>Input Title</label>
<input placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
<alert>No Alerts!</alert>
</form>
</module-body>
<module-footer>
<input type="button" onclick='if (document.querySelector("#testform").reportValidity()) { document.querySelector("#testform").submit(); }' value="Submit">
<input type="button" value="Reset">
</module-footer>
As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.
Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :
> x <- factor(sample(4:8,10,replace=T))
> x
[1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
[1] 6 4 8 6 7 6 8 5 8 4
To show it works.
The timings :
> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
user system elapsed
0.11 0.00 0.11
> system.time(as.numeric(levels(x))[x])
user system elapsed
0 0 0
It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.
The purpose is typically just to restrict the scope of the nested class. Nested classes compared to normal classes have the additional possibility of the private
modifier (as well as protected
of course).
Basically, if you only need to use this class from within the "parent" class (in terms of scope), then it is usually appropiate to define it as a nested class. If this class might need to be used from without the assembly/library, then it is usually more convenient to the user to define it as a separate (sibling) class, whether or not there is any conceptual relationship between the two classes. Even though it is technically possible to create a public
class nested within a public
parent class, this is in my opinion rarely an appropiate thing to implement.
When dealing with VARCHAR
/NVARCHAR
data most other examples treat white-space the same as empty string which is equal to C# function IsNullOrWhiteSpace
.
This version respects white-space and works the same as the C# function IsNullOrEmpty
:
IIF(ISNULL(DATALENGTH(val), 0) = 0, whenTrueValue, whenFalseValue)
Simple test:
SELECT
'"' + val + '"' AS [StrValue],
IIF(ISNULL(DATALENGTH(val), 0) = 0, 'TRUE', 'FALSE') AS IsNullOrEmpty
FROM ( VALUES
(NULL),
(''),
(' '),
('a'),
('a ')
) S (val)
If the column have index and a function is applied on the column then index doesn't work and full table scan occurs, causing really slow query.
Bad Query; This would ignore index on the column date_time
select * from users
where Date(date_time) > '2010-10-10'
To utilize index on column created of type datetime comparing with today/current date, the following method can be used.
Solution for OP:
select * from users
where created > CONCAT(CURDATE(), ' 23:59:59')
Sample to get data for today:
select * from users
where
created >= CONCAT(CURDATE(), ' 00:00:00') AND
created <= CONCAT(CURDATE(), ' 23:59:59')
Or use BETWEEN for short
select * from users
where created BETWEEN
CONCAT(CURDATE(), ' 00:00:00') AND CONCAT(CURDATE(), ' 23:59:59')
Tip: If you have to do a lot of calculation or queries on dates as well as time, then it's very useful to save date and time in separate columns. (Divide & Conquer)
As suggested by @linqu you should not change your data for presentation. Since pandas 0.17.1, (conditional) formatting was made easier. Quoting the documentation:
You can apply conditional formatting, the visual styling of a
DataFrame
depending on the data within, by using theDataFrame.style
property. This is a property that returns apandas.Styler
object, which has useful methods for formatting and displayingDataFrames
.
For your example, that would be (the usual table will show up in Jupyter):
df.style.format({
'var1': '{:,.2f}'.format,
'var2': '{:,.2f}'.format,
'var3': '{:,.2%}'.format,
})
Wildcards worked for me when the string I was searching for could be entered manually. However, I wanted to store this string in another cell and refer to it. I couldn't figure out how to do this with wildcards so I ended up doing the following:
A1 is the cell containing my search string. B and C are the columns within which I want to count the number of instances of A1, including within strings:
=COUNTIF(ARRAYFORMULA(ISNUMBER(SEARCH(A1, B:C))), TRUE)
If you are looking for ReactNative's componentDidMount
equivalent, Flutter has it. It's not that simple but it's working just the same way. In Flutter, Widget
s do not handle their events directly. Instead they use their State
object to do that.
class MyWidget extends StatefulWidget{
@override
State<StatefulWidget> createState() => MyState(this);
Widget build(BuildContext context){...} //build layout here
void onLoad(BuildContext context){...} //callback when layout build done
}
class MyState extends State<MyWidget>{
MyWidget widget;
MyState(this.widget);
@override
Widget build(BuildContext context) => widget.build(context);
@override
void initState() => widget.onLoad(context);
}
State.initState
immediately will be called once upon screen has finishes rendering the layout. And will never again be called even on hot reload if you're in debug mode, until explicitly reaches time to do so.
We also had this problem. My colleague found a solution. It turned up to be a redefinition of "main" in a third party library header:
#define main SDL_main
So the solution was to add:
#undef main
before our main function.
This is clearly a stupidity!
Adding the following lines to a new script will clear all variables each time you rerun the script:
from IPython import get_ipython
get_ipython().magic('reset -sf')
To make life easy, you can add them to your default template.
In Spyder: Tools>Preferences>Editor>Edit template
True jQuery way if you want to change directly the DOM without messing with inner HTML:
$('#text').find('br').prepend(document.createTextNode('\n')).remove();
Prepend inserts inside the element, before() is the method we need here:
$('#text').find('br').before(document.createTextNode('\n')).remove();
Code will find any <br> elements, insert raw text with new line character and then remove the <br> elements.
This should be faster if you work with long texts since there are no string operations here.
To display the new lines:
$('#text').css('white-space', 'pre-line');
One of the reasons for me getting an error was the file name make sure the file name is Dockerfile So i figured it out, hope it might help someone.
To use negative indices: start at -1 and step back by -1 at each iteration.
>>> a = ["foo", "bar", "baz"]
>>> for i in range(-1, -1*(len(a)+1), -1):
... print i, a[i]
...
-1 baz
-2 bar
-3 foo
To remove the last character, just use a slice: my_file_path[:-1]
. If you only want to remove a specific set of characters, use my_file_path.rstrip('/')
. If you see the string as a file path, the operation is os.path.dirname. If the path is in fact a filename, I rather wonder where the extra slash came from in the first place.
If you're using Angular/jQuery then this might help...
<img ng-src="{{item.url}}" altSrc="{{item.alt_url}}" onerror="this.src = $(this).attr('altSrc')">
Explanation
Assuming that item
has a property url
that might be null, when it is then the image will show up as broken. That triggers execution of onerror
attribute expression, as described above. You need to override the src
attribute as described above, but you will need jQuery to access your altSrc. Couldn't get it to work with vanilla JavaScript.
Might seem a little hacky but saved the day on my project.