What you have done is correct. In general there can be many URIs to the same resource - there are no rules that say you shouldn't do that.
And generally, you may need to access items directly or as a subset of something else - so your structure makes sense to me.
Just because employees are accessible under department:
company/{companyid}/department/{departmentid}/employees
Doesn't mean they can't be accessible under company too:
company/{companyid}/employees
Which would return employees for that company. It depends on what is needed by your consuming client - that is what you should be designing for.
But I would hope that all URLs handlers use the same backing code to satisfy the requests so that you aren't duplicating code.
Encode the response content with a common enum that allows the client to switch on it and fork logic accordingly. I'm not sure how your client would distinguish the difference between a "data not found" 404 and a "web resource not found" 404? You don;t want someone to browse to userZ/9 and have the client wonder off as if the request was valid but there was no data returned.
Generally speaking, I tend to use path parameters when there is an obvious 'hierarchy' in the resource, such as:
/region/state/42
If that single resource has a status, one could:
/region/state/42/status
However, if 'region' is not really part of the resource being exposed, it probably belongs as one of the query parameters - similar to pagination (as you mentioned).
Just to add to this answer by Kamilk : https://www.stackoverflow.com/a/13905589
Depends a lot on how large dataset you are working on. Small data sets do work on effectively on offset pagination but large realtime datasets do require cursor pagination.
Found a wonderful article on how Slack evolved its api's pagination as there datasets increased explaining the positives and negatives at every stage : https://slack.engineering/evolving-api-pagination-at-slack-1c1f644f8e12
To get the number of days the easiest way would be:
SELECT EXTRACT(DAY FROM NOW() - '2014-08-02 08:10:56');
As far as I know it would return the same as:
SELECT (EXTRACT(epoch FROM (SELECT (NOW() - '2014-08-02 08:10:56')))/86400)::int;
You can use the grep -v invert-match
-v, --invert-match select non-matching lines
like this:
find . > files_and_folders
cat files_and_folders | grep -v "permission denied" > files_and_folders
Should to the magic
To clear from the current position to the end of the current line, do this:
public static void ClearToEndOfCurrentLine()
{
int currentLeft = Console.CursorLeft;
int currentTop = Console.CursorTop;
Console.Write(new String(' ', Console.WindowWidth - currentLeft));
Console.SetCursorPosition(currentLeft, currentTop);
}
You can use it in the same datafram (df) using the previously provided code
df[!grepl("REVERSE", df$Name),]
or you might assign a different name to the datafram using this code
df1<-df[!grepl("REVERSE", df$Name),]
As Davide Gualano has been told. This one
$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")
use GET method for sending the request, and this one
$("#myDiv").load("myScript.php", {var:x, var2:y, var3:z})
use POST method for sending the request. But any limitation that is applied to each method (post/get) is applied to the alternative usages that has been mentioned in the question.
For example: url length limits the amount of sending data in GET method.
You probably want to check the length of the string first and do something like this:
if (!myStr.empty())
{
char lastChar = *myStr.rbegin();
}
How to specify 64 bit integers in c
Going against the usual good idea to appending LL
.
Appending LL
to a integer constant will insure the type is at least as wide as long long
. If the integer constant is octal or hex, the constant will become unsigned long long
if needed.
If ones does not care to specify too wide a type, then LL
is OK. else, read on.
long long
may be wider than 64-bit.
Today, it is rare that long long
is not 64-bit, yet C specifies long long
to be at least 64-bit. So by using LL
, in the future, code may be specifying, say, a 128-bit number.
C has Macros for integer constants which in the below case will be type int_least64_t
#include <stdint.h>
#include <inttypes.h>
int main(void) {
int64_t big = INT64_C(9223372036854775807);
printf("%" PRId64 "\n", big);
uint64_t jenny = INT64_C(0x08675309) << 32; // shift was done on at least 64-bit type
printf("0x%" PRIX64 "\n", jenny);
}
output
9223372036854775807
0x867530900000000
The best way is to use the ncurses library - though this might be a sledgehammer to crack a nut if you just want to output a simple coloured string
Try this function for get root directory path:
get_template_directory_uri();
netsh http show urlacl
The command is mentioned in a previous comment but I'd like to bring it up as an answer. It will get you all reserved URLs in the system. If you look through all records with "80" in URL, you shall have your answer.
For example, in my case, I got:
Reserved URL: http://+:80/Temporary_Listen_Addresses/
User: \Everyone
Listen: Yes
Delegate: No
SDDL: D:(A;;GX;;;WD)
Reserved URL: http://+:80/0131501b-d67f-491b-9a40-c4bf27bcb4d4/
User: NT AUTHORITY\NETWORK SERVICE
Listen: Yes
Delegate: No
SDDL: D:(A;;GX;;;NS)
After a quick Google search, I learnt that "NT AUTHORITY\NETWORK SERVICE" belongs to SQL Server. So I went to Services and stopped SQL Server Reporting Service, port 80 is free again as I check netstat -a -b
its simple just give your physical path in directoryPath with file name
public FilePathResult GetFileFromDisk(string fileName)
{
return File(directoryPath, "multipart/form-data", fileName);
}
If you don't want to map ports from your host to the container you can access directly to the docker range ip for the container. This range is by default only accessed from your host. You can check your container network data doing:
docker inspect <containerNameOrId>
Probably is better to filter:
docker inspect <containerNameOrId> | grep '"IPAddress"' | head -n 1
Usually, the default docker ip range is 172.17.0.0/16
. Your host should be 172.17.0.1
and your first container should be 172.17.0.2
if everything is normal and you didn't specify any special network options.
EDIT Another more elegant way using docker features instead of "bash tricking":
docker inspect -f "{{ .NetworkSettings.IPAddress }}" <containerNameOrId>
I just solved this problem :
@Query(value = "SELECT ...", nativeQuery = true
)) so I recommend to define custom DTO using interface . Combine @vincsilver and @jdigital's answers with some modifications,
.reg
to current directorycode:
set TODAY=%DATE:~0,4%-%DATE:~5,2%-%DATE:~8,2%
regedit /e "%CD%\user_env_variables[%TODAY%].reg" "HKEY_CURRENT_USER\Environment"
regedit /e "%CD%\global_env_variables[%TODAY%].reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Output would like:
global_env_variables[2017-02-14].reg
user_env_variables[2017-02-14].reg
Note the following is functionally different to Gordon Linoff's answer. His answer assumes that you want to use email2
if email
is NULL. Mine assumes you want to use email2
if email
is an empty-string. The correct answer will depend on your database (or you could perform a NULL check and an empty-string check - it all depends on what is appropriate for your database design).
SELECT `id` , `naam`
FROM `klanten`
WHERE `email` LIKE '%[email protected]%'
OR (LENGTH(email) = 0 AND `email2` LIKE '%[email protected]%')
Instead of implementing a "constants interface", in Java 1.5+, you can use static imports to import the constants/static methods from another class/interface:
import static com.kittens.kittenpolisher.KittenConstants.*;
This avoids the ugliness of making your classes implement interfaces that have no functionality.
As for the practice of having a class just to store constants, I think it's sometimes necessary. There are certain constants that just don't have a natural place in a class, so it's better to have them in a "neutral" place.
But instead of using an interface, use a final class with a private constructor. (Making it impossible to instantiate or subclass the class, sending a strong message that it doesn't contain non-static functionality/data.)
Eg:
/** Set of constants needed for Kitten Polisher. */
public final class KittenConstants
{
private KittenConstants() {}
public static final String KITTEN_SOUND = "meow";
public static final double KITTEN_CUTENESS_FACTOR = 1;
}
Visual Studio 2013 natively supports Git.
See the official announcement.
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.
You can achieve it using custom log4j appender.
MaxNumberOfDays - possibility to set amount of days of rotated log files.
CompressBackups - possibility to archive old logs with zip extension.
package com.example.package;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Optional;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CustomLog4jAppender extends FileAppender {
private static final int TOP_OF_TROUBLE = -1;
private static final int TOP_OF_MINUTE = 0;
private static final int TOP_OF_HOUR = 1;
private static final int HALF_DAY = 2;
private static final int TOP_OF_DAY = 3;
private static final int TOP_OF_WEEK = 4;
private static final int TOP_OF_MONTH = 5;
private String datePattern = "'.'yyyy-MM-dd";
private String compressBackups = "false";
private String maxNumberOfDays = "7";
private String scheduledFilename;
private long nextCheck = System.currentTimeMillis() - 1;
private Date now = new Date();
private SimpleDateFormat sdf;
private RollingCalendar rc = new RollingCalendar();
private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");
public CustomLog4jAppender() {
}
public CustomLog4jAppender(Layout layout, String filename, String datePattern) throws IOException {
super(layout, filename, true);
this.datePattern = datePattern;
activateOptions();
}
public void setDatePattern(String pattern) {
datePattern = pattern;
}
public String getDatePattern() {
return datePattern;
}
@Override
public void activateOptions() {
super.activateOptions();
if (datePattern != null && fileName != null) {
now.setTime(System.currentTimeMillis());
sdf = new SimpleDateFormat(datePattern);
int type = computeCheckPeriod();
printPeriodicity(type);
rc.setType(type);
File file = new File(fileName);
scheduledFilename = fileName + sdf.format(new Date(file.lastModified()));
} else {
LogLog.error("Either File or DatePattern options are not set for appender [" + name + "].");
}
}
private void printPeriodicity(int type) {
String appender = "Log4J Appender: ";
switch (type) {
case TOP_OF_MINUTE:
LogLog.debug(appender + name + " to be rolled every minute.");
break;
case TOP_OF_HOUR:
LogLog.debug(appender + name + " to be rolled on top of every hour.");
break;
case HALF_DAY:
LogLog.debug(appender + name + " to be rolled at midday and midnight.");
break;
case TOP_OF_DAY:
LogLog.debug(appender + name + " to be rolled at midnight.");
break;
case TOP_OF_WEEK:
LogLog.debug(appender + name + " to be rolled at start of week.");
break;
case TOP_OF_MONTH:
LogLog.debug(appender + name + " to be rolled at start of every month.");
break;
default:
LogLog.warn("Unknown periodicity for appender [" + name + "].");
}
}
private int computeCheckPeriod() {
RollingCalendar rollingCalendar = new RollingCalendar(gmtTimeZone, Locale.ENGLISH);
Date epoch = new Date(0);
if (datePattern != null) {
for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
simpleDateFormat.setTimeZone(gmtTimeZone);
String r0 = simpleDateFormat.format(epoch);
rollingCalendar.setType(i);
Date next = new Date(rollingCalendar.getNextCheckMillis(epoch));
String r1 = simpleDateFormat.format(next);
if (!r0.equals(r1)) {
return i;
}
}
}
return TOP_OF_TROUBLE;
}
private void rollOver() throws IOException {
if (datePattern == null) {
errorHandler.error("Missing DatePattern option in rollOver().");
return;
}
String datedFilename = fileName + sdf.format(now);
if (scheduledFilename.equals(datedFilename)) {
return;
}
this.closeFile();
File target = new File(scheduledFilename);
if (target.exists()) {
Files.delete(target.toPath());
}
File file = new File(fileName);
boolean result = file.renameTo(target);
if (result) {
LogLog.debug(fileName + " -> " + scheduledFilename);
} else {
LogLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "].");
}
try {
this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
} catch (IOException e) {
errorHandler.error("setFile(" + fileName + ", false) call failed.");
}
scheduledFilename = datedFilename;
}
@Override
protected void subAppend(LoggingEvent event) {
long n = System.currentTimeMillis();
if (n >= nextCheck) {
now.setTime(n);
nextCheck = rc.getNextCheckMillis(now);
try {
cleanupAndRollOver();
} catch (IOException ioe) {
LogLog.error("cleanupAndRollover() failed.", ioe);
}
}
super.subAppend(event);
}
public String getCompressBackups() {
return compressBackups;
}
public void setCompressBackups(String compressBackups) {
this.compressBackups = compressBackups;
}
public String getMaxNumberOfDays() {
return maxNumberOfDays;
}
public void setMaxNumberOfDays(String maxNumberOfDays) {
this.maxNumberOfDays = maxNumberOfDays;
}
protected void cleanupAndRollOver() throws IOException {
File file = new File(fileName);
Calendar cal = Calendar.getInstance();
int maxDays = 7;
try {
maxDays = Integer.parseInt(getMaxNumberOfDays());
} catch (Exception e) {
// just leave it at 7.
}
cal.add(Calendar.DATE, -maxDays);
Date cutoffDate = cal.getTime();
if (file.getParentFile().exists()) {
File[] files = file.getParentFile().listFiles(new StartsWithFileFilter(file.getName(), false));
int nameLength = file.getName().length();
for (File value : Optional.ofNullable(files).orElse(new File[0])) {
String datePart;
try {
datePart = value.getName().substring(nameLength);
Date date = sdf.parse(datePart);
if (date.before(cutoffDate)) {
Files.delete(value.toPath());
} else if (getCompressBackups().equalsIgnoreCase("YES") || getCompressBackups().equalsIgnoreCase("TRUE")) {
zipAndDelete(value);
}
} catch (Exception pe) {
// This isn't a file we should touch (it isn't named correctly)
}
}
}
rollOver();
}
private void zipAndDelete(File file) throws IOException {
if (!file.getName().endsWith(".zip")) {
File zipFile = new File(file.getParent(), file.getName() + ".zip");
try (FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos)) {
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[4096];
while (true) {
int bytesRead = fis.read(buffer);
if (bytesRead == -1) {
break;
} else {
zos.write(buffer, 0, bytesRead);
}
}
zos.closeEntry();
}
Files.delete(file.toPath());
}
}
class StartsWithFileFilter implements FileFilter {
private String startsWith;
private boolean inclDirs;
StartsWithFileFilter(String startsWith, boolean includeDirectories) {
super();
this.startsWith = startsWith.toUpperCase();
inclDirs = includeDirectories;
}
public boolean accept(File pathname) {
if (!inclDirs && pathname.isDirectory()) {
return false;
} else {
return pathname.getName().toUpperCase().startsWith(startsWith);
}
}
}
class RollingCalendar extends GregorianCalendar {
private static final long serialVersionUID = -3560331770601814177L;
int type = CustomLog4jAppender.TOP_OF_TROUBLE;
RollingCalendar() {
super();
}
RollingCalendar(TimeZone tz, Locale locale) {
super(tz, locale);
}
void setType(int type) {
this.type = type;
}
long getNextCheckMillis(Date now) {
return getNextCheckDate(now).getTime();
}
Date getNextCheckDate(Date now) {
this.setTime(now);
switch (type) {
case CustomLog4jAppender.TOP_OF_MINUTE:
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.MINUTE, 1);
break;
case CustomLog4jAppender.TOP_OF_HOUR:
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.HOUR_OF_DAY, 1);
break;
case CustomLog4jAppender.HALF_DAY:
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
int hour = get(Calendar.HOUR_OF_DAY);
if (hour < 12) {
this.set(Calendar.HOUR_OF_DAY, 12);
} else {
this.set(Calendar.HOUR_OF_DAY, 0);
this.add(Calendar.DAY_OF_MONTH, 1);
}
break;
case CustomLog4jAppender.TOP_OF_DAY:
this.set(Calendar.HOUR_OF_DAY, 0);
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.DATE, 1);
break;
case CustomLog4jAppender.TOP_OF_WEEK:
this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek());
this.set(Calendar.HOUR_OF_DAY, 0);
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.WEEK_OF_YEAR, 1);
break;
case CustomLog4jAppender.TOP_OF_MONTH:
this.set(Calendar.DATE, 1);
this.set(Calendar.HOUR_OF_DAY, 0);
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.MONTH, 1);
break;
default:
throw new IllegalStateException("Unknown periodicity type.");
}
return getTime();
}
}
}
And use this properties in your log4j config file:
log4j.appender.[appenderName]=com.example.package.CustomLog4jAppender
log4j.appender.[appenderName].File=/logs/app-daily.log
log4j.appender.[appenderName].Append=true
log4j.appender.[appenderName].encoding=UTF-8
log4j.appender.[appenderName].layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.[appenderName].layout.ConversionPattern=%-5.5p %d %C{1.} - %m%n
log4j.appender.[appenderName].DatePattern='.'yyyy-MM-dd
log4j.appender.[appenderName].MaxNumberOfDays=7
log4j.appender.[appenderName].CompressBackups=true
First of all, you may want to store text in CLOB/NCLOB columns instead of BLOB, which is designed for binary data (your query would work with a CLOB, by the way).
The following query will let you see the first 32767 characters (at most) of the text inside the blob, provided all the character sets are compatible (original CS of the text stored in the BLOB, CS of the database used for VARCHAR2) :
select utl_raw.cast_to_varchar2(dbms_lob.substr(BLOB_FIELD)) from TABLE_WITH_BLOB where ID = '<row id>';
Try this:
SELECT Count(*)
FROM <DATABASE_NAME>.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
I was curious if there is any measurable impact on performance between the various ways one can call std::sort, so I've created this simple test:
$ cat sort.cpp
#include<algorithm>
#include<iostream>
#include<vector>
#include<chrono>
#define COMPILER_BARRIER() asm volatile("" ::: "memory");
typedef unsigned long int ulint;
using namespace std;
struct S {
int x;
int y;
};
#define BODY { return s1.x*s2.y < s2.x*s1.y; }
bool operator<( const S& s1, const S& s2 ) BODY
bool Sgreater_func( const S& s1, const S& s2 ) BODY
struct Sgreater {
bool operator()( const S& s1, const S& s2 ) const BODY
};
void sort_by_operator(vector<S> & v){
sort(v.begin(), v.end());
}
void sort_by_lambda(vector<S> & v){
sort(v.begin(), v.end(), []( const S& s1, const S& s2 ) BODY );
}
void sort_by_functor(vector<S> &v){
sort(v.begin(), v.end(), Sgreater());
}
void sort_by_function(vector<S> &v){
sort(v.begin(), v.end(), &Sgreater_func);
}
const int N = 10000000;
vector<S> random_vector;
ulint run(void foo(vector<S> &v)){
vector<S> tmp(random_vector);
foo(tmp);
ulint checksum = 0;
for(int i=0;i<tmp.size();++i){
checksum += i *tmp[i].x ^ tmp[i].y;
}
return checksum;
}
void measure(void foo(vector<S> & v)){
ulint check_sum = 0;
// warm up
const int WARMUP_ROUNDS = 3;
const int TEST_ROUNDS = 10;
for(int t=WARMUP_ROUNDS;t--;){
COMPILER_BARRIER();
check_sum += run(foo);
COMPILER_BARRIER();
}
for(int t=TEST_ROUNDS;t--;){
COMPILER_BARRIER();
auto start = std::chrono::high_resolution_clock::now();
COMPILER_BARRIER();
check_sum += run(foo);
COMPILER_BARRIER();
auto end = std::chrono::high_resolution_clock::now();
COMPILER_BARRIER();
auto duration_ns = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();
cout << "Took " << duration_ns << "s to complete round" << endl;
}
cout << "Checksum: " << check_sum << endl;
}
#define M(x) \
cout << "Measure " #x " on " << N << " items:" << endl;\
measure(x);
int main(){
random_vector.reserve(N);
for(int i=0;i<N;++i){
random_vector.push_back(S{rand(), rand()});
}
M(sort_by_operator);
M(sort_by_lambda);
M(sort_by_functor);
M(sort_by_function);
return 0;
}
What it does is it creates a random vector, and then measures how much time is required to copy it and sort the copy of it (and compute some checksum to avoid too vigorous dead code elimination).
I was compiling with g++ (GCC) 7.2.1 20170829 (Red Hat 7.2.1-1)
$ g++ -O2 -o sort sort.cpp && ./sort
Here are results:
Measure sort_by_operator on 10000000 items:
Took 0.994285s to complete round
Took 0.990162s to complete round
Took 0.992103s to complete round
Took 0.989638s to complete round
Took 0.98105s to complete round
Took 0.991913s to complete round
Took 0.992176s to complete round
Took 0.981706s to complete round
Took 0.99021s to complete round
Took 0.988841s to complete round
Checksum: 18446656212269526361
Measure sort_by_lambda on 10000000 items:
Took 0.974274s to complete round
Took 0.97298s to complete round
Took 0.964506s to complete round
Took 0.96899s to complete round
Took 0.965773s to complete round
Took 0.96457s to complete round
Took 0.974286s to complete round
Took 0.975524s to complete round
Took 0.966238s to complete round
Took 0.964676s to complete round
Checksum: 18446656212269526361
Measure sort_by_functor on 10000000 items:
Took 0.964359s to complete round
Took 0.979619s to complete round
Took 0.974027s to complete round
Took 0.964671s to complete round
Took 0.964764s to complete round
Took 0.966491s to complete round
Took 0.964706s to complete round
Took 0.965115s to complete round
Took 0.964352s to complete round
Took 0.968954s to complete round
Checksum: 18446656212269526361
Measure sort_by_function on 10000000 items:
Took 1.29942s to complete round
Took 1.3029s to complete round
Took 1.29931s to complete round
Took 1.29946s to complete round
Took 1.29837s to complete round
Took 1.30132s to complete round
Took 1.3023s to complete round
Took 1.30997s to complete round
Took 1.30819s to complete round
Took 1.3003s to complete round
Checksum: 18446656212269526361
Looks like all the options except for passing function pointer are very similar, and passing a function pointer causes +30% penalty.
It also looks like the operator< version is ~1% slower (I repeated the test multiple times and the effect persists), which is a bit strange as it suggests that the generated code is different (I lack skill to analyze --save-temps output).
You can try the code below:
# Load the packages required to read XML files.
library("XML")
library("methods")
# Convert the input xml file to a data frame.
xmldataframe <- xmlToDataFrame("input.xml")
print(xmldataframe)
Add this class in .css class
.scrol {
font: bold 14px Arial;
border:1px solid black;
width:100% ;
color:#616D7E;
height:20px;
overflow:scroll;
overflow-y:scroll;
overflow-x:hidden;
}
and use the class in div. like here.
<div> <p class = "scrol" id = "title">-</p></div>
I have attached image , you see the out put of the above code
Steps to create Hash Key.
1: Download openssl from Openssl for Windows . I downloaded the Win64 version
2:Unzip and copy all the files in the bin folder including openssl.exe(All file of bin folder)
3:Goto to the folder where you installed JDK for me it’s C:\Program Files\Java\jdk1.8.0_05\bin
4:Paste all the files you copied from Openssl’s bin folder to the Jdk folder.
then go C:\Program Files\Java\jdk1.8.0_05\bin and press shift key and right click and open cmd
C:\Program Files\Java\jdk1.8.0_05\bin>//cmd path
that is for Sha1 past this
keytool -exportcert -alias androiddebugkey -keystore "C:\User\ABC\.android.keystore" | openssl sha1 -binary | openssl base64
//and ABC is system name put own system name
Since you now specified you want to add to it, what you want isn't a simple IEnumerable<T>
but at least an ICollection<T>
. I recommend simply using a List<T>
like this:
List<object> myList=new List<object>();
myList.Add(1);
myList.Add(2);
myList.Add(3);
You can use myList everywhere an IEnumerable<object>
is expected, since List<object>
implements IEnumerable<object>
.
(old answer before clarification)
You can't create an instance of IEnumerable<T>
since it's a normal interface(It's sometimes possible to specify a default implementation, but that's usually used only with COM).
So what you really want is instantiate a class that implements the interface IEnumerable<T>
. The behavior varies depending on which class you choose.
For an empty sequence use:
IEnumerable<object> e0=Enumerable.Empty<object>();
For an non empty enumerable you can use some collection that implements IEnumerable<T>
. Common choices are the array T[]
, List<T>
or if you want immutability ReadOnlyCollection<T>
.
IEnumerable<object> e1=new object[]{1,2,3};
IEnumerable<object> e2=new List<object>(){1,2,3};
IEnumerable<object> e3=new ReadOnlyCollection(new object[]{1,2,3});
Another common way to implement IEnumerable<T>
is the iterator feature introduced in C# 3:
IEnumerable<object> MyIterator()
{
yield return 1;
yield return 2;
yield return 3;
}
IEnumerable<object> e4=MyIterator();
I realize this is a little old, but, yes it can be done. Some javascript to get you started:
viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0');
Just change the parts you need and Mobile Safari will respect the new settings.
Update:
If you don't already have the meta viewport tag in the source, you can append it directly with something like this:
var metaTag=document.createElement('meta');
metaTag.name = "viewport"
metaTag.content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
document.getElementsByTagName('head')[0].appendChild(metaTag);
Or if you're using jQuery:
$('head').append('<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">');
Update your pom.xml
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.1</version>
</dependency>
Environment variables are 'evaluated' (ie. they are attributed) in the following order:
Every process has an environment block that contains a set of environment variables and their values. There are two types of environment variables: user environment variables (set for each user) and system environment variables (set for everyone). A child process inherits the environment variables of its parent process by default.
Programs started by the command processor inherit the command processor's environment variables.
Environment variables specify search paths for files, directories for temporary files, application-specific options, and other similar information. The system maintains an environment block for each user and one for the computer. The system environment block represents environment variables for all users of the particular computer. A user's environment block represents the environment variables the system maintains for that particular user, including the set of system environment variables.
Here's a detailed manual:
http://codexpi.com/add-android-adb-path-mac-os-x-mavericks/
To sum this up:
Create and open the bash_profile file
touch .bash_profile
open -e .bash_profile
Add the path of the platform-tools folder (within the Android SDK)
export PATH="$PATH:/Users/USERNAME/PATH TO ANDROID SDK/platform-tools/
Run the command . .bash_profile
to update (no need to restart the terminal)
It's a class of problems where we must simulate every possibility to be sure we have the optimal solution.
There are a lot of good heuristics for some NP-Complete problems, but they are only an educated guess at best.
The best solution for me was to add a key binding to run PHP code directly in the terminal
To do so you just need to download terminal-command-keys
from VS code extensions marketplace:
Then got to File>Preferences>Keyboard Shortcuts and click on the following icon at the upper right corner:
It will open up the keybindings.json
file
Add the following settings
[
{
"key": "ctrl+s",
"command":"terminalCommandKeys.run",
"when": "editorLangId == php",
"args": {
"cmd":"php ${file}",
"newTerminal":true,
"saveAllfiles": true,
"showTerminal": true,
}
}
]
key is the shortcut to run your PHP file (I use ctrl+s) you can change it as you wish
when to run different commands for different file types (I set it for PHP files only) vscode's "when" clauses
See the full settings documentation from here
That's it, I hope it helps.
For any ubuntu users visiting this page, I was facing the same error and the issue was XAMPP (LAMPP in ubuntu) was not able to connect to mysql because another mysql service was working so my solution to this issue was
stop mysql service
sudo service mysql stop
restart lampp
sudo /opt/lampp/lampp restart
There is a list of Sqlite wrappers for .Net at http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers. From what I've heard http://sqlite.phxsoftware.com/ is quite good. This particular one lets you access Sqlite through ADO.Net just like any other database.
Just in case someone still facing an error after trying to import CommonModule
, try to restart the server. It surprisingly work
You're really close to the answer yourself
<button type="submit">
<img src="save.gif" alt="Save icon"/>
<br/>
Save
</button>
Or, you can just remove the type-attribute
<button>
<img src="save.gif" alt="Save icon"/>
<br/>
Save
</button>
I thing these two links have a wide discussion on your problem related stuff. fb:ref clear cashes by calling
fbml.refreshRefUrl
like this
<tt>fbml.refreshRefUrl("http://www.mysite.com/someurl.php")
You can study the related stuff from here fb:ref. I hope it will work for you
HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.
The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.
The size_t
type is the unsigned integer type that is the result of the sizeof
operator (and the offsetof
operator), so it is guaranteed to be big enough to contain the size of the biggest object your system can handle (e.g., a static array of 8Gb).
The size_t
type may be bigger than, equal to, or smaller than an unsigned int
, and your compiler might make assumptions about it for optimization.
You may find more precise information in the C99 standard, section 7.17, a draft of which is available on the Internet in pdf format, or in the C11 standard, section 7.19, also available as a pdf draft.
Since you're not passing in POST data, I'll assume that what you are trying to do is set an initial value that will be displayed in the form. The way you do this is with the initial
keyword.
form = CustomForm(initial={'Email': GetEmailString()})
See the Django Form docs for more explanation.
If you are trying to change a value after the form was submitted, you can use something like:
if form.is_valid():
form.cleaned_data['Email'] = GetEmailString()
Check the referenced docs above for more on using cleaned_data
Like this:
@Html.DropDownListFor(model => model.Status, new List<SelectListItem>
{ new SelectListItem{Text="Active", Value="True"},
new SelectListItem{Text="Deactive", Value="False"}},"Select One")
If you want Active to be selected by default then use Selected
property of SelectListItem
:
@Html.DropDownListFor(model => model.Status, new List<SelectListItem>
{ new SelectListItem{Text="Active", Value="True",Selected=true},
new SelectListItem{Text="Deactive", Value="False"}},"Select One")
If using SelectList
, then you have to use this overload and specify SelectListItem
Value
property which you want to set selected:
@Html.DropDownListFor(model => model.title,
new SelectList(new List<SelectListItem>
{
new SelectListItem { Text = "Active" , Value = "True"},
new SelectListItem { Text = "InActive", Value = "False" }
},
"Value", // property to be set as Value of dropdown item
"Text", // property to be used as text of dropdown item
"True"), // value that should be set selected of dropdown
new { @class = "form-control" })
swift 3
let preferredLanguage = Locale.preferredLanguages[0] as String
print (preferredLanguage) //en-US
let arr = preferredLanguage.components(separatedBy: "-")
let deviceLanguage = arr.first
print (deviceLanguage) //en
std::map::find
returns an iterator to the found element (or to the end()
if the element was not found). So long as the map
is not const, you can modify the element pointed to by the iterator:
std::map<char, int> m;
m.insert(std::make_pair('c', 0)); // c is for cookie
std::map<char, int>::iterator it = m.find('c');
if (it != m.end())
it->second = 42;
I didn't like how I had to explicitly specify all the other column in the other solutions so this worked best for me. Though it might be slow for large dataframes...?
df = df.set_index('Mid').reset_index()
Why Not Use an Inner Class (Nesting)
class A extends B {
private class C extends D {
//Classes A , B , C , D accessible here
}
}
I tend to just show/hide a IMG as other have stated. I found a good website which generates "loading gifs"
Link
I just put it inside a div
and hide by default display: none;
(css) then when you call the function show the image, once its complete hide it again.
By calling method
public class a
{
void sum(int i,int k)
{
System.out.println("THe sum of the number="+(i+k));
}
}
class b
{
public static void main(String[] args)
{
a vc=new a();
vc.sum(10 , 20);
}
}
The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.
Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.
github gist https://gist.github.com/anjia0532/da4a17f848468de5a374c860b17607e7
#set $token "?"; # deprecated
set $token ""; # declar token is ""(empty str) for original request without args,because $is_args concat any var will be `?`
if ($is_args) { # if the request has args update token to "&"
set $token "&";
}
location /test {
set $args "${args}${token}k1=v1&k2=v2"; # update original append custom params with $token
# if no args $is_args is empty str,else it's "?"
# http is scheme
# service is upstream server
#proxy_pass http://service/$uri$is_args$args; # deprecated remove `/`
proxy_pass http://service$uri$is_args$args; # proxy pass
}
#http://localhost/test?foo=bar ==> http://service/test?foo=bar&k1=v1&k2=v2
#http://localhost/test/ ==> http://service/test?k1=v1&k2=v2
This is how I managed to sort and populate:
Model.find()
.sort('date', -1)
.populate('authors')
.exec(function(err, docs) {
// code here
})
The following test works in Chrome 16 (dev branch) on X86 and Chrome 15 on Mac OSX Lion
In my experience JSON.stringify is slightly faster than util.inspect. I had to save the result object of a DB2 query as a json file, The query returned an object of 92k rows, the conversion took very long to complete with util.inspect, so I did the following test by writing the same 1000 record object to a file with both methods.
JSON.Stringify
fs.writeFile('./data.json', JSON.stringify(obj, null, 2));
Time: 3:57 (3 min 57 sec)
Result's format:
[
{
"PROB": "00001",
"BO": "AXZ",
"CNTRY": "649"
},
...
]
util.inspect
var util = require('util');
fs.writeFile('./data.json', util.inspect(obj, false, 2, false));
Time: 4:12 (4 min 12 sec)
Result's format:
[ { PROB: '00001',
BO: 'AXZ',
CNTRY: '649' },
...
]
The tabindex is used to define a sequence that users follow when they use the Tab key to navigate through a page. By default, the natural tabbing order will match the source order in the markup.
The tabindex content attribute allows authors to control whether an element is supposed to be focusable, whether it is supposed to be reachable using sequential focus navigation, and what is to be the relative order of the element for the purposes of sequential focus navigation. The name "tab index" comes from the common use of the "tab" key to navigate through the focusable elements. The term "tabbing" refers to moving forward through the focusable elements that can be reached using sequential focus navigation.
W3C Recommendation: HTML5
Section 7.4.1 Sequential focus navigation and the tabindex attribute
The tabindex
starts at 0 or any positive whole number and increments upward. It's common to see the value 0 avoided because in older versions of Mozilla and IE, the tabindex would start at 1, move on to 2, and only after 2 would it go to 0 and then 3. The maximum integer value for tabindex
is 32767
. If elements have the same tabindex
then the tabindex will match the source order in the markup. A negative value will remove the element from the tab index so it will never be focused.
If an element is assigned a tabindex
of -1
it will remove the element and it will never be focusable but focus can be given to the element programmatically using element.focus()
.
If you specify the tabindex
attribute with no value or an empty value it will be ignored.
If the disabled
attribute is set on an element which has a tabindex
, the element will be ignored.
If a tabindex
is set anywhere within the page regardless of where it is in relation to the rest of the code (it could be in the footer, content area, where-ever) if there is a defined tabindex
then the tab order will start at the element which is explicitly assigned the lowest tabindex
value above 0. It will then cycle through the elements defined and only after the explicit tabindex
elements have been tabbed through, will it return to the beginning of the document and follow the natural tab order.
In the HTML4 spec only the following elements support the tabindex attribute: anchor, area, button, input, object, select, and textarea. But the HTML5 spec, with accessibility in mind, allows all elements to be assigned tabindex
.
--
<ul tabindex="-1">
<li tabindex="1"></li>
<li tabindex="2"></li>
<li tabindex="3"></li>
</ul>
is the same as
<ul tabindex="-1">
<li tabindex="1"></li>
<li tabindex="1"></li>
<li tabindex="1"></li>
</ul>
because regardless of the fact that they are all assigned tabindex="1"
, they will still follow the same order, the first one is first, and the last one is last. This is also the same..
<div>
<a></a>
<a></a>
<a></a>
</div>
because you do not need to explicitly define the tabIndex if it's default behavior. A div
by default will not be focusable, the anchor
tags will.
Be careful, characters like ’ or » are considered as alpha by MySQL. It better to use something like :
IF c BETWEEN 'a' AND 'z' OR c BETWEEN 'A' AND 'Z' OR c BETWEEN '0' AND '9' OR c = '-' THEN
I found this question when I was looking for the answer to the above question. But in my case the issue was the use of an 'en dash' rather than a 'dash'. Check which dash you are using, it might be the wrong one. I hope this answer speeds up someone else's search, a comment like this could have saved me a bit of time.
if string is a variable, use the .repr method on it:
>>> s = '\tgherkin\n'
>>> s
'\tgherkin\n'
>>> print(s)
gherkin
>>> print(s.__repr__())
'\tgherkin\n'
You can't do this with jQuery ajax, but with native XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//this.response is what you're looking for
handler(this.response);
console.log(this.response, typeof this.response);
var img = document.getElementById('img');
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
}
}
xhr.open('GET', 'http://jsfiddle.net/img/logo.png');
xhr.responseType = 'blob';
xhr.send();
EDIT
So revisiting this topic, it seems it is indeed possible to do this with jQuery 3
jQuery.ajax({_x000D_
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
cache:false,_x000D_
xhr:function(){// Seems like the only way to get access to the xhr object_x000D_
var xhr = new XMLHttpRequest();_x000D_
xhr.responseType= 'blob'_x000D_
return xhr;_x000D_
},_x000D_
success: function(data){_x000D_
var img = document.getElementById('img');_x000D_
var url = window.URL || window.webkitURL;_x000D_
img.src = url.createObjectURL(data);_x000D_
},_x000D_
error:function(){_x000D_
_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
or
use xhrFields to set the responseType
jQuery.ajax({_x000D_
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
cache:false,_x000D_
xhrFields:{_x000D_
responseType: 'blob'_x000D_
},_x000D_
success: function(data){_x000D_
var img = document.getElementById('img');_x000D_
var url = window.URL || window.webkitURL;_x000D_
img.src = url.createObjectURL(data);_x000D_
},_x000D_
error:function(){_x000D_
_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
If you use the Connect to Database under tools in Visual Studio, you will be able to add the name of the Server and database and test the connection. Upon success you can copy the string from the bottom of the dialog.
It's a little trickier to do what you're trying to do than I'd prefer, but that's because you don't really directly bind a DataGrid
to a DataTable
.
When you bind DataGrid.ItemsSource
to a DataTable
, you're really binding it to the default DataView
, not to the table itself. This is why, for instance, you don't have to do anything to make a DataGrid
sort rows when you click on a column header - that functionality's baked into DataView
, and DataGrid
knows how to access it (through the IBindingList
interface).
The DataView
implements IEnumerable<DataRowView>
(more or less), and the DataGrid
fills its items by iterating over this. This means that when you've bound DataGrid.ItemsSource
to a DataTable
, its SelectedItem
property will be a DataRowView
, not a DataRow
.
If you know all this, it's pretty straightforward to build a wrapper class that lets you expose properties that you can bind to. There are three key properties:
Table
, the DataTable
,Row
, a two-way bindable property of type DataRowView
, and SearchText
, a string property that, when it's set, will find the first matching DataRowView
in the table's default view, set the Row
property, and raise PropertyChanged
.It looks like this:
public class DataTableWrapper : INotifyPropertyChanged
{
private DataRowView _Row;
private string _SearchText;
public DataTableWrapper()
{
// using a parameterless constructor lets you create it directly in XAML
DataTable t = new DataTable();
t.Columns.Add("id", typeof (int));
t.Columns.Add("text", typeof (string));
// let's acquire some sample data
t.Rows.Add(new object[] { 1, "Tower"});
t.Rows.Add(new object[] { 2, "Luxor" });
t.Rows.Add(new object[] { 3, "American" });
t.Rows.Add(new object[] { 4, "Festival" });
t.Rows.Add(new object[] { 5, "Worldwide" });
t.Rows.Add(new object[] { 6, "Continental" });
t.Rows.Add(new object[] { 7, "Imperial" });
Table = t;
}
// you should have this defined as a code snippet if you work with WPF
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
{
h(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
// SelectedItem gets bound to this two-way
public DataRowView Row
{
get { return _Row; }
set
{
if (_Row != value)
{
_Row = value;
OnPropertyChanged("Row");
}
}
}
// the search TextBox is bound two-way to this
public string SearchText
{
get { return _SearchText; }
set
{
if (_SearchText != value)
{
_SearchText = value;
Row = Table.DefaultView.OfType<DataRowView>()
.Where(x => x.Row.Field<string>("text").Contains(_SearchText))
.FirstOrDefault();
}
}
}
public DataTable Table { get; private set; }
}
And here's XAML that uses it:
<Window x:Class="DataGridSelectionDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
xmlns:DataGridSelectionDemo="clr-namespace:DataGridSelectionDemo"
Title="DataGrid selection demo"
Height="350"
Width="525">
<Window.DataContext>
<DataGridSelectionDemo:DataTableWrapper />
</Window.DataContext>
<DockPanel>
<Grid DockPanel.Dock="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label>Text</Label>
<TextBox Grid.Column="1"
Text="{Binding SearchText, Mode=TwoWay}" />
</Grid>
<dg:DataGrid DockPanel.Dock="Top"
ItemsSource="{Binding Table}"
SelectedItem="{Binding Row, Mode=TwoWay}" />
</DockPanel>
</Window>
Assuming it actually is a symlink,
$ rm -d symlink
It should figure it out, but since it can't we enable the latent code that was intended for another case that no longer exists but happens to do the right thing here.
var=$(echo "asdf")
echo $var
# => asdf
Using this method, the command is immediately evaluated and it's return value is stored.
stored_date=$(date)
echo $stored_date
# => Thu Jan 15 10:57:16 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 10:57:16 EST 2015
Same with backtick
stored_date=`date`
echo $stored_date
# => Thu Jan 15 11:02:19 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 11:02:19 EST 2015
Using eval in the $(...)
will not make it evaluated later
stored_date=$(eval "date")
echo $stored_date
# => Thu Jan 15 11:05:30 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 11:05:30 EST 2015
Using eval, it is evaluated when eval
is used
stored_date="date" # < storing the command itself
echo $(eval "$stored_date")
# => Thu Jan 15 11:07:05 EST 2015
# (wait a few seconds)
echo $(eval "$stored_date")
# => Thu Jan 15 11:07:16 EST 2015
# ^^ Time changed
In the above example, if you need to run a command with arguments, put them in the string you are storing
stored_date="date -u"
# ...
For bash scripts this is rarely relevant, but one last note. Be careful with eval
. Eval only strings you control, never strings coming from an untrusted user or built from untrusted user input.
[HttpPost]
public JsonResult DeleteCotnact(int id)
{
using (MycasedbEntities dbde = new MycasedbEntities())
{
Contact rowcontact = (from c in dbde.Contact
where c.Id == id
select c).FirstOrDefault();
dbde.Contact.Remove(rowcontact);
dbde.SaveChanges();
return Json(id);
}
}
What do you think of this, simple or not, you could also try this:
var productrow = cnn.Product.Find(id);
cnn.Product.Remove(productrow);
cnn.SaveChanges();
Try adding the following line at the top of your python script.
# _*_ coding:utf-8 _*_
There are loads of PHP exploits which can be disabled by settings in the PHP.ini file. Obvious example is register_globals, but depending on settings it may also be possible to include or open files from remote machines via HTTP, which can be exploited if a program uses variable filenames for any of its include() or file handling functions.
PHP also allows variable function calling by adding () to the end of a variable name -- eg $myvariable();
will call the function name specified by the variable. This is exploitable; eg if an attacker can get the variable to contain the word 'eval', and can control the parameter, then he can do anything he wants, even though the program doesn't actually contain the eval() function.
pure python code:
from math import sqrt
def stddev(lst):
mean = float(sum(lst)) / len(lst)
return sqrt(float(reduce(lambda x, y: x + y, map(lambda x: (x - mean) ** 2, lst))) / len(lst))
Have you thought about this:
try {
ko.applyBindings(PersonListViewModel);
}
catch (err) {
console.log(err.message);
}
I came up with this because in Knockout, i found this code
var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
if (!sourceBindings) {
if (alreadyBound) {
throw Error("You cannot apply bindings multiple times to the same element.");
}
ko.utils.domData.set(node, boundElementDomDataKey, true);
}
So to me its not really an issue that its already bound, its that the error was not caught and dealt with...
You cannot add default values for function parameters. But you can do this:
function tester(paramA, paramB){
if (typeof paramA == "undefined"){
paramA = defaultValue;
}
if (typeof paramB == "undefined"){
paramB = defaultValue;
}
}
Here's a beautiful dynamic function I wrote to remove last part of url or path.
/**
* remove the last directories
*
* @param $path the path
* @param $level number of directories to remove
*
* @return string
*/
private function removeLastDir($path, $level)
{
if(is_int($level) && $level > 0){
$path = preg_replace('#\/[^/]*$#', '', $path);
return $this->removeLastDir($path, (int) $level - 1);
}
return $path;
}
yum install python-devel
will work.
If yum
doesn't work then use
apt-get install python-dev
Short answer: for both PUT and DELETE, you should send either 200 (OK) or 204 (No Content).
Long answer: here's a complete decision diagram (click to magnify).
var thisRegex = new RegExp('\[(\d+)\]\[(\d+)\]');
if(!thisRegex.test(text)){
alert('fail');
}
I found test to act more preg_match as it provides a Boolean return. However you do have to declare a RegExp var.
TIP: RegExp adds it's own / at the start and finish, so don't pass them.
foreach ($array as $key => $val) {
echo $val;
}
Use following codes to read the file
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
-> This application is printing the file content line by line
When you declare a variable without initializing it, a random number from memory is selected and the variable is initialized to that value.
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
As many have stated, relying on the moving target of the user agent data is problematic. The same can be said for counting on screen size.
My approach is borrowed from a CSS technique to determine if the interface is touch:
Using only javascript (support by all modern browsers), a media query match can easily infer whether the device is mobile.
function isMobile() {
var match = window.matchMedia || window.msMatchMedia;
if(match) {
var mq = match("(pointer:coarse)");
return mq.matches;
}
return false;
}
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
The three operators have related but different meanings, despite the misleading note from the IDE.
The ::
operator is known as the scope resolution operator, and it is used to get from a namespace or class to one of its members.
The .
and ->
operators are for accessing an object instance's members, and only comes into play after creating an object instance. You use .
if you have an actual object (or a reference to the object, declared with &
in the declared type), and you use ->
if you have a pointer to an object (declared with *
in the declared type).
The this
object is always a pointer to the current instance, hence why the ->
operator is the only one that works.
Examples:
// In a header file
namespace Namespace {
class Class {
private:
int x;
public:
Class() : x(4) {}
void incrementX();
};
}
// In an implementation file
namespace Namespace {
void Class::incrementX() { // Using scope resolution to get to the class member when we aren't using an instance
++(this->x); // this is a pointer, so using ->. Equivalent to ++((*this).x)
}
}
// In a separate file lies your main method
int main() {
Namespace::Class myInstance; // instantiates an instance. Note the scope resolution
Namespace::Class *myPointer = new Namespace::Class;
myInstance.incrementX(); // Calling a function on an object instance.
myPointer->incrementX(); // Calling a function on an object pointer.
(*myPointer).incrementX(); // Calling a function on an object pointer by dereferencing first
return 0;
}
CSS
body { margin: 0; }
canvas { display: block; }
JavaScript
window.addEventListener("load", function()
{
var canvas = document.createElement('canvas'); document.body.appendChild(canvas);
var context = canvas.getContext('2d');
function draw()
{
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(0, 0); context.lineTo(canvas.width, canvas.height);
context.moveTo(canvas.width, 0); context.lineTo(0, canvas.height);
context.stroke();
}
function resize()
{
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
draw();
}
window.addEventListener("resize", resize);
resize();
});
This happened to me because of a partially downloaded gradle distribution zip
To resolve simply go to below path
"C:/Users/your_username/.gradle"
OR
pull your gradle path from File->Settings->Build, Exectution, Deployment-> Gradle -> gradle service directory path.
Delete the partially downloaded distribution gradle folder
OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.
Data Used
This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.
Below is the implementation.
import numpy as np import cv2 # Read the image image = cv2.imread( 'digits.png' ) # gray scale conversion gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # We will divide the image # into 5000 small dimensions # of size 20x20 divisions = list (np.hsplit(i, 100 ) for i in np.vsplit(gray_img, 50 )) # Convert into Numpy array # of size (50,100,20,20) NP_array = np.array(divisions) # Preparing train_data # and test_data. # Size will be (2500,20x20) train_data = NP_array[:,: 50 ].reshape( - 1 , 400 ).astype(np.float32) # Size will be (2500,20x20) test_data = NP_array[:, 50 : 100 ].reshape( - 1 , 400 ).astype(np.float32) # Create 10 different labels # for each type of digit k = np.arange( 10 ) train_labels = np.repeat(k, 250 )[:,np.newaxis] test_labels = np.repeat(k, 250 )[:,np.newaxis] # Initiate kNN classifier knn = cv2.ml.KNearest_create() # perform training of data knn.train(train_data, cv2.ml.ROW_SAMPLE, train_labels) # obtain the output from the # classifier by specifying the # number of neighbors. ret, output ,neighbours, distance = knn.findNearest(test_data, k = 3 ) # Check the performance and # accuracy of the classifier. # Compare the output with test_labels # to find out how many are wrong. matched = output = = test_labels correct_OP = np.count_nonzero(matched) #Calculate the accuracy. accuracy = (correct_OP * 100.0 ) / (output.size) # Display accuracy. print (accuracy) |
Output
91.64
Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).
1) My first question was about letter_recognition.data
file that comes with OpenCV samples. I wanted to know what is inside that file.
It contains a letter, along with 16 features of that letter.
And this SOF
helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers
.
(Although I didn't understand some of the features at the end)
2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.
So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)
I took the below image for my training data:
(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).
To prepare the data for training, I made a small code in OpenCV. It does the following things:
key press manually
. This time we press the digit key ourselves corresponding to the letter in the box..txt
files.At the end of the manual classification of digits, all the digits in the training data (train.png
) are labeled manually by ourselves, image will look like below:
Below is the code I used for the above purpose (of course, not so clean):
import sys
import numpy as np
import cv2
im = cv2.imread('pitrain.png')
im3 = im.copy()
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)
################# Now finding Contours ###################
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
samples = np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]
for cnt in contours:
if cv2.contourArea(cnt)>50:
[x,y,w,h] = cv2.boundingRect(cnt)
if h>28:
cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
roi = thresh[y:y+h,x:x+w]
roismall = cv2.resize(roi,(10,10))
cv2.imshow('norm',im)
key = cv2.waitKey(0)
if key == 27: # (escape to quit)
sys.exit()
elif key in keys:
responses.append(int(chr(key)))
sample = roismall.reshape((1,100))
samples = np.append(samples,sample,0)
responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"
np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)
Now we enter in to training and testing part.
For the testing part, I used the below image, which has the same type of letters I used for the training phase.
For training we do as follows:
.txt
files we already saved earlierFor testing purposes, we do as follows:
I included last two steps (training and testing) in single code below:
import cv2
import numpy as np
####### training part ###############
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))
model = cv2.KNearest()
model.train(samples,responses)
############################# testing part #########################
im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt)>50:
[x,y,w,h] = cv2.boundingRect(cnt)
if h>28:
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
roi = thresh[y:y+h,x:x+w]
roismall = cv2.resize(roi,(10,10))
roismall = roismall.reshape((1,100))
roismall = np.float32(roismall)
retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
string = str(int((results[0][0])))
cv2.putText(out,string,(x,y+h),0,1,(0,255,0))
cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)
And it worked, below is the result I got:
Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.
But anyway, this is a good start to go for beginners (I hope so).
There should be a line in your postgresql.conf
file that says:
port = 1486
Change that.
The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/
On Windows it is C:\Program Files\PostgreSQL\9.3\data
Don't forget to sudo service postgresql restart
for changes to take effect.
A simple answer in JQuery, I just created this code and thought it will be helpful for others too
var cont;
$("div [contenteditable=true]").focus(function() {
cont=$(this).html();
});
$("div [contenteditable=true]").blur(function() {
if ($(this).html()!=cont) {
//Here you can write the code to run when the content change
}
});
"Is there a definition of exactly what width:auto does mean? The CSS spec seems vague to me, but maybe I missed the relevant section."
No one actually answered the above part of the original poster's question.
Here's the answer: http://www.456bereastreet.com/archive/201112/the_difference_between_widthauto_and_width100/
As long as the value of width is auto, the element can have horizontal margin, padding and border without becoming wider than its container...
On the other hand, if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border... This may be what you want, but most likely it isn’t.
To visualise the difference I made an example: http://www.456bereastreet.com/lab/width-auto/
It depends on what you're looking for, if you need System.Windows.Media.Color (like in WPF) it's very easy:
System.Windows.Media.Color color = (Color)System.Windows.Media.ColorConverter.ConvertFromString("Red");//or hexadecimal color, e.g. #131A84
For angular JS you can find it on angular-animate.js file as below:
/** * @license AngularJS v1.4.8 * (c) 2010-2015 Google, Inc. http://angularjs.org * License: MIT */
$string="kalion/home/public_html";
$newstring=( stristr($string,"/")==FALSE ) ? $string : substr($string,0,stripos($string,"/"));
Installing Crontab on Ubuntu
sudo apt-get update
We download the crontab file to the root
wget https://pypi.python.org/packages/47/c2/d048cbe358acd693b3ee4b330f79d836fb33b716bfaf888f764ee60aee65/crontab-0.20.tar.gz
Unzip the file crontab-0.20.tar.gz
tar xvfz crontab-0.20.tar.gz
Login to a folder crontab-0.20
cd crontab-0.20*
Installation order
python setup.py install
See also here:.. http://www.syriatalk.im/crontab.html
To fix this issue in Web.config I just had to add debug="true"
<system.web>
<compilation targetFramework="4.0" debug="true">
What helped me to find this solution has been looking at the Modules windows while debugging and saw that for my ASP.NET DLLs loaded I had: Binary was not built with debug information.
The JavaScript function:
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};
To use this function:
capitalizedString = someString.toLowerCase().capitalize();
Also, this would work on multiple words string.
To make sure the converted City name is injected into the database, lowercased and first letter capitalized, then you would need to use JavaScript before you send it over to server side. CSS simply styles, but the actual data would remain pre-styled. Take a look at this jsfiddle example and compare the alert message vs the styled output.
When you go to a stream url, you get offered a file. feed this file to a parser to extract the contents out of it. the file is (usually) plain text and contains the url to play.
I'm actually updating this thread with a more recent 1-line solution:
let arr = ['A', 'B', 'C'];
arr = arr.filter(e => e !== 'B'); // will return ['A', 'C']
The idea is basically to filter the array by selecting all elements different to the element you want to remove.
Note: will remove all occurrences.
EDIT:
If you want to remove only the first occurence:
t = ['A', 'B', 'C', 'B'];
t.splice(t.indexOf('B'), 1); // will return ['B'] and t is now equal to ['A', 'C', 'B']
Like the comments suggest, the solution is to use nested spans/rows.
<div class="container">
<div class="row">
<div class="span4">1</div>
<div class="span8">
<div class="row">
<div class="span4">2</div>
<div class="span4">3</div>
</div>
<div class="row">
<div class="span4">4</div>
<div class="span4">5</div>
</div>
</div>
</div>
<div class="row">
<div class="span4">6</div>
<div class="span4">7</div>
<div class="span4">8</div>
</div>
</div>
Add a Console.ReadKey
call to your program to force it to wait for you to press a key before exiting.
I modified the class and the answers to the question and wrote a class that allows updating the database via DB_VERSION.
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_NAME = "info.db";
private static String DB_PATH = "";
private static final int DB_VERSION = 1;
private SQLiteDatabase mDataBase;
private final Context mContext;
private boolean mNeedUpdate = false;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
if (android.os.Build.VERSION.SDK_INT >= 17)
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
else
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
this.mContext = context;
copyDataBase();
this.getReadableDatabase();
}
public void updateDataBase() throws IOException {
if (mNeedUpdate) {
File dbFile = new File(DB_PATH + DB_NAME);
if (dbFile.exists())
dbFile.delete();
copyDataBase();
mNeedUpdate = false;
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() {
if (!checkDataBase()) {
this.getReadableDatabase();
this.close();
try {
copyDBFile();
} catch (IOException mIOException) {
throw new Error("ErrorCopyingDataBase");
}
}
}
private void copyDBFile() throws IOException {
InputStream mInput = mContext.getAssets().open(DB_NAME);
//InputStream mInput = mContext.getResources().openRawResource(R.raw.info);
OutputStream mOutput = new FileOutputStream(DB_PATH + DB_NAME);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0)
mOutput.write(mBuffer, 0, mLength);
mOutput.flush();
mOutput.close();
mInput.close();
}
public boolean openDataBase() throws SQLException {
mDataBase = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.CREATE_IF_NECESSARY);
return mDataBase != null;
}
@Override
public synchronized void close() {
if (mDataBase != null)
mDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion)
mNeedUpdate = true;
}
}
Using a class.
In the activity class, declare variables.
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
In the onCreate method, write the following code.
mDBHelper = new DatabaseHelper(this);
try {
mDBHelper.updateDataBase();
} catch (IOException mIOException) {
throw new Error("UnableToUpdateDatabase");
}
try {
mDb = mDBHelper.getWritableDatabase();
} catch (SQLException mSQLException) {
throw mSQLException;
}
If you add a database file to the folder res/raw then use the following modification of the class.
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_NAME = "info.db";
private static String DB_PATH = "";
private static final int DB_VERSION = 1;
private SQLiteDatabase mDataBase;
private final Context mContext;
private boolean mNeedUpdate = false;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
if (android.os.Build.VERSION.SDK_INT >= 17)
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
else
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
this.mContext = context;
copyDataBase();
this.getReadableDatabase();
}
public void updateDataBase() throws IOException {
if (mNeedUpdate) {
File dbFile = new File(DB_PATH + DB_NAME);
if (dbFile.exists())
dbFile.delete();
copyDataBase();
mNeedUpdate = false;
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() {
if (!checkDataBase()) {
this.getReadableDatabase();
this.close();
try {
copyDBFile();
} catch (IOException mIOException) {
throw new Error("ErrorCopyingDataBase");
}
}
}
private void copyDBFile() throws IOException {
//InputStream mInput = mContext.getAssets().open(DB_NAME);
InputStream mInput = mContext.getResources().openRawResource(R.raw.info);
OutputStream mOutput = new FileOutputStream(DB_PATH + DB_NAME);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0)
mOutput.write(mBuffer, 0, mLength);
mOutput.flush();
mOutput.close();
mInput.close();
}
public boolean openDataBase() throws SQLException {
mDataBase = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.CREATE_IF_NECESSARY);
return mDataBase != null;
}
@Override
public synchronized void close() {
if (mDataBase != null)
mDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion)
mNeedUpdate = true;
}
}
I assume you always want EntityId
to be the primary key, so replacing it by a composite key is not an option (if only because composite keys are far more complicated to work with and because it is not very sensible to have primary keys that also have meaning in the business logic).
The least you should do is create a unique key on both fields in the database and specifically check for unique key violation exceptions when saving changes.
Additionally you could (should) check for unique values before saving changes. The best way to do that is by an Any()
query, because it minimizes the amount of transferred data:
if (context.Entities.Any(e => e.FirstColumn == value1
&& e.SecondColumn == value2))
{
// deal with duplicate values here.
}
Beware that this check alone is never enough. There is always some latency between the check and the actual commit, so you'll always need the unique constraint + exception handling.
Old thread, I know. I needed also something to monitor events and wrote this very handy (excellent) solution. You can monitor all events with this hook (in windows programming this is called a hook). This hook does not affects the operation of your software/program.
In the console log you can see something like this:
Explanation of what you see:
In the console log you will see all events you select (see below "how to use") and shows the object-type, classname(s), id, <:name of function>, <:eventname>. The formatting of the objects is css-like.
When you click a button or whatever binded event, you will see it in the console log.
The code I wrote:
function setJQueryEventHandlersDebugHooks(bMonTrigger, bMonOn, bMonOff)
{
jQuery.fn.___getHookName___ = function()
{
// First, get object name
var sName = new String( this[0].constructor ),
i = sName.indexOf(' ');
sName = sName.substr( i, sName.indexOf('(')-i );
// Classname can be more than one, add class points to all
if( typeof this[0].className === 'string' )
{
var sClasses = this[0].className.split(' ');
sClasses[0]='.'+sClasses[0];
sClasses = sClasses.join('.');
sName+=sClasses;
}
// Get id if there is one
sName+=(this[0].id)?('#'+this[0].id):'';
return sName;
};
var bTrigger = (typeof bMonTrigger !== "undefined")?bMonTrigger:true,
bOn = (typeof bMonOn !== "undefined")?bMonOn:true,
bOff = (typeof bMonOff !== "undefined")?bMonOff:true,
fTriggerInherited = jQuery.fn.trigger,
fOnInherited = jQuery.fn.on,
fOffInherited = jQuery.fn.off;
if( bTrigger )
{
jQuery.fn.trigger = function()
{
console.log( this.___getHookName___()+':trigger('+arguments[0]+')' );
return fTriggerInherited.apply(this,arguments);
};
}
if( bOn )
{
jQuery.fn.on = function()
{
if( !this[0].__hooked__ )
{
this[0].__hooked__ = true; // avoids infinite loop!
console.log( this.___getHookName___()+':on('+arguments[0]+') - binded' );
$(this).on( arguments[0], function(e)
{
console.log( $(this).___getHookName___()+':'+e.type );
});
}
var uResult = fOnInherited.apply(this,arguments);
this[0].__hooked__ = false; // reset for another event
return uResult;
};
}
if( bOff )
{
jQuery.fn.off = function()
{
if( !this[0].__unhooked__ )
{
this[0].__unhooked__ = true; // avoids infinite loop!
console.log( this.___getHookName___()+':off('+arguments[0]+') - unbinded' );
$(this).off( arguments[0] );
}
var uResult = fOffInherited.apply(this,arguments);
this[0].__unhooked__ = false; // reset for another event
return uResult;
};
}
}
Examples how to use it:
Monitor all events:
setJQueryEventHandlersDebugHooks();
Monitor all triggers only:
setJQueryEventHandlersDebugHooks(true,false,false);
Monitor all ON events only:
setJQueryEventHandlersDebugHooks(false,true,false);
Monitor all OFF unbinds only:
setJQueryEventHandlersDebugHooks(false,false,true);
Remarks/Notice:
Hope it helps! ;-)
Try to specify the port in
conn = DriverManager.getConnection("jdbc:mysql://localhost/mysql?"
+ "user=root&password=onelife");
I think you should have something like this:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?"
+ "user=root&password=onelife");
Also, the port number in my example (3306) is the default port, but you may change it while installing MySQL.
I think that a better way to specify password and user is to separate them from the URL like this:
connection = DriverManager.getConnection(url, login, password);
I created dummy sample for Google Maps v2 Android with Kotlin and AndroidX
You can find complete project here: github-link
MainActivity.kt
class MainActivity : AppCompatActivity() {
val position = LatLng(-33.920455, 18.466941)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
with(mapView) {
// Initialise the MapView
onCreate(null)
// Set the map ready callback to receive the GoogleMap object
getMapAsync{
MapsInitializer.initialize(applicationContext)
setMapLocation(it)
}
}
}
private fun setMapLocation(map : GoogleMap) {
with(map) {
moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13f))
addMarker(MarkerOptions().position(position))
mapType = GoogleMap.MAP_TYPE_NORMAL
setOnMapClickListener {
Toast.makeText(this@MainActivity, "Clicked on map", Toast.LENGTH_SHORT).show()
}
}
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" package="com.murgupluoglu.googlemap">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="API_KEY_HERE" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.gms.maps.MapView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="@+id/mapView"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Correlated Subquery is a sub-query that uses values from the outer query. In this case the inner query has to be executed for every row of outer query.
See example here http://en.wikipedia.org/wiki/Correlated_subquery
Simple subquery doesn't use values from the outer query and is being calculated only once:
SELECT id, first_name
FROM student_details
WHERE id IN (SELECT student_id
FROM student_subjects
WHERE subject= 'Science');
CoRelated Subquery Example -
Query To Find all employees whose salary is above average for their department
SELECT employee_number, name
FROM employees emp
WHERE salary > (
SELECT AVG(salary)
FROM employees
WHERE department = emp.department);
I am on Android Studio 2.0 and facing the same problem. The solution provided by Rudy Kurniawan sorted out this issue. The affected file can be located by:
"Project" -> "Android" -> "Gradle Scripts" -> "build.gradle(Module:app)"
The "Project" pane is default on the left. To find it, inspect the name of the side tabs, click it, then use the top pull down box to get to "Android". Expand the tree in the pane to find the target file. Double-click it to edit.
I think you are trying to over complicate things. A simple solution is to just style your checkbox by default with the unchecked styles and then add the checked state styles.
input[type="checkbox"] {
// Unchecked Styles
}
input[type="checkbox"]:checked {
// Checked Styles
}
I apologize for bringing up an old thread but felt like it could have used a better answer.
EDIT (3/3/2016):
W3C Specs state that :not(:checked)
as their example for selecting the unchecked state. However, this is explicitly the unchecked state and will only apply those styles to the unchecked state. This is useful for adding styling that is only needed on the unchecked state and would need removed from the checked state if used on the input[type="checkbox"]
selector. See example below for clarification.
input[type="checkbox"] {
/* Base Styles aka unchecked */
font-weight: 300; // Will be overwritten by :checked
font-size: 16px; // Base styling
}
input[type="checkbox"]:not(:checked) {
/* Explicit Unchecked Styles */
border: 1px solid #FF0000; // Only apply border to unchecked state
}
input[type="checkbox"]:checked {
/* Checked Styles */
font-weight: 900; // Use a bold font when checked
}
Without using :not(:checked)
in the example above the :checked
selector would have needed to use a border: none;
to achieve the same affect.
Use the input[type="checkbox"]
for base styling to reduce duplication.
Use the input[type="checkbox"]:not(:checked)
for explicit unchecked styles that you do not want to apply to the checked state.
The problem you encounter comes from the lack of call to super.prepareForReuse()
.
Some other solutions above, suggesting to update the UI of the cell from the delegate's functions, are leading to a flawed design where the logic of the cell's behaviour is outside of its class. Furthermore, it's extra code that can be simply fixed by calling super.prepareForReuse()
. For example :
class myCell: UICollectionViewCell {
// defined in interface builder
@IBOutlet weak var viewSelection : UIView!
override var isSelected: Bool {
didSet {
self.viewSelection.alpha = isSelected ? 1 : 0
}
}
override func prepareForReuse() {
// Do whatever you want here, but don't forget this :
super.prepareForReuse()
// You don't need to do `self.viewSelection.alpha = 0` here
// because `super.prepareForReuse()` will update the property `isSelected`
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.viewSelection.alpha = 0
}
}
With such design, you can even leave the delegate's functions collectionView:didSelectItemAt:
/collectionView:didDeselectItemAt:
all empty, and the selection process will be totally handled, and behave properly with the cells recycling.
I see quite a few things wrong. For starters, you don't have your magic button defined and there is no event handler for it.
Also you shouldn't use:
dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
Use only one of the two. From Android documentation:
View.GONE This view is invisible, and it doesn't take any space for layout purposes.
View.INVISIBLE This view is invisible, but it still takes up space for layout purposes.
In your example, you are overriding the View.GONE
assignment with the View.INVISIBLE
one.
Try replacing:
final DatePicker dp2 = new DatePicker(this)
with:
DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
Similarly for other widgets:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
final DatePicker dp2 = new DatePicker(this);
final Button btn2 = new Button(this);
final Button magicButton = new Button(this);
final TextView txt2 = new TextView(TestActivity.this);
dp2.setVisibility(View.GONE);
btn2.setVisibility(View.GONE);
btn2.setText("set Date");
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
txt2.setText("You selected "
+ dp2.getDayOfMonth() + "/" + (dp2.getMonth() + 1)
+ "/" + dp2.getYear());
}
});
magicButton.setText("Magic Button");
magicButton.setOnClickListener(new View.OnClickListener()
public void onClick(View arg0) {
dp2.setVisibility(View.VISIBLE);
btn2.setVisibility(View.VISIBLE);
}
});
ll.addView(dp2);
ll.addView(btn2);
ll.addView(magicButton);
ll.addView(txt2);
setContentView(ll);
}
There is a way to do this without using a pipe character, which is convenient if you are forking a process from another programming language to do this:
find $JAVA_SRC_DIR -name '*.java' -exec javac -d $OUTPUT_DIR {} +
Though if you are in Bash and/or don't mind using a pipe, then you can do:
find $JAVA_SRC_DIR -name '*.java' | xargs javac -d $OUTPUT_DIR
Auth::id()
, likePost::create([ 'body' => request('body'), 'title' => request('title'), 'user_id' => Auth::id()]);
also remember to include Auth facade at top of your controller which is App\Http\Controllers\Auth
You can create the radio buttons dynamically, ListBox
can help you do that, without converters, quite simple.
The concrete steps are below:
MyLovelyEnum
and binding the SelectedItem of the ListBox to the VeryLovelyEnum
property. <Window.Resources>
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type system:Enum}"
x:Key="MyLovelyEnum">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:MyLovelyEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
Control Template
to populate each item inside as Radio button <ListBox ItemsSource="{Binding Source={StaticResource MyLovelyEnum}}" SelectedItem="{Binding VeryLovelyEnum, Mode=TwoWay}" >
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<RadioButton
Content="{TemplateBinding ContentPresenter.Content}"
IsChecked="{Binding Path=IsSelected,
RelativeSource={RelativeSource TemplatedParent},
Mode=TwoWay}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
The advantage is: if someday your enum class changes, you do not need to update the GUI (XAML file).
References: https://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/
I've managed to bind a custom model to an element at runtime. The code is here: http://jsfiddle.net/ZiglioNZ/tzD4T/457/
The interesting bit is that I apply the data-bind attribute to an element I didn't define:
var handle = slider.slider().find(".ui-slider-handle").first();
$(handle).attr("data-bind", "tooltip: viewModel.value");
ko.applyBindings(viewModel.value, $(handle)[0]);
Run ./mnistCUDNN
in /usr/src/cudnn_samples_v7/mnistCUDNN
Here is an example:
cudnnGetVersion() : 7005 , CUDNN_VERSION from cudnn.h : 7005 (7.0.5)
Host compiler version : GCC 5.4.0
There are 1 CUDA capable devices on your machine :
device 0 : sms 30 Capabilities 6.1, SmClock 1645.0 Mhz, MemSize (Mb) 24446, MemClock 4513.0 Mhz, Ecc=0, boardGroupID=0
Using device 0
Maybe map the share as a network drive and then do
git clone Z:\
Mostly just a guess; I always do this stuff using ssh. Following that suggstion of course will mean that you'll need to have that drive mapped every time you push/pull to/from the laptop. I'm not sure how you rig up ssh to work under windows but if you're going to be doing this a lot it might be worth investigating.
Took this from JeffK and made it a little more compact.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Newline As String = System.Environment.NewLine
TextBox1.Text = "This is a test"
TextBox1.Text += Newline + "This is another test"
End Sub
In your activity class use the method below :
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setlogo();// Your Method
Log.d("Daiya", "ORIENTATION_LANDSCAPE");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
setlogoForLandScape();// Your Method
Log.d("Daiya", "ORIENTATION_PORTRAIT");
}
}
Then to declare that your activity handles a configuration change, edit the appropriate element in your manifest file to include the android:configChanges
attribute with a value that represents the configuration you want to handle. Possible values are listed in the documentation for the android:configChanges
attribute (the most commonly used values are "orientation" to prevent restarts when the screen orientation changes and "keyboardHidden" to prevent restarts when the keyboard availability changes). You can declare multiple configuration values in the attribute by separating them with a pipe | character.
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
That's all!!
I found the solution by myself. Suppose you have the CSS below:
.parent {
align-items: center;
display: flex;
justify-content: center;
}
.child {
height: 100%; <- didn't work
}
In this case, setting the height 100% will not work, so I set the margin-bottom
rule to auto
, like:
.child {
margin-bottom: auto;
}
And the child will be aligned to the topmost of the parent.
You can also use the align-self
rule anyway if you prefer:
.child {
align-self: flex-start;
}
To access properties and methods of a parent class use the base
keyword. So in your child class LoadData()
method you would do this:
public class Child : Parent
{
public void LoadData()
{
base.MyMethod(); // call method of parent class
base.CurrentRow = 1; // set property of parent class
// other stuff...
}
}
Note that you would also have to change the access modifier of your parent MyMethod()
to at least protected
for the child class to access it.
This is what ended up working.
$("select").change(function(){
$.get("/page.html?" + $(this).parent("form").find(":input").serialize());
});
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
Since the img is an inline element, Just use text-center
on it's container. Using mx-auto
will center the container (column) too.
<div class="row">
<div class="col-4 mx-auto text-center">
<img src="..">
</div>
</div>
By default, images are display:inline
. If you only want the center the image (and not the other column content), make the image display:block
using the d-block
class, and then mx-auto
will work.
<div class="row">
<div class="col-4">
<img class="mx-auto d-block" src="..">
</div>
</div>
How about this? There's no need for key codes (at least in Lion, not sure about earlier), and a subroutine simplifies the main script.
The below script will ssh to localhost as user "me", enter password "myPassw0rd" after a 1 second delay, issue ls, delay 2 seconds, and then exit.
tell application "Terminal"
activate
my execCmd("ssh me@localhost", 1)
my execCmd("myPassw0rd", 0)
my execCmd("ls", 2)
my execCmd("exit", 0)
end tell
on execCmd(cmd, pause)
tell application "System Events"
tell application process "Terminal"
set frontmost to true
keystroke cmd
keystroke return
end tell
end tell
delay pause
end execCmd
You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.
$fh = fopen("employees.txt", "r"); if ($fh) { while (($line = fgets($fh)) !== false) { $line = trim($line); echo "<option value='".$line."'>".$line."</option>"; } } else { // error opening the file, do something }
Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?
And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.
Okay, here are the explanations.
e.keyCode - used to get the number that represents the key on the keyboard
e.charCode - a number that represents the unicode character of the key on keyboard
e.which - (jQuery specific) is a property introduced in jQuery (DO Not use in plain javascript)
Below is the code snippet to get the keyCode and charCode
<script>
// get key code
function getKey(event) {
event = event || window.event;
var keyCode = event.which || event.keyCode;
alert(keyCode);
}
// get char code
function getChar(event) {
event = event || window.event;
var keyCode = event.which || event.keyCode;
var typedChar = String.fromCharCode(keyCode);
alert(typedChar);
}
</script>
Live example of Getting keyCode and charCode in JavaScript.
Try using Web API HttpClient
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://domain.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var obj = new MyObject() { Str = "MyString"};
response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
if (response.IsSuccessStatusCode)
{
response.//.. Contains the returned content.
}
}
}
You can find more details here Web API Clients
function numberToEnglish( n ) {
var string = n.toString(), units, tens, scales, start, end, chunks, chunksLen, chunk, ints, i, word, words, and = 'and';
/* Remove spaces and commas */
string = string.replace(/[, ]/g,"");
/* Is number zero? */
if( parseInt( string ) === 0 ) {
return 'zero';
}
/* Array of units as words */
units = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ];
/* Array of tens as words */
tens = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ];
/* Array of scales as words */
scales = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quatttuor-decillion', 'quindecillion', 'sexdecillion', 'septen-decillion', 'octodecillion', 'novemdecillion', 'vigintillion', 'centillion' ];
/* Split user argument into 3 digit chunks from right to left */
start = string.length;
chunks = [];
while( start > 0 ) {
end = start;
chunks.push( string.slice( ( start = Math.max( 0, start - 3 ) ), end ) );
}
/* Check if function has enough scale words to be able to stringify the user argument */
chunksLen = chunks.length;
if( chunksLen > scales.length ) {
return '';
}
/* Stringify each integer in each chunk */
words = [];
for( i = 0; i < chunksLen; i++ ) {
chunk = parseInt( chunks[i] );
if( chunk ) {
/* Split chunk into array of individual integers */
ints = chunks[i].split( '' ).reverse().map( parseFloat );
/* If tens integer is 1, i.e. 10, then add 10 to units integer */
if( ints[1] === 1 ) {
ints[0] += 10;
}
/* Add scale word if chunk is not zero and array item exists */
if( ( word = scales[i] ) ) {
words.push( word );
}
/* Add unit word if array item exists */
if( ( word = units[ ints[0] ] ) ) {
words.push( word );
}
/* Add tens word if array item exists */
if( ( word = tens[ ints[1] ] ) ) {
words.push( word );
}
/* Add 'and' string after units or tens integer if: */
if( ints[0] || ints[1] ) {
/* Chunk has a hundreds integer or chunk is the first of multiple chunks */
if( ints[2] || ! i && chunksLen ) {
words.push( and );
}
}
/* Add hundreds word if array item exists */
if( ( word = units[ ints[2] ] ) ) {
words.push( word + ' hundred' );
}
}
}
return words.reverse().join( ' ' );
}
// - - - - - Tests - - - - - -
function test(v) {
var sep = ('string'==typeof v)?'"':'';
console.log("numberToEnglish("+sep + v.toString() + sep+") = "+numberToEnglish(v));
}
test(2);
test(721);
test(13463);
test(1000001);
test("21,683,200,000,621,384");
_x000D_
The other answer below by Eric is wrong. The namespace declaration he mentioned had nothing to do with the problem.
The real reason it doesn't work is due to security concerns (cf. issue 4197, issue 111905).
Imagine this scenario:
You receive an email message from an attacker containing a web page as an attachment, which you download.
You open the now-local web page in your browser.
The local web page creates an <iframe>
whose source is https://mail.google.com/mail/.
Because you are logged in to Gmail, the frame loads the messages in your inbox.
The local web page reads the contents of the frame by using JavaScript to access frames[0].document.documentElement.innerHTML
. (An online web page would not be able to perform this step because it would come from a non-Gmail origin; the same-origin policy would cause the read to fail.)
The local web page places the contents of your inbox into a <textarea>
and submits the data via a form POST to the attacker's web server. Now the attacker has your inbox, which may be useful for spamming or identify theft.
Chrome foils the above scenario by putting restrictions on local files opened using Chrome. To overcome these restrictions, we've got two solutions:
Try running Chrome with the --allow-file-access-from-files
flag. I've not tested this myself, but if it works, your system will now also be vulnerable to scenarios of the kind mentioned above.
Upload it to a host, and problem solved.
When i modify the font size in Tools-> Options->Fonts & Colors->Syntax
to 14, the Editor font change fine, but Netbeans doesn´t take any change in fontsize IDE (icons, menus, ...) until i Add the --fontsize XX
option in the file ...\NetBeans x.x\etc\netbeans.conf at the end of line netbeans_default_options
AND set to true the already added option -J-Dsun.java2d.dpiaware
, But i had to increase the font size Editor to 24. Thats works for me.
On your project folder, open up the bin\Debug subfolder and you'll see the compiled result.
XAMPP comes preloaded with the FileZilla FTP server. Here is how to setup the service, and create an account.
Enable the FileZilla FTP Service through the XAMPP Control Panel to make it startup automatically (check the checkbox next to filezilla to install the service). Then manually start the service.
Create an ftp account through the FileZilla Server Interface (its the essentially the filezilla control panel). There is a link to it Start Menu in XAMPP folder. Then go to Users->Add User->Stuff->Done.
Try connecting to the server (localhost, port 21).
If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.
If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:
private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
CookieContainer cookieContainer,
string userAgent, string acceptHeaderString,
string referer,
string contentType, out string responseUri)
{
var result = "";
if (!string.IsNullOrEmpty(requestUri))
{
var request = WebRequest.Create(requestUri) as HttpWebRequest;
if (request != null)
{
request.KeepAlive = true;
var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
request.CachePolicy = cachePolicy;
request.Expect = null;
if (!string.IsNullOrEmpty(method))
request.Method = method;
if (!string.IsNullOrEmpty(acceptHeaderString))
request.Accept = acceptHeaderString;
if (!string.IsNullOrEmpty(referer))
request.Referer = referer;
if (!string.IsNullOrEmpty(contentType))
request.ContentType = contentType;
if (!string.IsNullOrEmpty(userAgent))
request.UserAgent = userAgent;
if (cookieContainer != null)
request.CookieContainer = cookieContainer;
request.Timeout = Constants.RequestTimeOut;
if (request.Method == "POST")
{
if (postData != null)
{
request.ContentLength = postData.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
}
}
}
using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
{
if (httpWebResponse != null)
{
responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
cookieContainer.Add(httpWebResponse.Cookies);
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
}
}
responseUri = null;
return null;
}
I think you cant remove column names, only reset them by range
with shape
:
print df.shape[1]
2
print range(df.shape[1])
[0, 1]
df.columns = range(df.shape[1])
print df
0 1
0 23 12
1 21 44
2 98 21
This is same as using to_csv
and read_csv
:
print df.to_csv(header=None,index=False)
23,12
21,44
98,21
print pd.read_csv(io.StringIO(u""+df.to_csv(header=None,index=False)), header=None)
0 1
0 23 12
1 21 44
2 98 21
Next solution with skiprows
:
print df.to_csv(index=False)
A,B
23,12
21,44
98,21
print pd.read_csv(io.StringIO(u""+df.to_csv(index=False)), header=None, skiprows=1)
0 1
0 23 12
1 21 44
2 98 21
toolbar.setLogo(resize(logo, (int) Float.parseFloat(mContext.getResources().getDimension(R.dimen._120sdp) + ""), (int) Float.parseFloat(mContext.getResources().getDimension(R.dimen._35sdp) + "")));
public Drawable resize(Drawable image, int width, int height)
{
Bitmap b = ((BitmapDrawable) image).getBitmap();
Bitmap bitmapResized = Bitmap.createScaledBitmap(b, width, height, false);
return new BitmapDrawable(getResources(), bitmapResized);
}
The known problem with the templates is code bloating, which is consequence of generating the class definition in each and every module which invokes the class template specialization. To prevent this, starting with C++0x, one could use the keyword extern in front of the class template specialization
#include <MyClass>
extern template class CMyClass<int>;
The explicit instantion of the template class should happen only in a single translation unit, preferable the one with template definition (MyClass.cpp)
template class CMyClass<int>;
template class CMyClass<float>;
You'll have to do 2 things to make a Bootstrap label (or anything really) adjust sizes based on screen size:
.label { font-size: 75% }
. So any extra selector on your CSS rule will make it more specific.Here's an example CSS listing to accomplish what you are asking, using the default 4 sizes in Bootstrap:
@media (max-width: 767) {
/* your custom css class on a parent will increase specificity */
/* so this rule will override Bootstrap's font size setting */
.autosized .label { font-size: 14px; }
}
@media (min-width: 768px) and (max-width: 991px) {
.autosized .label { font-size: 16px; }
}
@media (min-width: 992px) and (max-width: 1199px) {
.autosized .label { font-size: 18px; }
}
@media (min-width: 1200px) {
.autosized .label { font-size: 20px; }
}
Here is how it could be used in the HTML:
<!-- any ancestor could be set to autosized -->
<div class="autosized">
...
...
<span class="label label-primary">Label 1</span>
</div>
You can also just search on sites like Tucows and CNET, they have it there too.
<?php
$username="root";
$password="";
$database="test";
#get the data from form fields
$Id=$_POST['Id'];
$P_name=$_POST['P_name'];
$address1=$_POST['address1'];
$address2=$_POST['address2'];
$email=$_POST['email'];
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die("unable to select database");
if($_POST['insertrecord']=="insert"){
$query="insert into person values('$Id','$P_name','$address1','$address2','$email')";
echo "inside";
mysql_query($query);
$query1="select * from person";
$result=mysql_query($query1);
$num= mysql_numrows($result);
#echo"<b>output</b>";
print"<table border size=1 >
<tr><th>Id</th>
<th>P_name</th>
<th>address1</th>
<th>address2</th>
<th>email</th>
</tr>";
$i=0;
while($i<$num)
{
$Id=mysql_result($result,$i,"Id");
$P_name=mysql_result($result,$i,"P_name");
$address1=mysql_result($result,$i,"address1");
$address2=mysql_result($result,$i,"address2");
$email=mysql_result($result,$i,"email");
echo"<tr><td>$Id</td>
<td>$P_name</td>
<td>$address1</td>
<td>$address2</td>
<td>$email</td>
</tr>";
$i++;
}
print"</table>";
}
if($_POST['searchdata']=="Search")
{
$P_name=$_POST['name'];
$query="select * from person where P_name='$P_name'";
$result=mysql_query($query);
print"<table border size=1><tr><th>Id</th>
<th>P_name</th>
<th>address1</th>
<th>address2</th>
<th>email</th>
</tr>";
while($row=mysql_fetch_array($result))
{
$Id=$row[Id];
$P_name=$row[P_name];
$address1=$row[address1];
$address2=$row[address2];
$email=$row[email];
echo"<tr><td>$Id</td>
<td>$P_name</td>
<td>$address1</td>
<td>$address2</td>
<td>$email</td>
</tr>";
}
echo"</table>";
}
echo"<a href=lab2.html> Back </a>";
?>
Finally I found solution in Spring Docs:
To completely disable the use of file extensions, you must set both of the following:
useSuffixPatternMatching(false), see PathMatchConfigurer favorPathExtension(false), see ContentNegotiationConfigurer
Adding this to my WebMvcConfigurerAdapter
implementation solved the problem:
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
@Override
public void configurePathMatch(PathMatchConfigurer matcher) {
matcher.setUseSuffixPatternMatch(false);
}
It will be better if you try to call the new method inside you subscribe
this._reportService.getReport()
.subscribe((data: any) => {
this.downloadFile(data);
},
(error: any) => ?onsole.log(error),
() => console.log('Complete')
);
Inside downloadFile(data)
function we need to make block, link, href and file name
downloadFile(data: any, type: number, name: string) {
const blob = new Blob([data], {type: 'text/csv'});
const dataURL = window.URL.createObjectURL(blob);
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
return;
}
const link = document.createElement('a');
link.href = dataURL;
link.download = 'export file.csv';
link.click();
setTimeout(() => {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(dataURL);
}, 100);
}
}
From another answer:
A little history
Remember, there is nothing inherently special about $
. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing document.getElementById
. Should I capital 'b'
of 'by'
? Should I capital 'i'
of Id?
You get the drift. Because functions are first-class citizens in JavaScript, you can always do this:
var $ = document.getElementById; //freedom from document.getElementById!
When Prototype library arrived, they named their function, which gets the DOM elements, as '$'
. Almost all the JavaScript libraries copied this idea. Prototype also introduced a $$
function to select elements using CSS selector.
jQuery also adapted $
function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$'
could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)
Declare the array size will solve your problem
String[] title = {
"Abundance",
"Anxiety",
"Bruxism",
"Discipline",
"Drug Addiction"
};
String urlbase = "http://www.somewhere.com/data/";
String imgSel = "/logo.png";
String[] mStrings = new String[title.length];
for(int i=0;i<title.length;i++) {
mStrings[i] = urlbase + title[i].toLowerCase() + imgSel;
System.out.println(mStrings[i]);
}
UPDATE TABLE
SET EndDate = CAST('2017-12-31' AS DATE)
WHERE Id = '123'
SQL Server 2008 has a type called datetimeoffset
. It's really useful for this type of stuff.
http://msdn.microsoft.com/en-us/library/bb630289.aspx
Then you can use the function SWITCHOFFSET
to move it from one timezone to another, but still keeping the same UTC value.
http://msdn.microsoft.com/en-us/library/bb677244.aspx
Rob
Matrix Multiplication in pure python.
def matmult(m1,m2):
r=[]
m=[]
for i in range(len(m1)):
for j in range(len(m2[0])):
sums=0
for k in range(len(m2)):
sums=sums+(m1[i][k]*m2[k][j])
r.append(sums)
m.append(r)
r=[]
return m
Use the same DBContext object throughout the transaction.
I believe you have to reference bootstrap.js before bootstrap-datepicker.js
In order to calculate the difference you have to put the +
operator,
that way typescript
converts the dates to numbers.
+new Date()- +new Date("2013-02-20T12:01:04.753Z")
From there you can make a formula to convert the difference to minutes
or hours
.
Failure [INSTALL_FAILED_OLDER_SDK]
basically means that the installation has failed due to the target location (AVD/Device) having an older SDK version than the targetSdkVersion
specified in your app.
FROM
apply plugin: 'com.android.application'
android {
compileSdkVersion 'L' //Avoid String change to 20 without quotes
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "com.vahe_muradyan.notes"
minSdkVersion 8
targetSdkVersion 'L' //Set your correct Target which is 17 for Android 4.2.2
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:19.+' // Avoid Generalization
// can lead to dependencies issues remove +
}
TO
apply plugin: 'com.android.application'
android {
compileSdkVersion 20
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "com.vahe_muradyan.notes"
minSdkVersion 8
targetSdkVersion 17
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:19.0.0'
}
This is common error from eclipse to now Android Studio 0.8-.8.6
Things to avoid in Android Studio (As for now)
You can use the WooCommerce Layered Nav widget, which allows you to use different sets of attributes as filters for products. Here's the "official" description:
Shows a custom attribute in a widget which lets you narrow down the list of products when viewing product categories.
If you look into plugins/woocommerce/widgets/widget-layered_nav.php, you can see the way it operates with the attributes in order to set filters. The URL then looks like this:
... and the digits are actually the id-s of the different attribute values, that you want to set.
split
returns an Iterator
, which you can convert into a Vec
using collect
: split_line.collect::<Vec<_>>()
. Going through an iterator instead of returning a Vec
directly has several advantages:
split
is lazy. This means that it won't really split the line until you need it. That way it won't waste time splitting the whole string if you only need the first few values: split_line.take(2).collect::<Vec<_>>()
, or even if you need only the first value that can be converted to an integer: split_line.filter_map(|x| x.parse::<i32>().ok()).next()
. This last example won't waste time attempting to process the "23.0" but will stop processing immediately once it finds the "1".split
makes no assumption on the way you want to store the result. You can use a Vec
, but you can also use anything that implements FromIterator<&str>
, for example a LinkedList
or a VecDeque
, or any custom type that implements FromIterator<&str>
.Try this:
<img v-bind:src="'/media/avatars/' + joke.avatar" />
Don't forget single quote around your path string. also in your data check you have correctly defined image variable.
joke: {
avatar: 'image.jpg'
}
A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output
After trying out both of the top two suggestions, I've settled on a shady-looking middle route for Python 2.7. Maybe 3 is saner, but for me:
class MyDict(MutableMapping):
# ... the few __methods__ that mutablemapping requires
# and then this monstrosity
@property
def __class__(self):
return dict
which I really hate, but seems to fit my needs, which are:
**my_dict
dict
, this bypasses your code. try it out.isinstance(my_dict, dict)
dict
If you need to tell yourself apart from others, personally I use something like this (though I'd recommend better names):
def __am_i_me(self):
return True
@classmethod
def __is_it_me(cls, other):
try:
return other.__am_i_me()
except Exception:
return False
As long as you only need to recognize yourself internally, this way it's harder to accidentally call __am_i_me
due to python's name-munging (this is renamed to _MyDict__am_i_me
from anything calling outside this class). Slightly more private than _method
s, both in practice and culturally.
So far I have no complaints, aside from the seriously-shady-looking __class__
override. I'd be thrilled to hear of any problems that others encounter with this though, I don't fully understand the consequences. But so far I've had no problems whatsoever, and this allowed me to migrate a lot of middling-quality code in lots of locations without needing any changes.
As evidence: https://repl.it/repls/TraumaticToughCockatoo
Basically: copy the current #2 option, add print 'method_name'
lines to every method, and then try this and watch the output:
d = LowerDict() # prints "init", or whatever your print statement said
print '------'
splatted = dict(**d) # note that there are no prints here
You'll see similar behavior for other scenarios. Say your fake-dict
is a wrapper around some other datatype, so there's no reasonable way to store the data in the backing-dict; **your_dict
will be empty, regardless of what every other method does.
This works correctly for MutableMapping
, but as soon as you inherit from dict
it becomes uncontrollable.
Edit: as an update, this has been running without a single issue for almost two years now, on several hundred thousand (eh, might be a couple million) lines of complicated, legacy-ridden python. So I'm pretty happy with it :)
Edit 2: apparently I mis-copied this or something long ago. @classmethod __class__
does not work for isinstance
checks - @property __class__
does: https://repl.it/repls/UnitedScientificSequence
Some social tools like Google+ use a simple method to get a favicon for external links, fetching http://your.domainname.com/favicon.ico
Since they don't prefetch the HTML content, the <link>
tag will not work. In this case, you might want to use a mod_rewrite rule or just place the file in the default location.
Turned out there was some extra code in the AppModel that was messing things up:
in beforeFind
and afterFind
:
App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");
I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.
Update: Disabling the href works better in the link function return. Code below has been updated.
aDisabled
naturally executes before ngClick
because directives are sorted in alphabetical order. When aDisabled
is renamed to tagDisabled
, the directive does not work.
To "disable" the "a" tag, I'd want the following things:
href
links not to be followed when clickedngClick
events not to fire when clickeddisabled
classThis directive does this by mimicking the ngDisabled directive. Based on the value of a-disabled
directive, all of the above features are toggled.
myApp.directive('aDisabled', function() {
return {
compile: function(tElement, tAttrs, transclude) {
//Disable ngClick
tAttrs["ngClick"] = "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")";
//return a link function
return function (scope, iElement, iAttrs) {
//Toggle "disabled" to class when aDisabled becomes true
scope.$watch(iAttrs["aDisabled"], function(newValue) {
if (newValue !== undefined) {
iElement.toggleClass("disabled", newValue);
}
});
//Disable href on click
iElement.on("click", function(e) {
if (scope.$eval(iAttrs["aDisabled"])) {
e.preventDefault();
}
});
};
}
};
});
Here is a css style that might indicate a disabled tag:
a.disabled {
color: #AAAAAA;
cursor: default;
pointer-events: none;
text-decoration: none;
}
Some of the code looks a bit complex to me. This is very simple code to select only the used rows in two discontiguous columns D and H. It presumes the columns are of unequal length and thus more flexible vs if the columns were of equal length.
As you most likely surmised 4=column D and 8=column H
Dim dlastRow As Long
Dim hlastRow As Long
dlastRow = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
hlastRow = ActiveSheet.Cells(Rows.Count, 8).End(xlUp).Row
Range("D2:D" & dlastRow & ",H2:H" & hlastRow).Select
Hope you find useful - DON'T FORGET THAT COMMA BEFORE THE SECOND COLUMN, AS I DID, OR IT WILL BOMB!!
Java ArrayList
has an indexOf
method. Java arrays have no such method.
You are not creating datetime index properly,
format = '%Y-%m-%d %H:%M:%S'
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format=format)
df = df.set_index(pd.DatetimeIndex(df['Datetime']))
A workspace is a collection of projects. It's useful to organize your projects when there's correlation between them (e.g.: Project A includes a library, that is provided as a project itself as project B. When you build the workspace project B is compiled and linked in project A).
It's common to use a workspace in the popular CocoaPods. When you install your pods, they are placed inside a workspace, that holds your project and the pod libraries.
$model=User::where('id',$id)->delete();
My favourite has always been gnuplot. It's very extensive, so it might be a bit too complex for your needs though. It is cross-platform and there is a C++ API.
node-gyp requires old Python 2 - link
If you don't have it installed - check other answers about installing windows-build-tools.
If you are like me and have both old and new Python versions installed, chances are that node-gyp tries to use Python 3. And that results in the following SyntaxError: invalid syntax
error.
I found an article about having two Python versions installed. And they recommend renaming Python 2.* executable to python2.exe
- link.
So it looks like node-gyp is expecting to find old Python 2 executable renamed. Hence the error message:
...
gyp verb check python checking for Python executable "python2" in the PATH
gyp verb `which` failed Error: not found: python2
...
Once I renamed C:\Python27\python.exe
to C:\Python27\python2.exe
it worked without errors.
Of course, both C:\Python27\
and C:\Python39\
have to be in PATH variable. And no need in setting old Python version in npm config. Your default Python still will be the new one.
If you desire to use Python 3, you can use the following:
import json
import urllib.request
req = urllib.request.Request('url')
with urllib.request.urlopen(req) as response:
result = json.loads(response.readall().decode('utf-8'))
String jsonInput = "{ \"hi\": \"Assume this is the JSON\"} ";
com.fasterxml.jackson.databind.ObjectMapper mapper =
new com.fasterxml.jackson.databind.ObjectMapper();
MyClass myObject = objectMapper.readValue(jsonInput, MyClass.class);
If your JSON input in has more properties than your POJO has and you just want to ignore the extras in Jackson 2.4, you can configure your ObjectMapper as follows. This syntax is different from older Jackson versions. (If you use the wrong syntax, it will silently do nothing.)
mapper.disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNK??NOWN_PROPERTIES);
In Windows-Pycharm: If File Location|Path contains any string like \t
then need to escape that with additional \
like \\t
Here's a handy site to test out your headers. You can see your browser headers and also use cURL to reflect back whatever headers you send.
For example, you can validate the content negotiation like this.
This Accept
header prefers plain text so returns in that format:-
$ curl -H "Accept: application/json;q=0.9,text/plain" http://gethttp.info/Accept
application/json;q=0.9,text/plain
Whereas this one prefers JSON and so returns in that format:-
$ curl -H "Accept: application/json,text/*;q=0.99" http://gethttp.info/Accept
{
"Accept": "application/json,text/*;q=0.99"
}
<html>
<head>
<script src='https://surikov.github.io/webaudiofont/npm/dist/WebAudioFontPlayer.js'></script>
<script src='https://surikov.github.io/webaudiofontdata/sound/0000_JCLive_sf2_file.js'></script>
<script>
var selectedPreset=_tone_0000_JCLive_sf2_file;
var AudioContextFunc = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContextFunc();
var player=new WebAudioFontPlayer();
player.loader.decodeAfterLoading(audioContext, '_tone_0000_JCLive_sf2_file');
</script>
</head>
<body>
<p><a href="#" onmousedown="player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, 0, 55, 3.5);">Play a note</a></p>
<hr/>
<p><a href="https://github.com/surikov/webaudiofont">source</a></p>
</body>
listen here https://jsbin.com/lamidog/1/edit?html,output
The most important use case is probably exception checking.
While junit4 includes the expected element for checking if an exception occurred, it seems like it isn't part of the newer junit5. Another advantage of using fail()
over the expected
is that you can combine it with finally
allowing test-case cleanup.
dao.insert(obj);
try {
dao.insert(obj);
fail("No DuplicateKeyException thrown.");
} catch (DuplicateKeyException e) {
assertEquals("Error code doesn't match", 123, e.getErrorCode());
} finally {
//cleanup
dao.delete(obj);
}
As noted in another comment. Having a test to fail until you can finish implementing it sounds reasonable as well.
String source = "24/10/17";
String[] sourceSplit= source.split("/");
int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(anno,mese-1,giorno);
Date data1= calendar.getTime();
SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");
String dayFormatted= myFormat.format(data1);
System.out.println("data formattata,-->"+dayFormatted);
Neither of these options is correct. You're trying to implement a synchronous interface asynchronously. Don't do that. The problem is that when DoOperation()
returns, the operation won't be complete yet. Worse, if an exception happens during the operation (which is very common with IO operations), the user won't have a chance to deal with that exception.
What you need to do is to modify the interface, so that it is asynchronous:
interface IIO
{
Task DoOperationAsync(); // note: no async here
}
class IOImplementation : IIO
{
public async Task DoOperationAsync()
{
// perform the operation here
}
}
This way, the user will see that the operation is async
and they will be able to await
it. This also pretty much forces the users of your code to switch to async
, but that's unavoidable.
Also, I assume using StartNew()
in your implementation is just an example, you shouldn't need that to implement asynchronous IO. (And new Task()
is even worse, that won't even work, because you don't Start()
the Task
.)
Any time you cannot have iterators invalidated.
There is a project called Locutus, it implements PHP functions in Javascript and in_array() is included, you can use it exactly as you use in PHP.
Examples of use:
in_array('van', myArray);
in_array(1, otherArray, true); // Forcing strict type
The Android resource linking failed error can also appear if you have an error in any of your XML resources. In my case I was using the following line twice in one of my XML drawables in drawable folder:
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
I removed the duplicate line and the error disappeared. The error was a bit misleading:
Android resource linking failed Output: /Users/johndoe/Desktop/myapp/app/src/main/res/layout/activity_main.xml:2: error: resource drawable/bg_main (aka com.example.myproject:drawable/bg_main) not found.
According to the above error, the first thing you need to do is to proof read all the drawable resources that are accessed in the activity_main because the chances are higher that you will find the error. In the worst case scenario you might end up checking all your resource files.
<?php
function getBetween($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
?>
Example:
<?php
$content = "Try to find the guy in the middle with this function!";
$start = "Try to find ";
$end = " with this function!";
$output = getBetween($content,$start,$end);
echo $output;
?>
This will return "the guy in the middle".
Here is what i tried to do to add parameter in the url which contain the specific character in the url.
jQuery('a[href*="google.com"]').attr('href', function(i,href) {
//jquery date addition
var requiredDate = new Date();
var numberOfDaysToAdd = 60;
requiredDate.setDate(requiredDate.getDate() + numberOfDaysToAdd);
//var convertedDate = requiredDate.format('d-M-Y');
//var newDate = datepicker.formatDate('yy/mm/dd', requiredDate );
//console.log(requiredDate);
var month = requiredDate.getMonth()+1;
var day = requiredDate.getDate();
var output = requiredDate.getFullYear() + '/' + ((''+month).length<2 ? '0' : '') + month + '/' + ((''+day).length<2 ? '0' : '') + day;
//
Working Example Click
My solution results in a syntax like this:
// Checking to see if var 'column' is in array ['a', 'b', 'c']
if (column.isAmong(['a', 'b', 'c']) {
// Do something
}
And I implement this by extending the basic Object prototype, like this:
Object.prototype.isAmong = function (MyArray){
for (var a=0; a<MyArray.length; a++) {
if (this === MyArray[a]) {
return true;
}
}
return false;
}
We might alternatively name the method isInArray (but probably not inArray) or simply isIn.
Advantages: Simple, straightforward, and self-documenting.
Another good solution. You need create a file typings.json in root directory of project with content:
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160725163759",
"jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
"node": "registry:dt/node#6.0.0+20160909174046"
}
}
Then install global or local typings package, if it not installed (i am install it global):
sudo npm install --global typings
In project root directory run command:
typings install
After that problem is solved. Not needed to change tsconfig target to es6 or es7. Your web application do not support after that some old version of browsers.
I know the question is Old and already answered but this can also be a solution
\b[\w-]+$
and I checked these two URLs
http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos
I know this is not an ideal question to answer but as the OP seems to be a beginner, I'd love to share some basic knowledge with him... Hope everybody understands
OP, you can convert a string to type Boolean
by using any of the methods stated below:
string sample = "True";
bool myBool = bool.Parse(sample);
///or
bool myBool = Convert.ToBoolean(sample);
bool.Parse
expects one parameter which in this case is sample
, .ToBoolean
also expects one parameter.
You can use TryParse
which is the same as Parse
but it doesn't throw any exception :)
string sample = "false";
Boolean myBool;
if (Boolean.TryParse(sample , out myBool))
{
}
Please note that you cannot convert any type of string to type Boolean
because the value of a Boolean
can only be True
or False
Hope you understand :)
Assuming your <input type="file" > has an id of upload this should hopefully do the trick:
var fullPath = document.getElementById('upload').value;
if (fullPath) {
var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
var filename = fullPath.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
alert(filename);
}
Could this class from this forum post help you?
public class BaseConverter {
public static string ToBase(string number, int start_base, int target_base) {
int base10 = this.ToBase10(number, start_base);
string rtn = this.FromBase10(base10, target_base);
return rtn;
}
public static int ToBase10(string number, int start_base) {
if (start_base < 2 || start_base > 36) return 0;
if (start_base == 10) return Convert.ToInt32(number);
char[] chrs = number.ToCharArray();
int m = chrs.Length - 1;
int n = start_base;
int x;
int rtn = 0;
foreach(char c in chrs) {
if (char.IsNumber(c))
x = int.Parse(c.ToString());
else
x = Convert.ToInt32(c) - 55;
rtn += x * (Convert.ToInt32(Math.Pow(n, m)));
m--;
}
return rtn;
}
public static string FromBase10(int number, int target_base) {
if (target_base < 2 || target_base > 36) return "";
if (target_base == 10) return number.ToString();
int n = target_base;
int q = number;
int r;
string rtn = "";
while (q >= n) {
r = q % n;
q = q / n;
if (r < 10)
rtn = r.ToString() + rtn;
else
rtn = Convert.ToChar(r + 55).ToString() + rtn;
}
if (q < 10)
rtn = q.ToString() + rtn;
else
rtn = Convert.ToChar(q + 55).ToString() + rtn;
return rtn;
}
}
Totally untested... let me know if it works! (Copy-pasted it in case the forum post goes away or something...)
from urllib.request import urlopen, Request
Should solve everything
If using @worldofjr answer in jQuery you are getting error:
e.relatedTarget.data is not a function
you should use:
$('#myModal').on('show.bs.modal', function (e) {
var loadurl = $(e.relatedTarget).data('load-url');
$(this).find('.modal-body').load(loadurl);
});
Not that e.relatedTarget
if wrapped by $(..)
I was getting the error in latest Bootstrap 3 and after using this method it's working without any problem.
public static void hanoi(int number, String source, String aux, String dest)
{
if (number == 1)
{
System.out.println(source + " - > "+dest);
}
else{
hanoi(number -1, source, dest, aux);
hanoi(1, source, aux, dest);
hanoi(number -1, aux, source, dest);
}
}
This is called string interpolation, and you do it like this:
"The #{animal} #{action} the #{second_animal}"
Important: it will only work when string is inside double quotes (" ").
Example of code that will not work as you expect:
'The #{animal} #{action} the #{second_animal}'
I've written a jQuery plugin that allow also to delegate the click and dblclick events
// jQuery plugin to bind both single and double click to objects
// parameter 'delegateSelector' is optional and allow to delegate the events
// parameter 'dblclickWait' is optional default is 300
(function($) {
$.fn.multipleClicks = function(delegateSelector, clickFun, dblclickFun, dblclickWait) {
var obj;
if (typeof(delegateSelector)==='function' && typeof(clickFun)==='function') {
dblclickWait = dblclickFun; dblclickFun = clickFun; clickFun = delegateSelector; delegateSelector = null; // If 'delegateSelector' is missing reorder arguments
} else if (!(typeof(delegateSelector)==='string' && typeof(clickFun)==='function' && typeof(dblclickFun)==='function')) {
return false;
}
return $(this).each(function() {
$(this).on('click', delegateSelector, function(event) {
var self = this;
clicks = ($(self).data('clicks') || 0)+1;
$(self).data('clicks', clicks);
if (clicks == 1) {
setTimeout(function(){
if ($(self).data('clicks') == 1) {
clickFun.call(self, event); // Single click action
} else {
dblclickFun.call(self, event); // Double click action
}
$(self).data('clicks', 0);
}, dblclickWait || 300);
}
});
});
};
})(jQuery);
I have found this error can occur with traditional ASP.NET website when you create the Controller in non App_Code directory (sometimes Visual Studio prevents this).
It sets the file type to "Compile" whereas any code added to "App_Code" is set to "Content". If you copy or move the file into App_Code then it is still set as "Compile".
I suspect it has something to with Website Project operation as website projects do not have any build operation.Clearing the bin folder and changing to "Content" seems to fix it.
expr match "$LIST" '$SOURCE'
don't work because of this function search $SOURCE from begin of the string and return the position just after pattern $SOURCE if found else 0. So you must write another code:
expr match "$LIST" '.*'"$SOURCE" or expr "$LIST" : '.*'"$SOURCE"
The expression $SOURCE must be double quoted so as a parser may set substitution. Single quoted not substitute and the code above will search textual string $SOURCE from the beginning of the $LIST. If you need the beginning of the string subtract the length $SOURCE e.g ${#SOURCE}. You may write also
expr "$LIST" : ".*\($SOURCE\)"
This function just extract $SOURCE from $LIST and return it. You'll get empty string else. But they problem with double double quote. I don't know how it resolve without using additional variable. It's light solution. So you may write in C. There is ready function strstr. Don't use expr index, So is very attractive. But index search not substring and only first char.
Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.
Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?
This seems to be related to Unable to install Python libraries
See Dominique Barton's answer:
Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.
On Debian-based systems I'd try:
apt-get update && apt-get upgrade python-pip
On Red Hat Linux-based systems:
yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)
On Mac:
sudo easy_install -U pip
You can also try to update
openssl
separately.
If it is a symmetrical (rectangular) array then Try pushing into a single dimension javascript array; use razor to determine the array structure; and then transform into a 2 dimensional array.
// this just sticks them all in a one dimension array of rows * cols
var myArray = new Array();
@foreach (var d in Model.ResultArray)
{
@:myArray.push("@d");
}
var MyA = new Array();
var rows = @Model.ResultArray.GetLength(0);
var cols = @Model.ResultArray.GetLength(1);
// now convert the single dimension array to 2 dimensions
var NewRow;
var myArrayPointer = 0;
for (rr = 0; rr < rows; rr++)
{
NewRow = new Array();
for ( cc = 0; cc < cols; cc++)
{
NewRow.push(myArray[myArrayPointer]);
myArrayPointer++;
}
MyA.push(NewRow);
}
Just to add another option to the mix, there are several useful constants within the string
module. While more useful in other cases, they can be used here.
>>> from string import digits
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'
There are several constants in the module, including:
ascii_letters
(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ)hexdigits
(0123456789abcdefABCDEF)If you are using these constants heavily, it can be worthwhile to covert them to a frozenset
. That enables O(1) lookups, rather than O(n), where n is the length of the constant for the original strings.
>>> digits = frozenset(digits)
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'
Within the inner class itself, you can use OuterClass.this
. This expression, which allows to refer to any lexically enclosing instance, is described in the JLS as Qualified this
.
I don't think there's a way to get the instance from outside the code of the inner class though. Of course, you can always introduce your own property:
public OuterClass getOuter() {
return OuterClass.this;
}
EDIT: By experimentation, it looks like the field holding the reference to the outer class has package level access - at least with the JDK I'm using.
EDIT: The name used (this$0
) is actually valid in Java, although the JLS discourages its use:
The
$
character should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.
Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:
git reset
This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run
git add -p
which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached
), you can commit, and then
git reset --hard
to destroy all the unwanted changes in your working directory.
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
If you want to use python3+ to install the packages you need to use pip3 install package_name
And to solve the errno 13 you have to add --user
at the end
pip3 install package_name --user
EDIT:
For any project in python it's highly recommended to work on a Virtual enviroment, is a tool that helps to keep dependencies required by different projects separate by creating isolated python virtual environments for them.
In order to create one with python3+ you have to use the following command:
virtualenv enviroment_name -p python3
And then you work on it just by activating it:
source enviroment_name/bin/activate
Once the virtual environment is activated, the name of your virtual environment will appear on left side of terminal. This will let you know that the virtual environment is currently active.
Now you can install dependencies related to the project in this virtual environment by just using pip
.
pip install package_name
It should be extremely risky... but you can use exec():
a = 'b=5'
exec(a)
c = b*2
print (c)
Result: 10
Saish's answer using REGEXP_LIKE
is the right idea but does not support floating numbers. This one will ...
Return values that are numeric
SELECT foo
FROM bar
WHERE REGEXP_LIKE (foo,'^-?\d+(\.\d+)?$');
Return values not numeric
SELECT foo
FROM bar
WHERE NOT REGEXP_LIKE (foo,'^-?\d+(\.\d+)?$');
You can test your regular expressions themselves till your heart is content at http://regexpal.com/ (but make sure you select the checkbox match at line breaks for this one).
There can be several reasons. Most of the times it may be some of the below reasons ,
So what to do is we have to resolve those missing / updating / newly_added jar files.
go to properties
Java Build Path
Libraries
tabAdd JARs
This will solve the problem if it's because one of the above reasons.
Just do this:
$ git clone git://example.com/myproject
$ cd myproject
$ git checkout branchxyz
Branch branchxyz set up to track remote branch branchxyz from origin.
Switched to a new branch 'branchxyz'
$ git pull
Already up-to-date.
$ git branch
* branchxyz
master
$ git branch -a
* branchxyz
master
remotes/origin/HEAD -> origin/master
remotes/origin/branchxyz
remotes/origin/branch123
You see, 'git clone git://example.com/myprojectt' fetches everything, even the branches, you just have to checkout them, then your local branch will be created.
You can use jQuery:
$(function() {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button[type=submit] .default').click();
return false;
} else {
return true;
}
});
});
I would rather use plt.clf()
after every plt.show()
to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.
Similarly, you could do plt.cla()
to just clear the current axes.
To clear a specific axes, useful when you have multiple axes within one figure, you could do for example:
fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0, 1].clear()