The below method can be tried.
def remove_suffix(string1, suffix):
length = len(suffix)
if string1[0:length] == suffix:
return string1[length:]
else:
return string1
suffix = "hello"
string1 = "hello world"
final_string = remove_suffix(string1, suffix)
print (final_string)
Try with keyListener in your textfield
jTextField.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if (text.getText().length() >= 1) {
button.setEnabled(true);
} else {
button.setEnabled(false);
}
}
@Override
public void keyReleased(KeyEvent e) {
}
});
Try this code,
public void ConnectToAccess()
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data source= C:\Documents and Settings\username\" +
@"My Documents\AccessFile.mdb";
try
{
conn.Open();
// Insert code to process data.
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}
}
http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx
I set it to automatically clean up on check-in, which is usually good enough for me. If something is too ugly, I'll just hit the shortcut (Ctrl-Alt-L, Return). And I see they have an option for auto-formatting pasted code, although I've never used that.
I'm in the process of porting a computation-intensive Android app written in Java to iOS6. I'm doing this by porting the non-UI parts from Java to C++, writing the (minimal) UI parts in Obj-C, and wrapping the former in a (small) C interface using the standard C/C++ technique, so that it can be accessed from Obj-C, which is after all a superset of C.
This has been effective so far, and I haven't encountered any gotchas. It seems to be a legitimate approach, since Xcode lets you create C++ classes as well as Obj-C classes, and some of the official sample code does things this way. I haven't had to go outside any officially supported interfaces to do this.
There wouldn't seem to be much to gain from writing my remaining UI code in C++ even if it were possible, in view of the help given to you by the interface builder in Xcode, so my answer would be that you can use C++ for almost all your app, or as much of it as you find appropriate/convenient.
If you are using jQuery:
$.inArray(5 + 5, [ "8", "9", "10", 10 + "" ]);
For more information: http://api.jquery.com/jQuery.inArray/
<div style="float: left;">Left Div</div>
<div style="float: right;">Right Div</div>
With the help of dr answer, I wrote a workaround that makes the conversion to put in your .bashrc. It won't break anything if you don't have any timestamp or already correct timestamps.
dmesg_with_human_timestamps () {
$(type -P dmesg) "$@" | perl -w -e 'use strict;
my ($uptime) = do { local @ARGV="/proc/uptime";<>}; ($uptime) = ($uptime =~ /^(\d+)\./);
foreach my $line (<>) {
printf( ($line=~/^\[\s*(\d+)\.\d+\](.+)/) ? ( "[%s]%s\n", scalar localtime(time - $uptime + $1), $2 ) : $line )
}'
}
alias dmesg=dmesg_with_human_timestamps
Also, a good reading on the dmesg timestamp conversion logic & how to enable timestamps when there are none: https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk92677
Let's try to take an example and understand:
I have a branch, say master, pointing to X <commit-id>, and I have a new branch pointing to Y <sha1>.
Where Y <commit-id> = <master> branch commits - few commits
Now say for Y branch I have to gap-close the commits between the master branch and the new branch. Below is the procedure we can follow:
Step 1:
git checkout -b local origin/new
where local is the branch name. Any name can be given.
Step 2:
git merge origin/master --no-ff --stat -v --log=300
Merge the commits from master branch to new branch and also create a merge commit of log message with one-line descriptions from at most <n> actual commits that are being merged.
For more information and parameters about Git merge, please refer to:
git merge --help
Also if you need to merge a specific commit, then you can use:
git cherry-pick <commit-id>
Following are the steps to push Docker Image to Private Repository of DockerHub
1- First check Docker Images using command
docker images
2- Check Docker Tag command Help
docker tag help
3- Now Tag a name to your created Image
docker tag localImgName:tagName DockerHubUser\Private-repoName:tagName(tag name is optional. Default name is latest)
4- Before pushing Image to DockerHub Private Repo, first login to DockerHub using command
docker login [provide dockerHub username and Password to login]
5- Now push Docker Image to your private Repo using command
docker push [options] ImgName[:tag] e.g docker push DockerHubUser\Private-repoName:tagName
6- Now navigate to the DockerHub Private Repo and you will see Docker image is pushed on your private Repository with name written as TagName in previous steps
If you scale 1600x900
to 1280x720
you have
scale_x = 1280.0/1600
scale_y = 720.0/900
Then you can use it to find button size, and button position
button_width = 300 * scale_x
button_height = 300 * scale_y
button_x = 1440 * scale_x
button_y = 860 * scale_y
If you scale 1280x720
to 1600x900
you have
scale_x = 1600.0/1280
scale_y = 900.0/720
and rest is the same.
I add .0
to value to make float
- otherwise scale_x
, scale_y
will be rounded to integer
- in this example to 0
(zero) (Python 2.x)
The default branch in a git repository is called master
.
To create a new branch use
git branch <branch-name>
To see a list of all branches in the current repository type
git branch
If you want to switch to another branch you can use
git checkout <branch-name>
To create a new branch and switch to it in one step
git checkout -b <branch-name>
To delete a branch, use
git branch -d <branch-name>
To create a branch with the changes from the current branch, do
git stash
git stash branch <branch-name>
SELECT
table_name,
column_name,
CONCAT('ALTER TABLE `',
TABLE_SCHEMA,
'`.`',
table_name,
'` CHANGE `',
column_name,
'` `',
column_name,
'` ',
column_type,
' ',
IF(is_nullable = 'YES', '' , 'NOT NULL '),
IF(column_default IS NOT NULL, concat('DEFAULT ', IF(column_default IN ('CURRENT_TIMESTAMP', 'CURRENT_TIMESTAMP()', 'NULL', 'b\'0\'', 'b\'1\''), column_default, CONCAT('\'',column_default,'\'') ), ' '), ''),
IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '' AND column_type = 'timestamp','NULL ', ''),
IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '','DEFAULT NULL ', ''),
extra,
' COMMENT \'',
column_comment,
'\' ;') as script
FROM
information_schema.columns
WHERE
table_schema = 'my_database_name'
ORDER BY table_name , column_name
Note: You can improve to only one table if you prefer
The solution given by @Rufinus is great but if you have auto increments it will break it.
replace
will replace all instances of a letter. All you need to do is use substring()
:
public String method(String str) {
if (str != null && str.length() > 0 && str.charAt(str.length() - 1) == 'x') {
str = str.substring(0, str.length() - 1);
}
return str;
}
I think the question is a bit confusing.
If you mean "can foreign key 'refer' to a primary key in the same table?", the answer is a firm yes as some replied. For example, in an employee table, a row for an employee may have a column for storing manager's employee number where the manager is also an employee and hence will have a row in the table like a row of any other employee.
If you mean "can column(or set of columns) be a primary key as well as a foreign key in the same table?", the answer, in my view, is a no; it seems meaningless. However, the following definition succeeds in SQL Server!
create table t1(c1 int not null primary key foreign key references t1(c1))
But I think it is meaningless to have such a constraint unless somebody comes up with a practical example.
AmanS, in your example d_id in no circumstance can be a primary key in Employee table. A table can have only one primary key. I hope this clears your doubt. d_id is/can be a primary key only in department table.
The method argument specifies the parameter of the smooth statistic. You can see stat_smooth
for the list of all possible arguments to the method argument.
This setup goes really fast for me (about 2 seconds the build)
build.gradle
android {
dexOptions {
incremental true
preDexLibraries = false
jumboMode = false
maxProcessCount 4
javaMaxHeapSize "6g"
}
}
gradle.properties
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.jvmargs=-Xmx8192M
my PC:
project files
- All located in local HD
Both are variable the only difference is that Mutable variable and immutable variable and there is nothing more difference. var is Mutable variable and val is immutable.In simple Language var can change is value after initialization value val is constant and it cannot change it value after initialization the value.
It is possible to extend the relation with query functions:
<?php
public function comments()
{
return $this->hasMany('Comment')->orderBy('column');
}
[edit after comment]
<?php
class User
{
public function comments()
{
return $this->hasMany('Comment');
}
}
class Controller
{
public function index()
{
$column = Input::get('orderBy', 'defaultColumn');
$comments = User::find(1)->comments()->orderBy($column)->get();
// use $comments in the template
}
}
default User model + simple Controller example; when getting the list of comments, just apply the orderBy() based on Input::get(). (be sure to do some input-checking ;) )
DisplacedAussie's answer is correct, but usually a shorter method is just to reverse the single axis in question:
plt.scatter(x_arr, y_arr)
ax = plt.gca()
ax.set_ylim(ax.get_ylim()[::-1])
where the gca()
function returns the current Axes instance and the [::-1]
reverses the list.
Just make sure put single space before and after "and" Keyword..
Try grepl
on the names of your data.frame
. grepl
matches a regular expression to a target and returns TRUE
if a match is found and FALSE
otherwise. The function is vectorised so you can pass a vector of strings to match and you will get a vector of boolean values returned.
# Data
df <- data.frame( ABC_1 = runif(3),
ABC_2 = runif(3),
XYZ_1 = runif(3),
XYZ_2 = runif(3) )
# ABC_1 ABC_2 XYZ_1 XYZ_2
#1 0.3792645 0.3614199 0.9793573 0.7139381
#2 0.1313246 0.9746691 0.7276705 0.0126057
#3 0.7282680 0.6518444 0.9531389 0.9673290
# Use grepl
df[ , grepl( "ABC" , names( df ) ) ]
# ABC_1 ABC_2
#1 0.3792645 0.3614199
#2 0.1313246 0.9746691
#3 0.7282680 0.6518444
# grepl returns logical vector like this which is what we use to subset columns
grepl( "ABC" , names( df ) )
#[1] TRUE TRUE FALSE FALSE
To answer the second part, I'd make the subset data.frame and then make a vector that indexes the rows to keep (a logical vector) like this...
set.seed(1)
df <- data.frame( ABC_1 = sample(0:1,3,repl = TRUE),
ABC_2 = sample(0:1,3,repl = TRUE),
XYZ_1 = sample(0:1,3,repl = TRUE),
XYZ_2 = sample(0:1,3,repl = TRUE) )
# We will want to discard the second row because 'all' ABC values are 0:
# ABC_1 ABC_2 XYZ_1 XYZ_2
#1 0 1 1 0
#2 0 0 1 0
#3 1 1 1 0
df1 <- df[ , grepl( "ABC" , names( df ) ) ]
ind <- apply( df1 , 1 , function(x) any( x > 0 ) )
df1[ ind , ]
# ABC_1 ABC_2
#1 0 1
#3 1 1
Change your default port in [tomcat_home_dir]/conf/server.xml find
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
change it to
<Connector port="8090" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
You can send a get request with Headers (for authentication with jwt for example):
axios.get('https://example.com/getSomething', {
headers: {
Authorization: 'Bearer ' + token //the token is a variable which holds the token
}
})
Also you can send a post request.
axios.post('https://example.com/postSomething', {
email: varEmail, //varEmail is a variable which holds the email
password: varPassword
},
{
headers: {
Authorization: 'Bearer ' + varToken
}
})
My way of doing it,is to set a request like this:
axios({
method: 'post', //you can set what request you want to be
url: 'https://example.com/request',
data: {id: varID},
headers: {
Authorization: 'Bearer ' + varToken
}
})
First you can use map and with chaining you can use filter
state.map(item => {
if(item.id === action.item.id){
return {
id : action.item.id,
name : item.name,
price: item.price,
quantity : item.quantity-1
}
}else{
return item;
}
}).filter(item => {
if(item.quantity <= 0){
return false;
}else{
return true;
}
});
Can you try this,
echo date("Y-m-d H:i:s", 1388516401);
As noted by theGame,
This means that you pass in a string value for the time, and optionally a value for the current time, which is a UNIX timestamp. The value that is returned is an integer which is a UNIX timestamp.
echo strtotime("2014-01-01 00:00:01");
This will return into the value 1388516401, which is the UNIX timestamp for the date 2014-01-01. This can be confirmed using the date() function as like below:
echo date('Y-m-d', 1198148400); // echos 2014-01-01
*Not as far as i know there isn't what i do normally in this kind of circumstances is create a block beneath with a bigger size((bordersize*2)+originalsize) and make it transparent using
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
here is an example
#main{
width:400px;
overflow:hidden;
position:relative;
}
.border{
width:100%;
position:absolute;
height:100%;
background-color:#F00;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
}
.content{
margin:15px;/*size of border*/
background-color:black;
}
<div id="main">
<div class="border">
</div>
<div class="content">
testing
</div>
</div>
Update:
This answer is outdated, since after all this question is more than 8 years old. Today all up to date browsers support rgba, box shadows and so on. But this is a decent example how it was 8+ years ago.
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
You can't free types that aren't dynamically allocated. Although arrays are syntactically similar (int* x = malloc(sizeof(int) * 4)
can be used in the same way that int x[4]
is), calling free(firstName)
would likely cause an error for the latter.
For example, take this code:
int x;
free(&x);
free()
is a function which takes in a pointer. &x
is a pointer. This code may compile, even though it simply won't work.
If we pretend that all memory is allocated in the same way, x
is "allocated" at the definition, "freed" at the second line, and then "freed" again after the end of the scope. You can't free the same resource twice; it'll give you an error.
This isn't even mentioning the fact that for certain reasons, you may be unable to free the memory at x
without closing the program.
tl;dr: Just free the struct
and you'll be fine. Don't call free on arrays; only call it on dynamically allocated memory.
In 2015 I would go with:
Of course you may want to keep JS for easy project setup and to avoid the transpilation process... there is no ultimate solution.
Or just wait for ECMA6, 7, ... :)
# file? will only return true for files
File.file?(filename)
and
# Will also return true for directories - watch out!
File.exist?(filename)
I know this question is quite old, but I was getting confused by the amount of solutions provided - each one of them claiming to be faster and better. I put together a project on github to compare the base64 encoders and decoders: https://github.com/gaspardpetit/base64/
At this point, I have not limited myself to C algorithms - if one implementation performs well in C++, it can easily be backported to C. Also tests were conducted using Visual Studio 2015. If somebody wants to update this answer with results from clang/gcc, be my guest.
FASTEST ENCODERS: The two fastest encoder implementations I found were Jouni Malinen's at http://web.mit.edu/freebsd/head/contrib/wpa/src/utils/base64.c and the Apache at https://opensource.apple.com/source/QuickTimeStreamingServer/QuickTimeStreamingServer-452/CommonUtilitiesLib/base64.c.
Here is the time (in microseconds) to encode 32K of data using the different algorithms I have tested up to now:
jounimalinen 25.1544
apache 25.5309
NibbleAndAHalf 38.4165
internetsoftwareconsortium 48.2879
polfosol 48.7955
wikibooks_org_c 51.9659
gnome 74.8188
elegantdice 118.899
libb64 120.601
manuelmartinez 120.801
arduino 126.262
daedalusalpha 126.473
CppCodec 151.866
wikibooks_org_cpp 343.2
adp_gmbh 381.523
LihO 406.693
libcurl 3246.39
user152949 4828.21
(René Nyffenegger's solution, credited in another answer to this question, is listed here as adp_gmbh).
Here is the one from Jouni Malinen that I slightly modified to return a std::string:
/*
* Base64 encoding/decoding (RFC1341)
* Copyright (c) 2005-2011, Jouni Malinen <[email protected]>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
// 2016-12-12 - Gaspard Petit : Slightly modified to return a std::string
// instead of a buffer allocated with malloc.
#include <string>
static const unsigned char base64_table[65] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* base64_encode - Base64 encode
* @src: Data to be encoded
* @len: Length of the data to be encoded
* @out_len: Pointer to output length variable, or %NULL if not used
* Returns: Allocated buffer of out_len bytes of encoded data,
* or empty string on failure
*/
std::string base64_encode(const unsigned char *src, size_t len)
{
unsigned char *out, *pos;
const unsigned char *end, *in;
size_t olen;
olen = 4*((len + 2) / 3); /* 3-byte blocks to 4-byte */
if (olen < len)
return std::string(); /* integer overflow */
std::string outStr;
outStr.resize(olen);
out = (unsigned char*)&outStr[0];
end = src + len;
in = src;
pos = out;
while (end - in >= 3) {
*pos++ = base64_table[in[0] >> 2];
*pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)];
*pos++ = base64_table[((in[1] & 0x0f) << 2) | (in[2] >> 6)];
*pos++ = base64_table[in[2] & 0x3f];
in += 3;
}
if (end - in) {
*pos++ = base64_table[in[0] >> 2];
if (end - in == 1) {
*pos++ = base64_table[(in[0] & 0x03) << 4];
*pos++ = '=';
}
else {
*pos++ = base64_table[((in[0] & 0x03) << 4) |
(in[1] >> 4)];
*pos++ = base64_table[(in[1] & 0x0f) << 2];
}
*pos++ = '=';
}
return outStr;
}
FASTEST DECODERS: Here are the decoding results and I must admit that I am a bit surprised:
polfosol 45.2335
wikibooks_org_c 74.7347
apache 77.1438
libb64 100.332
gnome 114.511
manuelmartinez 126.579
elegantdice 138.514
daedalusalpha 151.561
jounimalinen 206.163
arduino 335.95
wikibooks_org_cpp 350.437
CppCodec 526.187
internetsoftwareconsortium 862.833
libcurl 1280.27
LihO 1852.4
adp_gmbh 1934.43
user152949 5332.87
Polfosol's snippet from base64 decode snippet in c++ is the fastest by a factor of almost 2x.
Here is the code for the sake of completeness:
static const int B64index[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 63, 62, 62, 63, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0,
0, 0, 0, 63, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 };
std::string b64decode(const void* data, const size_t len)
{
unsigned char* p = (unsigned char*)data;
int pad = len > 0 && (len % 4 || p[len - 1] == '=');
const size_t L = ((len + 3) / 4 - pad) * 4;
std::string str(L / 4 * 3 + pad, '\0');
for (size_t i = 0, j = 0; i < L; i += 4)
{
int n = B64index[p[i]] << 18 | B64index[p[i + 1]] << 12 | B64index[p[i + 2]] << 6 | B64index[p[i + 3]];
str[j++] = n >> 16;
str[j++] = n >> 8 & 0xFF;
str[j++] = n & 0xFF;
}
if (pad)
{
int n = B64index[p[L]] << 18 | B64index[p[L + 1]] << 12;
str[str.size() - 1] = n >> 16;
if (len > L + 2 && p[L + 2] != '=')
{
n |= B64index[p[L + 2]] << 6;
str.push_back(n >> 8 & 0xFF);
}
}
return str;
}
Sample function is used for sample data in ORACLE. So you can try like this:-
SELECT * FROM TABLE_NAME SAMPLE(50);
Here 50 is the percentage of data contained by the table. So if you want 1000 rows from 100000. You can execute a query like:
SELECT * FROM TABLE_NAME SAMPLE(1);
Hope this can help you.
Try below code :-
1.
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
2.
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated
or
int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();
3.
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
metrics.heightPixels;
metrics.widthPixels;
I think you forgot to change
data={this.props.data}
to
data={this.state.data}
in the render function of CommentBox. I did the same mistake when I was following the tutorial. Thus the whole render function should look like
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
</div>
);
}
instead of
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.props.data} />
<CommentForm />
</div>
);
This is one way of doing it:
datagridview.DataSource = null;
datagridview.Refresh();
I hope it works for you because it is working for me.
I have came after another solution to this...here is the code
$('.selector').popover({
html: true,
trigger: 'manual',
container: $(this).attr('id'),
placement: 'top',
content: function () {
$return = '<div class="hover-hovercard"></div>';
}
}).on("mouseenter", function () {
var _this = this;
$(this).popover("show");
$(this).siblings(".popover").on("mouseleave", function () {
$(_this).popover('hide');
});
}).on("mouseleave", function () {
var _this = this;
setTimeout(function () {
if (!$(".popover:hover").length) {
$(_this).popover("hide")
}
}, 100);
});
Looking over the provided solutions I'm always think about drawbacks of modern education in IT field. Most of the developers are forgetting that even modern CPU's suffer from executing conditional operators, while arithmetics operations, especially with powers of 2 are faster. So on the purpose I'm showing this solution in PHP thread without any optimizations:
list($year,$month,$day) = explode("-",$birthday);
$age=floor(((date("Y")-$year)*512+(date("m")-$month)*32+date("d")-$day)/512);
In other languages which have strict type definitions and capable replacing * and / by shifts, this formula will "fly". Also changing divisor you can calculate age in months, weeks &etc. Be carefull, the order of operands in differences is essential
My 2¢! Really, part of the reason I'm throwing this up here, despite the long list of answers, is to provide a little more all in one
type solution and get some feed back in the future on how to expand it to include more real types
.
With the following solution, as aforementioned, I combined a couple of solutions found here, as well as incorporate a fix for returning a value of jQuery on jQuery defined object if available. I also append the method to the native Object prototype. I know that is often taboo, as it could interfere with other such extensions, but I leave that to user beware
. If you don't like this way of doing it, simply copy the base function anywhere you like and replace all variables of this
with an argument parameter to pass in (such as arguments[0]).
;(function() { // Object.realType
function realType(toLower) {
var r = typeof this;
try {
if (window.hasOwnProperty('jQuery') && this.constructor && this.constructor == jQuery) r = 'jQuery';
else r = this.constructor && this.constructor.name ? this.constructor.name : Object.prototype.toString.call(this).slice(8, -1);
}
catch(e) { if (this['toString']) r = this.toString().slice(8, -1); }
return !toLower ? r : r.toLowerCase();
}
Object['defineProperty'] && !Object.prototype.hasOwnProperty('realType')
? Object.defineProperty(Object.prototype, 'realType', { value: realType }) : Object.prototype['realType'] = realType;
})();
Then simply use with ease, like so:
obj.realType() // would return 'Object'
obj.realType(true) // would return 'object'
Note: There is 1 argument passable. If is bool of
true
, then the return will always be in lowercase.
More Examples:
true.realType(); // "Boolean"
var a = 4; a.realType(); // "Number"
$('div:first').realType(); // "jQuery"
document.createElement('div').realType() // "HTMLDivElement"
If you have anything to add that maybe helpful, such as defining when an object was created with another library (Moo, Proto, Yui, Dojo, etc...) please feel free to comment or edit this and keep it going to be more accurate and precise. OR roll on over to the GitHub I made for it and let me know. You'll also find a quick link to a cdn min file there.
SOAPAction is required in SOAP 1.1 but can be empty ("").
See https://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528
"The header field value of empty string ("") means that the intent of the SOAP message is provided by the HTTP Request-URI."
Try setting SOAPAction=""
Update (9/1/15): The OP has made this question a bit of a moving target. It’s been updated again. So, I feel responsible to update my reply.
Yes, this is possible.
You can solve this by updating Child’s onClick
to be this.props.onClick.bind(null, this)
:
var Child = React.createClass({
render: function () {
return <a onClick={this.props.onClick.bind(null, this)}>Click me</a>;
}
});
The event handler in your Parent can then access the component and event like so:
onClick: function (component, event) {
// console.log(component, event);
},
Parent already knows Child’s props
.
This isn’t clear in the provided example because no props are actually being provided. This sample code might better support the question being asked:
var Child = React.createClass({
render: function () {
return <a onClick={this.props.onClick}> {this.props.text} </a>;
}
});
var Parent = React.createClass({
getInitialState: function () {
return { text: "Click here" };
},
onClick: function (event) {
// event.component.props ?why is this not available?
},
render: function() {
return <Child onClick={this.onClick} text={this.state.text} />;
}
});
It becomes much clearer in this example that you already know what the props of Child are.
If it’s truly about using a Child’s props, you can avoid any hookup with Child altogether.
JSX has a spread attributes API I often use on components like Child. It takes all the props
and applies them to a component. Child would look like this:
var Child = React.createClass({
render: function () {
return <a {...this.props}> {this.props.text} </a>;
}
});
Allowing you to use the values directly in the Parent:
var Parent = React.createClass({
getInitialState: function () {
return { text: "Click here" };
},
onClick: function (text) {
alert(text);
},
render: function() {
return <Child onClick={this.onClick.bind(null, this.state.text)} text={this.state.text} />;
}
});
And there's no additional configuration required as you hookup additional Child components
var Parent = React.createClass({
getInitialState: function () {
return {
text: "Click here",
text2: "No, Click here",
};
},
onClick: function (text) {
alert(text);
},
render: function() {
return <div>
<Child onClick={this.onClick.bind(null, this.state.text)} text={this.state.text} />
<Child onClick={this.onClick.bind(null, this.state.text2)} text={this.state.text2} />
</div>;
}
});
But I suspect that’s not your actual use case. So let’s dig further…
The generic nature of the provided example is a hard to talk about. I’ve created a component that demonstrations a practical use for the question above, implemented in a very Reacty way:
DTServiceCalculator working example
DTServiceCalculator repo
This component is a simple service calculator. You provide it with a list of services (with names and prices) and it will calculate a total the selected prices.
ServiceItem
is the child-component in this example. It doesn’t have many opinions about the outside world. It requires a few props, one of which is a function to be called when clicked.
<div onClick={this.props.handleClick.bind(this.props.index)} />
It does nothing but to call the provided handleClick
callback with the provided index
[source].
DTServicesCalculator
is the parent-component is this example. It’s also a child. Let’s look.
DTServiceCalculator
creates a list of child-component (ServiceItem
s) and provides them with props [source]. It’s the parent-component of ServiceItem
but it`s the child-component of the component passing it the list. It doesn't own the data. So it again delegates handling of the component to its parent-component source
<ServiceItem chosen={chosen} index={i} key={id} price={price} name={name} onSelect={this.props.handleServiceItem} />
handleServiceItem
captures the index, passed from the child, and provides it to its parent [source]
handleServiceClick (index) {
this.props.onSelect(index);
}
The concept of “Ownership” is an important one in React. I recommend reading more about it here.
In the example I’ve shown, I keep delegating handling of an event up the component tree until we get to the component that owns the state.
When we finally get there, we handle the state selection/deselection like so [source]:
handleSelect (index) {
let services = […this.state.services];
services[index].chosen = (services[index].chosen) ? false : true;
this.setState({ services: services });
}
Try keeping your outer-most components as opaque as possible. Strive to make sure that they have very few preferences about how a parent-component might choose to implement them.
Keep aware of who owns the data you are manipulating. In most cases, you will need to delegate event handling up the tree to the component that owns that state.
Aside: The Flux pattern is a good way to reduce this type of necessary hookup in apps.
You may get day, month and year and may concatenate them or may use MM-dd-yyyy format as given below.
Date date1 = new Date();
String mmddyyyy1 = new SimpleDateFormat("MM-dd-yyyy").format(date1);
System.out.println("Formatted Date 1: " + mmddyyyy1);
Date date2 = new Date();
Calendar calendar1 = new GregorianCalendar();
calendar1.setTime(date2);
int day1 = calendar1.get(Calendar.DAY_OF_MONTH);
int month1 = calendar1.get(Calendar.MONTH) + 1; // {0 - 11}
int year1 = calendar1.get(Calendar.YEAR);
String mmddyyyy2 = ((month1<10)?"0"+month1:month1) + "-" + ((day1<10)?"0"+day1:day1) + "-" + (year1);
System.out.println("Formatted Date 2: " + mmddyyyy2);
LocalDateTime ldt1 = LocalDateTime.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MM-dd-yyyy");
String mmddyyyy3 = ldt1.format(format1);
System.out.println("Formatted Date 3: " + mmddyyyy3);
LocalDateTime ldt2 = LocalDateTime.now();
int day2 = ldt2.getDayOfMonth();
int mont2= ldt2.getMonthValue();
int year2= ldt2.getYear();
String mmddyyyy4 = ((mont2<10)?"0"+mont2:mont2) + "-" + ((day2<10)?"0"+day2:day2) + "-" + (year2);
System.out.println("Formatted Date 4: " + mmddyyyy4);
LocalDateTime ldt3 = LocalDateTime.of(2020, 6, 11, 14, 30); // int year, int month, int dayOfMonth, int hour, int minute
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("MM-dd-yyyy");
String mmddyyyy5 = ldt3.format(format2);
System.out.println("Formatted Date 5: " + mmddyyyy5);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(new Date());
int day3 = calendar2.get(Calendar.DAY_OF_MONTH); // OR Calendar.DATE
int month3= calendar2.get(Calendar.MONTH) + 1;
int year3 = calendar2.get(Calendar.YEAR);
String mmddyyyy6 = ((month3<10)?"0"+month3:month3) + "-" + ((day3<10)?"0"+day3:day3) + "-" + (year3);
System.out.println("Formatted Date 6: " + mmddyyyy6);
Date date3 = new Date();
LocalDate ld1 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date3)); // Accepts only yyyy-MM-dd
int day4 = ld1.getDayOfMonth();
int month4= ld1.getMonthValue();
int year4 = ld1.getYear();
String mmddyyyy7 = ((month4<10)?"0"+month4:month4) + "-" + ((day4<10)?"0"+day4:day4) + "-" + (year4);
System.out.println("Formatted Date 7: " + mmddyyyy7);
Date date4 = new Date();
int day5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getDayOfMonth();
int month5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getMonthValue();
int year5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getYear();
String mmddyyyy8 = ((month5<10)?"0"+month5:month5) + "-" + ((day5<10)?"0"+day5:day5) + "-" + (year5);
System.out.println("Formatted Date 8: " + mmddyyyy8);
Date date5 = new Date();
int day6 = Integer.parseInt(new SimpleDateFormat("dd").format(date5));
int month6 = Integer.parseInt(new SimpleDateFormat("MM").format(date5));
int year6 = Integer.parseInt(new SimpleDateFormat("yyyy").format(date5));
String mmddyyyy9 = ((month6<10)?"0"+month6:month6) + "-" + ((day6<10)?"0"+day6:day6) + "-" + (year6);`enter code here`
System.out.println("Formatted Date 9: " + mmddyyyy9);
Try this,
alter table goods add column `id` int(10) unsigned primary key auto_increment
Per Microsoft in powershell:
Get-ChildItem "hklm:SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\" | Get-ItemPropertyValue -Name Release | % { $_ -ge 394802 }
See the table at this link to get the DWORD value to search for specific versions:
The background of widgets are API level dependent.
ALTERNATIVE 1
You can provide a custom image to your EditText
background by
android:background="@drawable/custom_editText"
Your image should look something like this. It will give you the desired effect.
ALTERNATIVE 2
Set this xml to your EditText
background attribute.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#4C000000"/>
<corners android:bottomRightRadius="5dp"
android:bottomLeftRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
</shape>
This will have the same look and feel of your EditText
on every API.
Escape the quotes with backslashes:
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.
Had same problem. Just did a quick look up apache2 error.log
file and it said exactly what was the problem:
> sh: /usr/sbin/sendmail: Permission denied
So, the solution was to give proper permissions for /usr/sbin/sendmail
file (it wasn't accessible from php).
Command to do this would be:
> chmod 777 /usr/sbin/sendmail
be sure that it even exists!
You can add new column with the query
ALTER TABLE TableName ADD COLUMN COLNew CHAR(25)
But it will be added at the end, not in between the existing columns.
It's ridiculous that java doesn't have this yet. Scala has it
import com.text.Formatter
import com.json.{Formatter => JsonFormatter}
val Formatter textFormatter;
val JsonFormatter jsonFormatter;
Check whether you have declared the method where this code is executing as static
. If it is static
there may be some other thread resetting the ResultSet
.
Set your PERL_UNICODE
envariable to AS
. This makes all Perl scripts decode @ARGV
as UTF-8 strings, and sets the encoding of all three of stdin, stdout, and stderr to UTF-8. Both these are global effects, not lexical ones.
At the top of your source file (program, module, library, do
hickey), prominently assert that you are running perl version 5.12 or better via:
use v5.12; # minimal for unicode string feature
use v5.14; # optimal for unicode string feature
Enable warnings, since the previous declaration only enables strictures and features, not warnings. I also suggest promoting Unicode warnings into exceptions, so use both these lines, not just one of them. Note however that under v5.14, the utf8
warning class comprises three other subwarnings which can all be separately enabled: nonchar
, surrogate
, and non_unicode
. These you may wish to exert greater control over.
use warnings;
use warnings qw( FATAL utf8 );
Declare that this source unit is encoded as UTF-8. Although once upon a time this pragma did other things, it now serves this one singular purpose alone and no other:
use utf8;
Declare that anything that opens a filehandle within this lexical scope but not elsewhere is to assume that that stream is encoded in UTF-8 unless you tell it otherwise. That way you do not affect other module’s or other program’s code.
use open qw( :encoding(UTF-8) :std );
Enable named characters via \N{CHARNAME}
.
use charnames qw( :full :short );
If you have a DATA
handle, you must explicitly set its encoding. If you want this to be UTF-8, then say:
binmode(DATA, ":encoding(UTF-8)");
There is of course no end of other matters with which you may eventually find yourself concerned, but these will suffice to approximate the state goal to “make everything just work with UTF-8”, albeit for a somewhat weakened sense of those terms.
One other pragma, although it is not Unicode related, is:
use autodie;
It is strongly recommended.
My own boilerplate these days tends to look like this:
use 5.014;
use utf8;
use strict;
use autodie;
use warnings;
use warnings qw< FATAL utf8 >;
use open qw< :std :utf8 >;
use charnames qw< :full >;
use feature qw< unicode_strings >;
use File::Basename qw< basename >;
use Carp qw< carp croak confess cluck >;
use Encode qw< encode decode >;
use Unicode::Normalize qw< NFD NFC >;
END { close STDOUT }
if (grep /\P{ASCII}/ => @ARGV) {
@ARGV = map { decode("UTF-8", $_) } @ARGV;
}
$0 = basename($0); # shorter messages
$| = 1;
binmode(DATA, ":utf8");
# give a full stack dump on any untrapped exceptions
local $SIG{__DIE__} = sub {
confess "Uncaught exception: @_" unless $^S;
};
# now promote run-time warnings into stack-dumped
# exceptions *unless* we're in an try block, in
# which case just cluck the stack dump instead
local $SIG{__WARN__} = sub {
if ($^S) { cluck "Trapped warning: @_" }
else { confess "Deadly warning: @_" }
};
while (<>) {
chomp;
$_ = NFD($_);
...
} continue {
say NFC($_);
}
__END__
Saying that “Perl should [somehow!] enable Unicode by default” doesn’t even start to begin to think about getting around to saying enough to be even marginally useful in some sort of rare and isolated case. Unicode is much much more than just a larger character repertoire; it’s also how those characters all interact in many, many ways.
Even the simple-minded minimal measures that (some) people seem to think they want are guaranteed to miserably break millions of lines of code, code that has no chance to “upgrade” to your spiffy new Brave New World modernity.
It is way way way more complicated than people pretend. I’ve thought about this a huge, whole lot over the past few years. I would love to be shown that I am wrong. But I don’t think I am. Unicode is fundamentally more complex than the model that you would like to impose on it, and there is complexity here that you can never sweep under the carpet. If you try, you’ll break either your own code or somebody else’s. At some point, you simply have to break down and learn what Unicode is about. You cannot pretend it is something it is not.
goes out of its way to make Unicode easy, far more than anything else I’ve ever used. If you think this is bad, try something else for a while. Then come back to : either you will have returned to a better world, or else you will bring knowledge of the same with you so that we can make use of your new knowledge to make better at these things.
At a minimum, here are some things that would appear to be required for to “enable Unicode by default”, as you put it:
All source code should be in UTF-8 by default. You can get that with use utf8
or export PERL5OPTS=-Mutf8
.
The DATA
handle should be UTF-8. You will have to do this on a per-package basis, as in binmode(DATA, ":encoding(UTF-8)")
.
Program arguments to scripts should be understood to be UTF-8 by default. export PERL_UNICODE=A
, or perl -CA
, or export PERL5OPTS=-CA
.
The standard input, output, and error streams should default to UTF-8. export PERL_UNICODE=S
for all of them, or I
, O
, and/or E
for just some of them. This is like perl -CS
.
Any other handles opened by should be considered UTF-8 unless declared otherwise; export PERL_UNICODE=D
or with i
and o
for particular ones of these; export PERL5OPTS=-CD
would work. That makes -CSAD
for all of them.
Cover both bases plus all the streams you open with export PERL5OPTS=-Mopen=:utf8,:std
. See uniquote.
You don’t want to miss UTF-8 encoding errors. Try export PERL5OPTS=-Mwarnings=FATAL,utf8
. And make sure your input streams are always binmode
d to :encoding(UTF-8)
, not just to :utf8
.
Code points between 128–255 should be understood by to be the corresponding Unicode code points, not just unpropertied binary values. use feature "unicode_strings"
or export PERL5OPTS=-Mfeature=unicode_strings
. That will make uc("\xDF") eq "SS"
and "\xE9" =~ /\w/
. A simple export PERL5OPTS=-Mv5.12
or better will also get that.
Named Unicode characters are not by default enabled, so add export PERL5OPTS=-Mcharnames=:full,:short,latin,greek
or some such. See uninames and tcgrep.
You almost always need access to the functions from the standard Unicode::Normalize
module various types of decompositions. export PERL5OPTS=-MUnicode::Normalize=NFD,NFKD,NFC,NFKD
, and then always run incoming stuff through NFD and outbound stuff from NFC. There’s no I/O layer for these yet that I’m aware of, but see nfc, nfd, nfkd, and nfkc.
String comparisons in using eq
, ne
, lc
, cmp
, sort
, &c&cc are always wrong. So instead of @a = sort @b
, you need @a = Unicode::Collate->new->sort(@b)
. Might as well add that to your export PERL5OPTS=-MUnicode::Collate
. You can cache the key for binary comparisons.
built-ins like printf
and write
do the wrong thing with Unicode data. You need to use the Unicode::GCString
module for the former, and both that and also the Unicode::LineBreak
module as well for the latter. See uwc and unifmt.
If you want them to count as integers, then you are going to have to run your \d+
captures through the Unicode::UCD::num
function because ’s built-in atoi(3) isn’t currently clever enough.
You are going to have filesystem issues on filesystems. Some filesystems silently enforce a conversion to NFC; others silently enforce a conversion to NFD. And others do something else still. Some even ignore the matter altogether, which leads to even greater problems. So you have to do your own NFC/NFD handling to keep sane.
All your code involving a-z
or A-Z
and such MUST BE CHANGED, including m//
, s///
, and tr///
. It’s should stand out as a screaming red flag that your code is broken. But it is not clear how it must change. Getting the right properties, and understanding their casefolds, is harder than you might think. I use unichars and uniprops every single day.
Code that uses \p{Lu}
is almost as wrong as code that uses [A-Za-z]
. You need to use \p{Upper}
instead, and know the reason why. Yes, \p{Lowercase}
and \p{Lower}
are different from \p{Ll}
and \p{Lowercase_Letter}
.
Code that uses [a-zA-Z]
is even worse. And it can’t use \pL
or \p{Letter}
; it needs to use \p{Alphabetic}
. Not all alphabetics are letters, you know!
If you are looking for variables with /[\$\@\%]\w+/
, then you have a problem. You need to look for /[\$\@\%]\p{IDS}\p{IDC}*/
, and even that isn’t thinking about the punctuation variables or package variables.
If you are checking for whitespace, then you should choose between \h
and \v
, depending. And you should never use \s
, since it DOES NOT MEAN [\h\v]
, contrary to popular belief.
If you are using \n
for a line boundary, or even \r\n
, then you are doing it wrong. You have to use \R
, which is not the same!
If you don’t know when and whether to call Unicode::Stringprep, then you had better learn.
Case-insensitive comparisons need to check for whether two things are the same letters no matter their diacritics and such. The easiest way to do that is with the standard Unicode::Collate module. Unicode::Collate->new(level => 1)->cmp($a, $b)
. There are also eq
methods and such, and you should probably learn about the match
and substr
methods, too. These are have distinct advantages over the built-ins.
Sometimes that’s still not enough, and you need the Unicode::Collate::Locale module instead, as in Unicode::Collate::Locale->new(locale => "de__phonebook", level => 1)->cmp($a, $b)
instead. Consider that Unicode::Collate::->new(level => 1)->eq("d", "ð")
is true, but Unicode::Collate::Locale->new(locale=>"is",level => 1)->eq("d", " ð")
is false. Similarly, "ae" and "æ" are eq
if you don’t use locales, or if you use the English one, but they are different in the Icelandic locale. Now what? It’s tough, I tell you. You can play with ucsort to test some of these things out.
Consider how to match the pattern CVCV (consonsant, vowel, consonant, vowel) in the string “niño”. Its NFD form — which you had darned well better have remembered to put it in — becomes “nin\x{303}o”. Now what are you going to do? Even pretending that a vowel is [aeiou]
(which is wrong, by the way), you won’t be able to do something like (?=[aeiou])\X)
either, because even in NFD a code point like ‘ø’ does not decompose! However, it will test equal to an ‘o’ using the UCA comparison I just showed you. You can’t rely on NFD, you have to rely on UCA.
And that’s not all. There are a million broken assumptions that people make about Unicode. Until they understand these things, their code will be broken.
Code that assumes it can open a text file without specifying the encoding is broken.
Code that assumes the default encoding is some sort of native platform encoding is broken.
Code that assumes that web pages in Japanese or Chinese take up less space in UTF-16 than in UTF-8 is wrong.
Code that assumes Perl uses UTF-8 internally is wrong.
Code that assumes that encoding errors will always raise an exception is wrong.
Code that assumes Perl code points are limited to 0x10_FFFF is wrong.
Code that assumes you can set $/
to something that will work with any valid line separator is wrong.
Code that assumes roundtrip equality on casefolding, like lc(uc($s)) eq $s
or uc(lc($s)) eq $s
, is completely broken and wrong. Consider that the uc("s")
and uc("?")
are both "S"
, but lc("S")
cannot possibly return both of those.
Code that assumes every lowercase code point has a distinct uppercase one, or vice versa, is broken. For example, "ª"
is a lowercase letter with no uppercase; whereas both "?"
and "?"
are letters, but they are not lowercase letters; however, they are both lowercase code points without corresponding uppercase versions. Got that? They are not \p{Lowercase_Letter}
, despite being both \p{Letter}
and \p{Lowercase}
.
Code that assumes changing the case doesn’t change the length of the string is broken.
Code that assumes there are only two cases is broken. There’s also titlecase.
Code that assumes only letters have case is broken. Beyond just letters, it turns out that numbers, symbols, and even marks have case. In fact, changing the case can even make something change its main general category, like a \p{Mark}
turning into a \p{Letter}
. It can also make it switch from one script to another.
Code that assumes that case is never locale-dependent is broken.
Code that assumes Unicode gives a fig about POSIX locales is broken.
Code that assumes you can remove diacritics to get at base ASCII letters is evil, still, broken, brain-damaged, wrong, and justification for capital punishment.
Code that assumes that diacritics \p{Diacritic}
and marks \p{Mark}
are the same thing is broken.
Code that assumes \p{GC=Dash_Punctuation}
covers as much as \p{Dash}
is broken.
Code that assumes dash, hyphens, and minuses are the same thing as each other, or that there is only one of each, is broken and wrong.
Code that assumes every code point takes up no more than one print column is broken.
Code that assumes that all \p{Mark}
characters take up zero print columns is broken.
Code that assumes that characters which look alike are alike is broken.
Code that assumes that characters which do not look alike are not alike is broken.
Code that assumes there is a limit to the number of code points in a row that just one \X
can match is wrong.
Code that assumes \X
can never start with a \p{Mark}
character is wrong.
Code that assumes that \X
can never hold two non-\p{Mark}
characters is wrong.
Code that assumes that it cannot use "\x{FFFF}"
is wrong.
Code that assumes a non-BMP code point that requires two UTF-16 (surrogate) code units will encode to two separate UTF-8 characters, one per code unit, is wrong. It doesn’t: it encodes to single code point.
Code that transcodes from UTF-16 or UTF-32 with leading BOMs into UTF-8 is broken if it puts a BOM at the start of the resulting UTF-8. This is so stupid the engineer should have their eyelids removed.
Code that assumes the CESU-8 is a valid UTF encoding is wrong. Likewise, code that thinks encoding U+0000 as "\xC0\x80"
is UTF-8 is broken and wrong. These guys also deserve the eyelid treatment.
Code that assumes characters like >
always points to the right and <
always points to the left are wrong — because they in fact do not.
Code that assumes if you first output character X
and then character Y
, that those will show up as XY
is wrong. Sometimes they don’t.
Code that assumes that ASCII is good enough for writing English properly is stupid, shortsighted, illiterate, broken, evil, and wrong. Off with their heads! If that seems too extreme, we can compromise: henceforth they may type only with their big toe from one foot. (The rest will be duct taped.)
Code that assumes that all \p{Math}
code points are visible characters is wrong.
Code that assumes \w
contains only letters, digits, and underscores is wrong.
Code that assumes that ^
and ~
are punctuation marks is wrong.
Code that assumes that ü
has an umlaut is wrong.
Code that believes things like ?
contain any letters in them is wrong.
Code that believes \p{InLatin}
is the same as \p{Latin}
is heinously broken.
Code that believe that \p{InLatin}
is almost ever useful is almost certainly wrong.
Code that believes that given $FIRST_LETTER
as the first letter in some alphabet and $LAST_LETTER
as the last letter in that same alphabet, that [${FIRST_LETTER}-${LAST_LETTER}]
has any meaning whatsoever is almost always complete broken and wrong and meaningless.
Code that believes someone’s name can only contain certain characters is stupid, offensive, and wrong.
Code that tries to reduce Unicode to ASCII is not merely wrong, its perpetrator should never be allowed to work in programming again. Period. I’m not even positive they should even be allowed to see again, since it obviously hasn’t done them much good so far.
Code that believes there’s some way to pretend textfile encodings don’t exist is broken and dangerous. Might as well poke the other eye out, too.
Code that converts unknown characters to ?
is broken, stupid, braindead, and runs contrary to the standard recommendation, which says NOT TO DO THAT! RTFM for why not.
Code that believes it can reliably guess the encoding of an unmarked textfile is guilty of a fatal mélange of hubris and naïveté that only a lightning bolt from Zeus will fix.
Code that believes you can use printf
widths to pad and justify Unicode data is broken and wrong.
Code that believes once you successfully create a file by a given name, that when you run ls
or readdir
on its enclosing directory, you’ll actually find that file with the name you created it under is buggy, broken, and wrong. Stop being surprised by this!
Code that believes UTF-16 is a fixed-width encoding is stupid, broken, and wrong. Revoke their programming licence.
Code that treats code points from one plane one whit differently than those from any other plane is ipso facto broken and wrong. Go back to school.
Code that believes that stuff like /s/i
can only match "S"
or "s"
is broken and wrong. You’d be surprised.
Code that uses \PM\pM*
to find grapheme clusters instead of using \X
is broken and wrong.
People who want to go back to the ASCII world should be whole-heartedly encouraged to do so, and in honor of their glorious upgrade they should be provided gratis with a pre-electric manual typewriter for all their data-entry needs. Messages sent to them should be sent via an ??????s telegraph at 40 characters per line and hand-delivered by a courier. STOP.
I don’t know how much more “default Unicode in ” you can get than what I’ve written. Well, yes I do: you should be using Unicode::Collate
and Unicode::LineBreak
, too. And probably more.
As you see, there are far too many Unicode things that you really do have to worry about for there to ever exist any such thing as “default to Unicode”.
What you’re going to discover, just as we did back in 5.8, that it is simply impossible to impose all these things on code that hasn’t been designed right from the beginning to account for them. Your well-meaning selfishness just broke the entire world.
And even once you do, there are still critical issues that require a great deal of thought to get right. There is no switch you can flip. Nothing but brain, and I mean real brain, will suffice here. There’s a heck of a lot of stuff you have to learn. Modulo the retreat to the manual typewriter, you simply cannot hope to sneak by in ignorance. This is the 21?? century, and you cannot wish Unicode away by willful ignorance.
You have to learn it. Period. It will never be so easy that “everything just works,” because that will guarantee that a lot of things don’t work — which invalidates the assumption that there can ever be a way to “make it all work.”
You may be able to get a few reasonable defaults for a very few and very limited operations, but not without thinking about things a whole lot more than I think you have.
As just one example, canonical ordering is going to cause some real headaches. "\x{F5}"
‘õ’, "o\x{303}"
‘õ’, "o\x{303}\x{304}"
‘?’, and "o\x{304}\x{303}"
‘o~’ should all match ‘õ’, but how in the world are you going to do that? This is harder than it looks, but it’s something you need to account for.
If there’s one thing I know about Perl, it is what its Unicode bits do and do not do, and this thing I promise you: “ _?_?_?_?_?_ _?_s_ _?_?_ _U_?_?_?_?_?_?_ _?_?_?_?_?_ _?_?_?_?_?_?_ _ ”
You cannot just change some defaults and get smooth sailing. It’s true that I run with PERL_UNICODE
set to "SA"
, but that’s all, and even that is mostly for command-line stuff. For real work, I go through all the many steps outlined above, and I do it very, ** very** carefully.
If you want to use something like an INI file to hold settings, consider using configparser which loads key value pairs from a text file, and can easily write back to the file.
INI file has the format:
[Section]
key = value
key with spaces = somevalue
There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.
The steps in Excel 2010 are:
In a cell enter a formula like this
=VLOOKUP(A2,$D$3:$E$5,2,FALSE)
which will return the matching value from the second part of your list.
Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.
The steps in Excel 2010 are:
Sometime ago I implemented an easy to use "download manager" library: PTDownloadManager. You could give it a shot!
You could use jQuery and an Ajax call to post the specific update back to your server with Javascript.
It would look something like this:
function updatePostID(val, comment)
{
var args = {};
args.PostID = val;
args.Comment = comment;
$.ajax({
type: "POST",
url: controllerActionMethodUrlHere,
contentType: "application/json; charset=utf-8",
data: args,
dataType: "json",
success: function(msg)
{
// Something afterwards here
}
});
}
I started out naming enums in the plural but have since changed to singular. Just seems to make more sense in the context of where they're used.
enum Status { Unknown = 0, Incomplete, Ready }
Status myStatus = Status.Ready;
Compare to:
Statuses myStatus = Statuses.Ready;
I find the singular form to sound more natural in context. We are in agreement that when declaring the enum, which happens in one place, we're thinking "this is a group of whatevers", but when using it, presumably in many places, that we're thinking "this is one whatever".
You may consider 3rd party tool that called Excel Jetcell .NET component for read/write excel files:
C# sample
// Create New Excel Workbook
ExcelWorkbook Wbook = new ExcelWorkbook();
ExcelCellCollection Cells = Wbook.Worksheets.Add("Sheet1").Cells;
Cells["A1"].Value = "Excel writer example (C#)";
Cells["A1"].Style.Font.Bold = true;
Cells["B1"].Value = "=550 + 5";
// Write Excel XLS file
Wbook.WriteXLS("excel_net.xls");
VB.NET sample
' Create New Excel Workbook
Dim Wbook As ExcelWorkbook = New ExcelWorkbook()
Dim Cells As ExcelCellCollection = Wbook.Worksheets.Add("Sheet1").Cells
Cells("A1").Value = "Excel writer example (C#)"
Cells("A1").Style.Font.Bold = True
Cells("B1").Value = "=550 + 5"
' Write Excel XLS file
Wbook.WriteXLS("excel_net.xls")
You could set the property:
android:onClick="buttonClicked"
in the xml file for each of those buttons, and use this in the java code:
public void buttonClicked(View view) {
if (view.getId() == R.id.button1) {
// button1 action
} else if (view.getId() == R.id.button2) {
//button2 action
} else if (view.getId() == R.id.button3) {
//button3 action
}
}
kR105 wrote:
you can also have two classes within an element like this
<div class = "item1 item2 item3"></div
I can't see the value of this, since by the principle of cascading styles, the last one takes precedence. For example, if in my earlier example I changed the HTML to read
<div class="box1 box2"> Hello what is my color? </div>
the box's border and text would be blue, since .box2's style assigns these values.
Also in my earlier post I should have emphasized that adding selectors as I did is not the same as creating a subclass within a class (the first solution in this thread), though the effect is similar.
In swift 3 use:
let url = URL(string: "Whatever url you have(eg: https://google.com)")
Define "doesn't work".
const date = moment("2015-07-02"); // Thursday Feb 2015_x000D_
const dow = date.day();_x000D_
console.log(dow);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
This prints "4", as expected.
The most common reason for this message seems to be unzipping the eclipse zip file wrongly (for instance unzipping without recreating the directory structure). Therefore please unzip the zipped Eclipse again with a good unzip tool (like 7-zip) and make sure that the necessary sub directories are created during the extraction.
Also make sure that the path to the unzipped Eclipse does not get very long. I've seen cases where Eclipse was unzipped into a deeply nested directory structure (to put it at some place into an SVN repository) and that led to the same error message.
If that still doesn't work, you may try launching eclipse.exe with administrative rights. That should not really be necessary, but maybe your access rights are somehow broken after the re-installation of Windows.
Instead of
Object.values(myObject);
use
Object["values"](myObject);
In your example case:
const values = Object["values"](data).map(x => x.substr(0, x.length - 4));
This will hide the ts compiler error.
Instead of:
input:not(disabled)not:[type="submit"]:focus {}
Use:
input:not([disabled]):not([type="submit"]):focus {}
disabled
is an attribute so it needs the brackets, and you seem to have mixed up/missing colons and parentheses on the :not()
selector.
Demo: http://jsfiddle.net/HSKPx/
One thing to note: I may be wrong, but I don't think disabled
inputs can normally receive focus, so that part may be redundant.
Alternatively, use :enabled
input:enabled:not([type="submit"]):focus { /* styles here */ }
Again, I can't think of a case where disabled input can receive focus, so it seems unnecessary.
The OP asked, is it possible to reference a table, not how to add a table. So the working equivalent of
Sheets("Sheet1").Table("A_Table").Select
would be this statement:
Sheets("Sheet1").ListObjects("A_Table").Range.Select
or to select parts (like only the data in the table):
Dim LO As ListObject
Set LO = Sheets("Sheet1").ListObjects("A_Table")
LO.HeaderRowRange.Select ' Select just header row
LO.DataBodyRange.Select ' Select just data cells
LO.TotalsRowRange.Select ' Select just totals row
For the parts, you may want to test for the existence of the header and totals rows before selecting them.
And seriously, this is the only question on referencing tables in VBA in SO? Tables in Excel make so much sense, but they're so hard to work with in VBA!
If you have Jackson integeration with your application to serialize your bean to JSON format, then you can use Jackson anotation @JsonFormat to format your date to specified format.
In your case if you need your date into yyyy-MM-dd
format you need to specify @JsonFormat
above your field on which you want to apply this format.
For Example :
public class Subject {
private String uid;
private String number;
private String initials;
@JsonFormat(pattern="yyyy-MM-dd")
private Date dateOfBirth;
//Other Code
}
From Docs :
annotation used for configuring details of how values of properties are to be serialized.
Hope this helps.
In Mac OS X do this in the command prompt from the repo directory:
cd .git
rm index.lock
Documentation: C.2.3.1 <jee:jndi-lookup/>
(simple)
Example:
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/MyDataSource"/>
You just need to find out what JNDI name your appserver has bound the datasource to. This is entirely server-specific, consult the docs on your server to find out how.
Remember to declare the jee
namespace at the top of your beans file, as described in C.2.3 The jee schema.
whats actually wrong with:
input { border: 1px solid #f00; }
do you only want it on inputs with errors? in that case give the input a class of error...
input.error { border: 1px solid #f00; }
Use dotPeek by JetBrains.
https://www.jetbrains.com/decompiler/
dotPeek is a free tool based on ReSharper. It can reliably decompile any .NET assembly into C# or IL code.
Some explanation ignore a condition about the retain cycle [If a group of objects is connected by a circle of strong relationships, they keep each other alive even if there are no strong references from outside the group.] For more information, read the document
You have to set setOnItemLongClickListener() in the ListView:
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// TODO Auto-generated method stub
Log.v("long clicked","pos: " + pos);
return true;
}
});
The XML for each item in the list (should you use a custom XML) must have android:longClickable="true"
as well (or you can use the convenience method lv.setLongClickable(true);
). This way you can have a list with only some items responding to longclick.
Hope this will help you.
For a concise way to retain the folder hierarchy under the parent directory to be archived:
import glob
import zipfile
with zipfile.ZipFile(fp_zip, "w", zipfile.ZIP_DEFLATED) as zipf:
for fp in glob(os.path.join(parent, "**/*")):
base = os.path.commonpath([parent, fp])
zipf.write(fp, arcname=fp.replace(base, ""))
If you want, you could change this to use pathlib
for file globbing.
Your database was shut down because of insufficient memory! You can edit the file my.cnf base below graph to resolve it
performance_schema_max_table_instances=200
table_definition_cache=200
table_open_cache=128
In Jan2018 the only solution worked for me:
<?php
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){
echo "<br> Line to show.";
echo str_pad('',4096)."\n";
ob_flush();
flush();
sleep(2);
}
echo "Done.";
ob_end_flush();
?>
I just spent a couple hours tracking an EXC_BAD_ACCESS and found NSZombies and other env vars didn't seem to tell me anything.
For me, it was a stupid NSLog statement with format specifiers but no args passed.
NSLog(@"Some silly log message %@-%@");
Fixed by
NSLog(@"Some silly log message %@-%@", someObj1, someObj2);
I'm not aware of standard practices for package organization. I generally create packages that cover some reasonably broad spectrum, but I can differentiate within a project. For example, a personal project I'm currently working on has a package devoted to my customized UI controls (full of classes subclassing swing classes). I've got a package devoted to my database management stuff, I've got a package for a set of listeners/events that I've created, and so on.
On the other hand I've had a coworker create a new package for almost everything he did. Each different MVC he wanted got its own package, and it seemed a MVC set was the only grouping of classes allowed to be in the same package. I recall at one point he had 5 different packages that each had a single class in them. I think his method is a little bit on the extreme (and the team forced him to reduce his package count when we simply couldn't handle it), but for a nontrivial application, so would putting everything in the same package. It's a balance point you and your teammates have to find for yourself.
One thing you can do is try to step back and think: if you were a new member introduced to the project, or your project was released as open source or an API, how easy/difficult would it be to find what you want? Because for me, that's what I really want out of packages: organization. Similar to how I store files in folder on my computer, I expect to be able to find them again without having to search my entire drive. I expect to be able to find the class I want without having to search the list of all classes in the package.
Give this a go:
<option onclick="parent.location='#5.2'">Bookmark 2</option>
I have created a javascript function that looks if he has enough space on the right side. If it has he will show it on the right side, else he will display it on the left side
Tested in:
Javascript:
$(document).ready(function(){
//little fix for the poisition.
var newPos = $(".fixed-menuprofile .dropdown-submenu").offset().left - $(this).width();
$(".fixed-menuprofile .dropdown-submenu").find('ul').offset({ "left": newPos });
$(".fixed-menu .dropdown-submenu").mouseover(function() {
var submenuPos = $(this).offset().left + 325;
var windowPos = $(window).width();
var oldPos = $(this).offset().left + $(this).width();
var newPos = $(this).offset().left - $(this).width();
if( submenuPos > windowPos ){
$(this).find('ul').offset({ "left": newPos });
} else {
$(this).find('ul').offset({ "left": oldPos });
}
});
});
because I don't want to add this fix on every menu items I created a new class on it. place the fixed-menu on the ul:
<ul class="dropdown-menu fixed-menu">
I hope this works out for you.
ps. little bug in safari and chrome, first hover will place it to mutch to the left will update this post if I fixed it.
From the Reflector'd source:
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
return new List<TSource>(source);
}
So yes, your original list won't be updated (i.e. additions or removals) however the referenced objects will.
Following up on Timores's elegant solution, I have found that the following creates a vertical fill in a vertical LinearLayout and a horizontal fill in a horizontal LinearLayout:
<Space
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
This works for me!
$("#your_textarea").on('keydown', function(e){
if(e.keyCode === 13 && !e.shiftKey)
{
$('form').submit();
}
});
It just specifies what interpreter you want to use. To understand this, create a file through terminal by doing touch test.py
, then type into that file the following:
#!/usr/bin/env python3
print "test"
and do chmod +x test.py
to make your script executable. After this when you do ./test.py
you should get an error saying:
File "./test.py", line 2
print "test"
^
SyntaxError: Missing parentheses in call to 'print'
because python3 doesn't supprt the print operator.
Now go ahead and change the first line of your code to:
#!/usr/bin/env python2
and it'll work, printing test
to stdout, because python2 supports the print operator. So, now you've learned how to switch between script interpreters.
After combining many answers and suggestion here, this is my final answer, which works well with flex
, which allows us to make columns with equal height, it also checks the last index, and you don't need to repeat the inner HTML. It doesn't use clearfix
:
<div ng-repeat="prod in productsFiltered=(products | filter:myInputFilter)" ng-if="$index % 3 == 0" class="row row-eq-height">
<div ng-repeat="i in [0, 1, 2]" ng-init="product = productsFiltered[$parent.$parent.$index + i]" ng-if="$parent.$index + i < productsFiltered.length" class="col-xs-4">
<div class="col-xs-12">{{ product.name }}</div>
</div>
</div>
It will output something like this:
<div class="row row-eq-height">
<div class="col-xs-4">
<div class="col-xs-12">
Product Name
</div>
</div>
<div class="col-xs-4">
<div class="col-xs-12">
Product Name
</div>
</div>
<div class="col-xs-4">
<div class="col-xs-12">
Product Name
</div>
</div>
</div>
<div class="row row-eq-height">
<div class="col-xs-4">
<div class="col-xs-12">
Product Name
</div>
</div>
<div class="col-xs-4">
<div class="col-xs-12">
Product Name
</div>
</div>
<div class="col-xs-4">
<div class="col-xs-12">
Product Name
</div>
</div>
</div>
Oracle SQL Developer 2020-02 support PostgreSQL, but it is just the basics by adding postgreSQL driver under jdbc dir and configure by adding as a 3rd party driver.
The supported functionality:
Not supported functionalities:
The sad thing is Oracle should only change the queries behind this view in case of PostgreSql connections. For example for indexes they need to use this query: select * from pg_catalog.pg_indexes;
You can use double join, if table A
B
are connected only by table AB
.
public static Specification<A> findB(String input) {
return (Specification<A>) (root, cq, cb) -> {
Join<A,AB> AjoinAB = root.joinList(A_.AB_LIST,JoinType.LEFT);
Join<AB,B> ABjoinB = AjoinAB.join(AB_.B,JoinType.LEFT);
return cb.equal(ABjoinB.get(B_.NAME),input);
};
}
That's just an another option
Sorry for that timing but I have came across this question and I also wanted to make SELECT IN
but I didn't even thought about double join.
I hope it will help someone.
Shortest Yet !!!
=f.hidden_field :title, :value => "some value"
Shorter, DRYer and perhaps more obvious.
Of course with ruby 1.9 and the new hash format we can go 3 characters shorter with...
=f.hidden_field :title, value: "some value"
Untested. Modify to suit:
$form = $('#my-form');
$rows = $form.find('.person-input-row');
$('button#add-new').click(function() {
$rows.find(':first').clone().insertAfter($rows.find(':last'));
$justInserted = $rows.find(':last');
$justInserted.hide();
$justInserted.find('input').val(''); // it may copy values from first one
$justInserted.slideDown(500);
});
This is better than copying innerHTML because you will lose all attached events etc.
//Do it like---
function dragStart(this_,event) {
var row=$(this_).attr('whatever');
event.dataTransfer.setData("Text", row);
}
If you want to filter the models by applicationname
and the remaining models by surname
:
List<Model> newList = list.Where(m => m.application == "applicationname")
.Select(m => new Model {
application = m.application,
users = m.users.Where(u => u.surname == "surname").ToList()
}).ToList();
As you can see, it needs to create new models and user-lists, hence it is not the most efficient way.
If you instead don't want to filter the list of users but filter the models by users with at least one user with a given username, use Any
:
List<Model> newList = list
.Where(m => m.application == "applicationname"
&& m.users.Any(u => u.surname == "surname"))
.ToList();
I've found the easiest way to centre and left-align text inside a container is the following:
HTML:
<div>
<p>Some interesting text.</p>
</div>
CSS:
P {
width: 50%; //or whatever looks best
margin: auto; //top and bottom margin can be added for aesthetic effect
}
Hope this is what you were looking for as it took me quite a bit of searching just to figure out this pretty basic solution.
If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr
function, like this
>>> chr(65)
'A'
similarly if you have 97,
>>> chr(97)
'a'
EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord
and the result has to be converted using unichr
instead of chr
.
>>> print unichr(ord(u'\u0B85'))
?
>>> print unichr(1 + ord(u'\u0B85'))
?
NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf
//for excluding zero
public class SmallestInt {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("enter number");
int val=input.nextInt();
int min=val;
//String notNull;
while(input.hasNextInt()==true)
{
val=input.nextInt();
if(val<min)
min=val;
}
System.out.println("min is: "+min);
}
}
very old post. but i'll just leave this here:
/* converts a number with byte unit (B / K / M / G) into an integer */
function unitToInt($s)
{
return (int)preg_replace_callback('/(\-?\d+)(.?)/', function ($m) {
return $m[1] * pow(1024, strpos('BKMG', $m[2]));
}, strtoupper($s));
}
$mem_limit = unitToInt(ini_get('memory_limit'));
Use nslookup
nslookup 208.77.188.166
...
Non-authoritative answer:
166.188.77.208.in-addr.arpa name = www.example.com.
Think of it as a letter. Sometimes you get a letter, say asking you to fill in a form then return the form in a pre-addressed envelope which is in the original envelope that was housing the form.
Once you have finished filling the form in, you put it in the provided return envelop and send it back.
The callbackUrl is like that return envelope. You are basically saying I am sending you this data. Once you are done with it, I am on this callbackUrl waiting for your response. So the API will process the data you have sent then look at the callback to send you the response.
This is useful because sometimes you may take ages to process some data and it makes no sense to have the caller wait for a response. For example, say your API allows users to send documents to it and virus scan them. Then you send a report after. The scan could take maybe 3minutes. The user cannot be waiting for 3minutes. So you acknowledge that you got the document and let the caller get on with other business while you do the scan then use the callbackUrl when done to tell them the result of the scan.
You might want to check out this tutorial: http://www.webdesignerwall.com/tutorials/css-decorative-gallery/
In it the writer uses an empty span element to add an overlaying image. You can use jQuery to inject said span elements, if you'd like to keep your code as clean as possible. An example is also given in the aforementioned article.
Hope this helps!
-Dave
First, you need to create a personal access token (PAT). This is described here: https://help.github.com/articles/creating-an-access-token-for-command-line-use/
Laughably, the article tells you how to create it, but gives absolutely no clue what to do with it. After about an hour of trawling documentation and Stack Overflow, I finally found the answer:
$ git clone https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>
I was actually forced to enable two-factor authentication by company policy while I was working remotely and still had local changes, so in fact it was not clone
I needed, but push
. I read in lots of places that I needed to delete and recreate the remote, but in fact my normal push
command worked exactly the same as the clone
above, and the remote did not change:
$ git push https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>
(@YMHuang put me on the right track with the documentation link.)
There are some relevant C++ unit testing resources at http://www.progweap.com/resources.html
If you want to continue exactly one Docker container with a known name:
docker start `docker ps -a -q --filter "name=elas"`
If you editing info.plist
directly, below should help you, don't key in "YES" as string below:
<key>UIFileSharingEnabled</key>
<string>YES</string>
You should use this:
<key>UIFileSharingEnabled</key>
<true/>
Use psexec -s
The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.
Newer versions of ARC(Advaced Rest client) also provides file upload option:
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
Okay, per http://www.oracle.com/technology/tech/globalization/htdocs/nls_lang%20faq.htm:
NLS_LANG cannot be changed by ALTER SESSION, NLS_LANGUAGE and NLS_TERRITORY can. However NLS_LANGUAGE and /or NLS_TERRITORY cannot be set as "standalone" parameters in the environment or registry on the client.
Evidently the "right" solution is, before logging into Oracle at all, setting the following environment variable:
export NLS_LANG=AMERICAN_AMERICA.UTF8
Oracle gets a big fat F for usability.
You are specifying .fixedbutton
in your CSS (a class) and specifying the id
on the element itself.
Change your CSS to the following, which will select the id
fixedbutton
#fixedbutton {
position: fixed;
bottom: 0px;
right: 0px;
}
SELECT
t.A,
t.B,
t.C,
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS number
FROM tableZ AS t
See working example at SQLFiddle
Of course, you may want to define the row-numbering order – if so, just swap OVER (ORDER BY (SELECT 1))
for, e.g., OVER (ORDER BY t.C)
, like in a normal ORDER BY
clause.
echo $PATH
and copy it's valueexport PATH=""
export PATH="/path/you/want/to/keep"
It is very unclear what you are trying to do, but you can sort a list like this:
List<String> fruits = new ArrayList<String>(7);
fruits.add("Pineapple");
fruits.add("apple");
fruits.add("apricot");
fruits.add("Banana");
fruits.add("mango");
fruits.add("melon");
fruits.add("peach");
System.out.println("Unsorted: " + fruits);
Collections.sort(fruits, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
});
System.out.println("Sorted: " + fruits);
This happened to me. I just re-committed the changes, and then it pushed.
For JSF Application
To get resource bundle prop files from a given file path to use them in a JSF app.
basename
property of loadBundle
tag.
<f:loadBundle basename="Message" var="msg" />
For basic implementation of extended RB please see the sample at Sample Customized Resource Bundle
/* Create this class to make it base class for Loading Bundle for JSF apps */
public class Message extends ResourceBundle {
public Messages (){
File file = new File("D:\\properties\\i18n");
ClassLoader loader=null;
try {
URL[] urls = {file.toURI().toURL()};
loader = new URLClassLoader(urls);
ResourceBundle bundle = getBundle("message", FacesContext.getCurrentInstance().getViewRoot().getLocale(), loader);
setParent(bundle);
} catch (MalformedURLException ex) { }
}
.
.
.
}
Otherwise, get the bundle from getBundle method but locale from others source like Locale.getDefault()
, the new (RB)class may not require in this case.
Yes, you need the full path.
log = open(os.path.join(root, f), 'r')
Is the quick fix. As the comment pointed out, os.walk
decends into subdirs so you do need to use the current directory root rather than indir
as the base for the path join.
I always go with the generic css title with my setup. I'm just building analytics for my blog admin page. I don't need anything fancy. Here's some code...
let comps = g.selectAll('.myClass')
.data(data)
.enter()
.append('rect')
...styling...
...transitions...
...whatever...
g.selectAll('.myClass')
.append('svg:title')
.text((d, i) => d.name + '-' + i);
And a screenshot of chrome...
You are using g++ 4.6 version you must invoke the flag -std=c++0x to compile
g++ -std=c++0x *.cpp -o output
You need to give the body
and the html
a height too. Otherwise, the body will only be as high as its contents (the single div), and 50% of that will be half the height of this div.
Updated fiddle: http://jsfiddle.net/j8bsS/5/
if you have existing project and you would like to add remote repository url then you need to do following command
git init
if you would like to add readme.md file then you can create it and add it using below command.
git add README.md
make your first commit using below command
git commit -m "first commit"
Now you completed all local repository process, now how you add remote repository url ? check below command this is for ssh url, you can change it for https.
git remote add origin [email protected]:user-name/repository-name.git
How you push your first commit see below command :
git push -u origin master
For django see (https://github.com/joke2k/django-environ)
$ pip install django-environ
import environ
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
# reading .env file
environ.Env.read_env()
# False if not in os.environ
DEBUG = env('DEBUG')
# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')
For someone who is trying all these solution but not working try this one, it worked for me
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<User>().Property(t => t.Email).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_EmailIndex") { IsUnique = true }));
}
For me this work for example here what happen is the main menu will be disabled when you open the registration form.
frmUserRegistration frmMainMenu = new frmUserRegistration();
frmMainMenu.ShowDialog(this);
Your compiler is right. You can't use the growthRate variable you declared in main as a function.
Maybe you should pick different names for your variables so they don't override function names?
def chunker(iterable, n):
"""Yield iterable in chunk sizes.
>>> chunks = chunker('ABCDEF', n=4)
>>> chunks.next()
['A', 'B', 'C', 'D']
>>> chunks.next()
['E', 'F']
"""
it = iter(iterable)
while True:
chunk = []
for i in range(n):
try:
chunk.append(next(it))
except StopIteration:
yield chunk
raise StopIteration
yield chunk
if __name__ == '__main__':
import doctest
doctest.testmod()
Try adding below code in build.gradle, it worked for me -
compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
multiDexEnabled true
}
These are subplot grid parameters encoded as a single integer. For example, "111" means "1x1 grid, first subplot" and "234" means "2x3 grid, 4th subplot".
Alternative form for add_subplot(111)
is add_subplot(1, 1, 1)
.
string data = "THExxQUICKxxBROWNxxFOX";
return data.Replace("xx","|").Split('|');
Just choose the replace character carefully (choose one that isn't likely to be present in the string already)!
You can use try-catch block to check for integer value
for eg:
User inputs in form of string
try
{
int num=Integer.parseInt("Some String Input");
}
catch(NumberFormatException e)
{
//If number is not integer,you wil get exception and exception message will be printed
System.out.println(e.getMessage());
}
Try this:
table1.GroupBy(x => x.Text).Select(x => x.FirstOrDefault());
This will group the table by Text
and use the first row from each groups resulting in rows where Text
is distinct.
As a sidenote to @Navaneethan 's answer, Jinja2
is able to do "regular" item selections for the list and the dictionary, given we know the key of the dictionary, or the locations of items in the list.
parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]
{% for dict_item in parent_dict %}
This example has {{dict_item['A']}} and {{dict_item['B']}}:
with the content --
{% for item in dict_item['content'] %}{{item[0]}} and {{item[1]}}{% endfor %}.
{% endfor %}
This example has val1 and val2:
with the content --
1.1 and 2.2.
This example has val3 and val4:
with the content --
3.3 and 4.4.
version control is your friend here, do a diff
or equivalent and you should see what's been added/modified.
In fact, removing the component folder might not be enough; with Angular-CLI v1.0, the command ng generate component my-new-component
also edits your app.module.ts
file by adding the respective import
line and the component to the providers
array.
Your json string is wrapped within square brackets ([]
), hence it is interpreted as array instead of single RetrieveMultipleResponse
object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse
, for example :
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
I think that R is reading the '\' in the string as an escape character. For example \n creates a new line within a string, \t creates a new tab within the string.
'\' will work because R will recognize this as a normal backslash.
I know this is an old thread but for others who reach there my suggestion is to create a scheduled job to copy content from production bucket to development one.
You can use If you use .NET this article might help you
https://edunyte.com/2015/03/aws-s3-copy-object-from-one-bucket-or/
I use this for every external link:
window.onload = function(){
var anchors = document.getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
if (anchors[i].hostname != window.location.hostname) {
anchors[i].setAttribute('target', '_blank');
}
}
}
Default is:
Username: root
Password: [null]
The Password is set to 'password' in some versions.
Facebook provides two ways to login and logout from an account. One is to use LoginButton and the other is to use LoginManager. LoginButton is just a button which on clicked, the logging in is accomplished. On the other side LoginManager does this on its own. In your case you have use LoginManager to logout automatically.
LoginManager.getInstance().logout()
does this work for you.
I know this is an older question, but I wanted to post an answer for users with the same question:
curl -H 'Cache-Control: no-cache' http://www.example.com
This curl command servers in its header request to return non-cached data from the web server.
You need to change parameter "a" => "a+". Follow this code bellows:
def storescores():
hs = open("hst.txt","a+")
Above solutions not helped me, but I resolve same issue by next way
private setHeaders(params) {
const accessToken = this.localStorageService.get('token');
const reqData = {
headers: {
Authorization: `Bearer ${accessToken}`
},
};
if(params) {
let reqParams = {};
Object.keys(params).map(k =>{
reqParams[k] = params[k];
});
reqData['params'] = reqParams;
}
return reqData;
}
and send request
this.http.get(this.getUrl(url), this.setHeaders(params))
Its work with NestJS backend, with other I don't know.
match_parent is used in place of fill_parent and sets it to go as far as the parent goes. Just use match_parent and forget about fill_parent. I completely ditched fill_parent and everything is perfect as usual.
Check here for more.
keyboard shortcuts in visual studio
(alt + z) => toggle word wrap
The accepted answer lists only the filenames, but to get the top 5 files one can also use:
ls -lht | head -6
where:
-l
outputs in a list format
-h
makes output human readable (i.e. file sizes appear in kb, mb, etc.)
-t
sorts output by placing most recently modified file first
head -6
will show 5 files because ls
prints the block size in the first line of output.
I think this is a slightly more elegant and possibly more useful approach.
Example output:
total 26960312
-rw-r--r--@ 1 user staff 1.2K 11 Jan 11:22 phone2.7.py
-rw-r--r--@ 1 user staff 2.7M 10 Jan 15:26 03-cookies-1.pdf
-rw-r--r--@ 1 user staff 9.2M 9 Jan 16:21 Wk1_sem.pdf
-rw-r--r--@ 1 user staff 502K 8 Jan 10:20 lab-01.pdf
-rw-rw-rw-@ 1 user staff 2.0M 5 Jan 22:06 0410-1.wmv
if you need to do it more often , you can even create your own method for pop the last element; something like this:
public void pop(List<string> myList) {
myList.RemoveAt(myList.Count - 1);
}
or even instead of void you can return the value like:
public string pop (List<string> myList) {
// first assign the last value to a seperate string
string extractedString = myList(myList.Count - 1);
// then remove it from list
myList.RemoveAt(myList.Count - 1);
// then return the value
return extractedString;
}
just notice that the second method's return type is not void , it is string b/c we want that function to return us a string ...
Here is an extension method doing that:
public static IEnumerable<KeyValuePair<TLeft, TRight>> FullOuterJoin<TLeft, TRight>(this IEnumerable<TLeft> leftItems, Func<TLeft, object> leftIdSelector, IEnumerable<TRight> rightItems, Func<TRight, object> rightIdSelector)
{
var leftOuterJoin = from left in leftItems
join right in rightItems on leftIdSelector(left) equals rightIdSelector(right) into temp
from right in temp.DefaultIfEmpty()
select new { left, right };
var rightOuterJoin = from right in rightItems
join left in leftItems on rightIdSelector(right) equals leftIdSelector(left) into temp
from left in temp.DefaultIfEmpty()
select new { left, right };
var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);
return fullOuterJoin.Select(x => new KeyValuePair<TLeft, TRight>(x.left, x.right));
}
Creating a .jshintrc
file is not necessary.
If you are using ECMAScript 6 then all you need to do is tell JSHint that:
You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted
to tell it how you want to sort.
And you want to get the keys; use map
to transform entries to keys.
List<Type> types = countByType.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
The 2018 ES6 answer is:
return Object.is(x, undefined) ? y : x;
If variable x is undefined, return variable y... otherwise if variable x is defined, return variable x.
You probably have an anonymous user ''@'localhost'
or ''@'127.0.0.1'
.
As per the manual:
When multiple matches are possible, the server must determine which of them to use. It resolves this issue as follows: (...)
- When a client attempts to connect, the server looks through the rows [of table mysql.user] in sorted order.
- The server uses the first row that matches the client host name and user name.
(...) The server uses sorting rules that order rows with the most-specific Host values first. Literal host names [such as 'localhost'] and IP addresses are the most specific.
Hence, such an anonymous user would "mask" any other user like '[any_username]'@'%'
when connecting from localhost
.
'bill'@'localhost'
does match 'bill'@'%'
, but would match (e.g.) ''@'localhost'
beforehands.
The recommended solution is to drop this anonymous user (this is usually a good thing to do anyways).
Below edits are mostly irrelevant to the main question. These are only meant to answer some questions raised in other comments within this thread.
Edit 1
Authenticating as 'bill'@'%'
through a socket.
root@myhost:/home/mysql-5.5.16-linux2.6-x86_64# ./mysql -ubill -ppass --socket=/tmp/mysql-5.5.sock Welcome to the MySQL monitor (...) mysql> SELECT user, host FROM mysql.user; +------+-----------+ | user | host | +------+-----------+ | bill | % | | root | 127.0.0.1 | | root | ::1 | | root | localhost | +------+-----------+ 4 rows in set (0.00 sec) mysql> SELECT USER(), CURRENT_USER(); +----------------+----------------+ | USER() | CURRENT_USER() | +----------------+----------------+ | bill@localhost | bill@% | +----------------+----------------+ 1 row in set (0.02 sec) mysql> SHOW VARIABLES LIKE 'skip_networking'; +-----------------+-------+ | Variable_name | Value | +-----------------+-------+ | skip_networking | ON | +-----------------+-------+ 1 row in set (0.00 sec)
Edit 2
Exact same setup, except I re-activated networking, and I now create an anonymous user ''@'localhost'
.
root@myhost:/home/mysql-5.5.16-linux2.6-x86_64# ./mysql Welcome to the MySQL monitor (...) mysql> CREATE USER ''@'localhost' IDENTIFIED BY 'anotherpass'; Query OK, 0 rows affected (0.00 sec) mysql> Bye root@myhost:/home/mysql-5.5.16-linux2.6-x86_64# ./mysql -ubill -ppass \ --socket=/tmp/mysql-5.5.sock ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES) root@myhost:/home/mysql-5.5.16-linux2.6-x86_64# ./mysql -ubill -ppass \ -h127.0.0.1 --protocol=TCP ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES) root@myhost:/home/mysql-5.5.16-linux2.6-x86_64# ./mysql -ubill -ppass \ -hlocalhost --protocol=TCP ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)
Edit 3
Same situation as in edit 2, now providing the anonymous user's password.
root@myhost:/home/mysql-5.5.16-linux2.6-x86_64# ./mysql -ubill -panotherpass -hlocalhost Welcome to the MySQL monitor (...) mysql> SELECT USER(), CURRENT_USER(); +----------------+----------------+ | USER() | CURRENT_USER() | +----------------+----------------+ | bill@localhost | @localhost | +----------------+----------------+ 1 row in set (0.01 sec)
Conclusion 1, from edit 1: One can authenticate as 'bill'@'%'
through a socket.
Conclusion 2, from edit 2: Whether one connects through TCP or through a socket has no impact on the authentication process (except one cannot connect as anyone else but 'something'@'localhost'
through a socket, obviously).
Conclusion 3, from edit 3: Although I specified -ubill
, I have been granted access as an anonymous user. This is because of the "sorting rules" advised above. Notice that in most default installations, a no-password, anonymous user exists (and should be secured/removed).
Being form
a block element, you can center-align it by setting its side margins to auto:
form { margin: 0 auto; }
EDIT:
As @moomoochoo correctly pointed out, this rule will only work if the block element (your form, in this case) has been assigned a specific width.
Also, this 'trick' will not work for floating elements.
I had trouble with a .pfx file with openconnect. Renaming didn't solve the problem. I used keytool to convert it to .p12 and it worked.
keytool -importkeystore -destkeystore new.p12 -deststoretype pkcs12 -srckeystore original.pfx
In my case the password for the new file (new.p12) had to be the same as the password for the .pfx file.
here a concatenation solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 10
int main() {
char *text = calloc(1,1), buffer[BUFFERSIZE];
printf("Enter a message: \n");
while( fgets(buffer, BUFFERSIZE , stdin) ) /* break with ^D or ^Z */
{
text = realloc( text, strlen(text)+1+strlen(buffer) );
if( !text ) ... /* error handling */
strcat( text, buffer ); /* note a '\n' is appended here everytime */
printf("%s\n", buffer);
}
printf("\ntext:\n%s",text);
return 0;
}
tv.setText(Integer.toString(intValue))
This is because of some pre-configurations in the cassandra. And to fix this, there are following commented lines in the cassandra-env.sh
file:
#add this if you’re having trouble connecting: #JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=<public name>
where you have to start fixing the error.
Open the terminal and start fixing using the following easy steps:
Step-1
use
sudo nano /etc/cassandra/cassandra-env.sh
this command and search for JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=
uncomment the line by simply removing #
attached in the start of the line.
NOTE: If you have never opened this file to fix this error then you will find JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=<public name>
Step-2
Now replace <public name>
with 127.0.0.1
Step-3 Save the file and restart the cassandra using systemctl restart cassandra.service
(if you haven't the server is alredy running). OR start the cassandra using systemctl start cassandra.service
(if the server is not running).
Step-4 Check the status either by using sudo service cassandra status
or systemctl status cassandra.service
.
Note: Once check the system monitor whether cassandra is running there or not.
Try cqlsh
now. It'll work.
Note: nano
is editor you can use other editors you are comfortable with.
Like we have date "07/May/2018" and we need date "2018-05-07" as mysql compatible
if (!empty($date)) {
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
$date = date('Y-m-d', $timestamp);
}
It works for me. enjoy :)
Updated accepted answer to angular 7.0.1 on stackblitz here: https://stackblitz.com/edit/angular-inputsetter?embed=1&file=src/app/app.component.ts
directives
are no more in Component decorator options. So I have provided sub directive to app module.
thank you @thierry-templier!
preg_replace("[^\w\s\d\.\-_~,;:\[\]\(\]]", '', $file)
Add/remove more valid characters depending on what is allowed for your system.
Alternatively you can try to create the file and then return an error if it's bad.
If the language you use accepts {}
, you can use [0-9]{4,6}
.
If not, you'll have to use [0-9][0-9][0-9][0-9][0-9]?[0-9]?
.
Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.
For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept
property to "application/json".
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
You mean staticly define a value, like this:
SELECT field1,
field2,
'example' AS newfield
FROM TABLE1
This will add a column called "newfield" to the output, and its value will always be "example".
Alternatively, you can directly use javascript's window.onresize
As example, my code (using scriptaculos) is :
window.onresize = function (){
var w = $("form").getWidth() + "px";
$('gfx').setStyle( { width : w } );
}
Where form is an html form on my webpage and gfx the highchart graphics.
MainActivity.java:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button button1;
TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.button1);
textView1=(TextView)findViewById(R.id.textView1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView1.setText("TextView displayed Successfully");
}
});
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click here" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
On production I prefer to redirect the requests to .php files under the directories where PHP processing should be disabled to a home page or to 404 page. This won't reveal any source code (why search engines should index uploaded malicious code?) and will look more friendly for visitors and even for evil hackers trying to exploit the stuff. Also it can be implemented in mostly in any context - vhost or .htaccess. Something like this:
<DirectoryMatch "^${docroot}/(image|cache|upload)/">
<FilesMatch "\.php$">
# use one of the redirections
#RedirectMatch temp "(.*)" "http://${servername}/404/"
RedirectMatch temp "(.*)" "http://${servername}"
</FilesMatch>
</DirectoryMatch>
Adjust the directives as you need.
Based on Stack Overflow questions Unix cut, remove first token and https://stackoverflow.com/a/15903654/781312:
(octal=$(echo -n ? | od -t o1 | head -1 | cut -d' ' -f2- | sed -e 's#\([0-9]\+\) *#\\0\1#g')
echo Octal representation is following $octal
echo -e "$octal")
Output is the following.
Octal representation is following \0342\0230\0240
?
The error is triggered because the file you're linking to in your HTML file is the unbundled version of the file.
To get the full bundled version you'll have to install it with npm
:
npm install --save milsymbol
This downloads the full package to your node_modules
folder.
You can then access the standalone minified JavaScript file at node_modules/milsymbol/dist/milsymbol.js
You can do this in any directory, and then just copy the below file to your /src
directory.
In case of Request to a REST Service:
You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:
@CrossOrigin(origins = "http://localhost:8080")
Very good tutorial: https://spring.io/guides/gs/rest-service-cors/
A clustered index alters the way that the rows are stored. When you create a clustered index on a column (or a number of columns), SQL server sorts the table’s rows by that column(s). It is like a dictionary, where all words are sorted in alphabetical order in the entire book.
A non-clustered index, on the other hand, does not alter the way the rows are stored in the table. It creates a completely different object within the table that contains the column(s) selected for indexing and a pointer back to the table’s rows containing the data. It is like an index in the last pages of a book, where keywords are sorted and contain the page number to the material of the book for faster reference.
Have you checked the Tomcat source code and the JVM source ? That may give you more help.
I think your general thinking is good. I would expect a ConnectException
in the scenario that you couldn't connect. The above looks very like it's client-driven.
Just for the sake of completeness, here is a link to the golang documentation which describes all types. In your case it is numeric types:
uint8 the set of all unsigned 8-bit integers (0 to 255)
uint16 the set of all unsigned 16-bit integers (0 to 65535)
uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
int8 the set of all signed 8-bit integers (-128 to 127)
int16 the set of all signed 16-bit integers (-32768 to 32767)
int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
float32 the set of all IEEE-754 32-bit floating-point numbers
float64 the set of all IEEE-754 64-bit floating-point numbers
complex64 the set of all complex numbers with float32 real and imaginary parts
complex128 the set of all complex numbers with float64 real and imaginary parts
byte alias for uint8
rune alias for int32
Which means that you need to use float64(integer_value)
.
For end of line use:
git diff --ignore-space-at-eol
Instead of what are you using currently:
git diff -w (--ignore-all-space)
For start of line... you are out of luck if you want a built in solution.
However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".
In my experience it may be the result of auto-generation by a string-based tools, where the author did not understand the rules of HTML.
When some developers generate HTML without the use of special XML-oriented tools, they may try to be sure the resulting HTML is valid by taking the approach that everything must be escaped.
Referring to your example, the reason why every occurrence of "
is represented by "
could be because using that approach, you can safely use such "special" characters in both attributes and values.
Another motivation I've seen is where people believe, "We must explicitly show that our symbols are not part of the syntax." Whereas, valid HTML can be created by using the proper string-manipulation tools, see the previous paragraph again.
Here is some pseudo-code loosely based on C#, although it is preferred to use valid methods and tools:
public class HtmlAndXmlWriter
{
private string Escape(string badString)
{
return badString.Replace("&", "&").Replace("\"", """).Replace("'", "'").Replace(">", ">").Replace("<", "<");
}
public string GetHtmlFromOutObject(Object obj)
{
return "<div class='type_" + Escape(obj.Type) + "'>" + Escape(obj.Value) + "</div>";
}
}
It's really very common to see such approaches taken to generate HTML.
You can try 'onbeforeunload
' event.
Also take a look at this-
I can see people giving lots of comments on this question. But I think, simple use of LIKE
could be easier to get the data from the table.
SELECT * FROM table WHERE COLUMN LIKE '2013-05-11%'
Use LIKE
and post data wild character search. Hopefully this will solve your problem.
The <hr>
should be placed inside a <div>
for proper functioning.
Place it like this to get desired width `
<div class='row'>
<div class='col-lg-8 col-lg-offset-2'>
<hr>
</div>
</div>
`
Hope this helps a future reader!
In my case,I was getting error while refreshing gradle ('View'->Tool Windows->Gradle) tab and hit "refresh" and getting this error no such property gradleversion for class jetgradleplugin.
Had to install latest intellij compatible with gradle 5+
You can use the monitoring program glances with its GPU monitoring plug-in:
sudo apt-get install -y python-pip; sudo pip install glances[gpu]
sudo glances
It also monitors the CPU, disk IO, disk space, network, and a few other things:
There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.
While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
I've found this the easy fix, simply add this to the css:
cursor: pointer;
Editing file /etc/apt/sources.list.d/additional-repositories.list
and adding deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable
worked for me, this post was very helpful https://github.com/typora/typora-issues/issues/2065
jQuery has the contains method. Here's a snippet for you:
<script type="text/javascript">
$(function() {
var foundin = $('*:contains("I am a simple string")');
});
</script>
The selector above selects any element that contains the target string. The foundin will be a jQuery object that contains any matched element. See the API information at: https://api.jquery.com/contains-selector/
One thing to note with the '*' wildcard is that you'll get all elements, including your html an body elements, which you probably don't want. That's why most of the examples at jQuery and other places use $('div:contains("I am a simple string")')
Combining various answers :
In MySQL 5.5, DEFAULT CURRENT_TIMESTAMP
and ON UPDATE CURRENT_TIMESTAMP
cannot be added on DATETIME
but only on TIMESTAMP
.
Rules:
1) at most one TIMESTAMP
column per table could be automatically (or manually[My addition]) initialized or updated to the current date and time. (MySQL Docs).
So only one TIMESTAMP
can have CURRENT_TIMESTAMP
in DEFAULT
or ON UPDATE
clause
2) The first NOT NULL
TIMESTAMP
column without an explicit DEFAULT
value like created_date timestamp default '0000-00-00 00:00:00'
will be implicitly given a DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
and hence subsequent TIMESTAMP
columns cannot be given CURRENT_TIMESTAMP
on DEFAULT
or ON UPDATE
clause
CREATE TABLE `address` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`village` int(11) DEFAULT NULL,
`created_date` timestamp default '0000-00-00 00:00:00',
-- Since explicit DEFAULT value that is not CURRENT_TIMESTAMP is assigned for a NOT NULL column,
-- implicit DEFAULT CURRENT_TIMESTAMP is avoided.
-- So it allows us to set ON UPDATE CURRENT_TIMESTAMP on 'updated_date' column.
-- How does setting DEFAULT to '0000-00-00 00:00:00' instead of CURRENT_TIMESTAMP help?
-- It is just a temporary value.
-- On INSERT of explicit NULL into the column inserts current timestamp.
-- `created_date` timestamp not null default '0000-00-00 00:00:00', // same as above
-- `created_date` timestamp null default '0000-00-00 00:00:00',
-- inserting 'null' explicitly in INSERT statement inserts null (Ignoring the column inserts the default value)!
-- Remember we need current timestamp on insert of 'null'. So this won't work.
-- `created_date` timestamp null , // always inserts null. Equally useless as above.
-- `created_date` timestamp default 0, // alternative to '0000-00-00 00:00:00'
-- `created_date` timestamp,
-- first 'not null' timestamp column without 'default' value.
-- So implicitly adds DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP.
-- Hence cannot add 'ON UPDATE CURRENT_TIMESTAMP' on 'updated_date' column.
`updated_date` timestamp null on update current_timestamp,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=132 DEFAULT CHARSET=utf8;
INSERT INTO address (village,created_date) VALUES (100,null);
mysql> select * from address;
+-----+---------+---------------------+--------------+
| id | village | created_date | updated_date |
+-----+---------+---------------------+--------------+
| 132 | 100 | 2017-02-18 04:04:00 | NULL |
+-----+---------+---------------------+--------------+
1 row in set (0.00 sec)
UPDATE address SET village=101 WHERE village=100;
mysql> select * from address;
+-----+---------+---------------------+---------------------+
| id | village | created_date | updated_date |
+-----+---------+---------------------+---------------------+
| 132 | 101 | 2017-02-18 04:04:00 | 2017-02-18 04:06:14 |
+-----+---------+---------------------+---------------------+
1 row in set (0.00 sec)
Other option (But updated_date
is the first column):
CREATE TABLE `address` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`village` int(11) DEFAULT NULL,
`updated_date` timestamp null on update current_timestamp,
`created_date` timestamp not null ,
-- implicit default is '0000-00-00 00:00:00' from 2nd timestamp onwards
-- `created_date` timestamp not null default '0000-00-00 00:00:00'
-- `created_date` timestamp
-- `created_date` timestamp default '0000-00-00 00:00:00'
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=132 DEFAULT CHARSET=utf8;
No, you can't call one constructor from another in C++03 (called a delegating constructor).
This changed in C++11 (aka C++0x), which added support for the following syntax:
(example taken from Wikipedia)
class SomeType
{
int number;
public:
SomeType(int newNumber) : number(newNumber) {}
SomeType() : SomeType(42) {}
};
I think that you could use a POST or PATCH method to handle this since they typically design for this.
Using a POST
method is typically used to add an element when used on list resource but you can also support several actions for this method. See this answer: How to Update a REST Resource Collection. You can also support different representation formats for the input (if they correspond to an array or a single elements).
In the case, it's not necessary to define your format to describe the update.
Using a PATCH
method is also suitable since corresponding requests correspond to a partial update. According to RFC5789 (http://tools.ietf.org/html/rfc5789):
Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.
In the case, you have to define your format to describe the partial update.
I think that in this case, POST
and PATCH
are quite similar since you don't really need to describe the operation to do for each element. I would say that it depends on the format of the representation to send.
The case of PUT
is a bit less clear. In fact, when using a method PUT
, you should provide the whole list. As a matter of fact, the provided representation in the request will be in replacement of the list resource one.
You can have two options regarding the resource paths.
In this case, you need to explicitely provide the link of docs with a binder in the representation you provide in the request.
Here is a sample route for this /docs
.
The content of such approach could be for method POST
:
[
{ "doc_number": 1, "binder": 4, (other fields in the case of creation) },
{ "doc_number": 2, "binder": 4, (other fields in the case of creation) },
{ "doc_number": 3, "binder": 5, (other fields in the case of creation) },
(...)
]
In addition you could also consider to leverage sub routes to describe the link between docs and binders. The hints regarding the association between a doc and a binder doesn't have now to be specified within the request content.
Here is a sample route for this /binder/{binderId}/docs
. In this case, sending a list of docs with a method POST
or PATCH
will attach docs to the binder with identifier binderId
after having created the doc if it doesn't exist.
The content of such approach could be for method POST
:
[
{ "doc_number": 1, (other fields in the case of creation) },
{ "doc_number": 2, (other fields in the case of creation) },
{ "doc_number": 3, (other fields in the case of creation) },
(...)
]
Regarding the response, it's up to you to define the level of response and the errors to return. I see two levels: the status level (global level) and the payload level (thinner level). It's also up to you to define if all the inserts / updates corresponding to your request must be atomic or not.
In this case, you can leverage the HTTP status. If everything goes well, you get a status 200
. If not, another status like 400
if the provided data aren't correct (for example binder id not valid) or something else.
In this case, a status 200
will be returned and it's up to the response representation to describe what was done and where errors eventually occur. ElasticSearch has an endpoint in its REST API for bulk update. This could give you some ideas at this level: http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/bulk.html.
You can also implement an asynchronous processing to handle the provided data. In this case, the HTTP status returns will be 202
. The client needs to pull an additional resource to see what happens.
Before finishing, I also would want to notice that the OData specification addresses the issue regarding relations between entities with the feature named navigation links. Perhaps could you have a look at this ;-)
The following link can also help you: https://templth.wordpress.com/2014/12/15/designing-a-web-api/.
Hope it helps you, Thierry
The Java language specification says you can have return with no expression if your method returns void.
result() returns Object type data. . . . result_array() returns Associative Array type data.
To switch the display-style between block
and none
you can do something like this:
function toggleDiv(id) {
var div = document.getElementById(id);
div.style.display = div.style.display == "none" ? "block" : "none";
}
working demo: http://jsfiddle.net/BQUyT/2/
Came here looking for a solution to a similar issue, which I just introduced by changing Schannel settings of our IIS server using "IIS Crypto" by Nartac... By disabling the SHA-1 hash, the local SQL Server was not able to be reached anymore, even though I didn't use an encrypted connection (not useful for an ASP.Net site accessing a local SQL Express instance using shared memory).
Thanks Count Zero for pointing me in the right direction :-)
So, lesson learned: do not disable SHA-1 on your IIS server if you have a local SQL Server instance.
There is one rule that is set by font-awesome.css
, which you need to override.
You should set overrides in your CSS files rather than inline, but essentially, the icon-ok class is being set to vertical-align: baseline;
by default and which I've corrected here:
<button id="whatever" class="btn btn-large btn-primary" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Example here: http://jsfiddle.net/fPXFY/4/ and the output of which is:
I've downsized the font-size of the icon above in this instance to 30px
, as it feels too big at 40px
for the size of the button, but this is purely a personal viewpoint. You could increase the padding on the button to compensate if required:
<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Producing: http://jsfiddle.net/fPXFY/5/ the output of which is:
Let's dissect it. There are three parts:
cd
-- This is change directory command./d
-- This switch makes cd
change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0
. (%~d0
Changs active drive, cd %~p0
change the directory).%~dp0
-- This can be dissected further into three parts:
%0
-- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.%~0
-- The ~
there strips double quotes ("
) around the expanded argument.%dp0
-- The d
and p
there are modifiers of the expansion. The d
forces addition of a drive letter and the p
adds full path. $(function(){
$(document).find('div').siblings().each(function(){
var obj = $(this);
obj.find('div').each(function(){
var obj1 = $(this);
if(!obj1.children().length > 0){
alert(obj1.html());
}
});
});
});
<div id="2">
<div>
<div>
<div>XYZ Pvt. Ltd.</div>
</div>
</div>
</div>
<div id="3">
<div>
<div>
<div>ABC Pvt Ltd.</div>
</div>
</div>
</div>
Visual Paradigm SDE for IntellIJ (Community edition) Modelling Case Tool
You need to install proper software. Now it should works well.
I guess that UML Class Diagram is only available on Ultimate Edition.
To show UML diagram click right mouse button on specific class -> Diagrams -> Show diagram... Or you can in editor click Ctrl+Alt+Shift+U. You could append new classes to diagram by drag and drop. On the top of window you could choose more options. To save UML you should just click on save icon.
I would suggest you are looking at the problem in the wrong light. The questtion should be 'what am i doing that needs 2G memory inside a apache process with Php via apache module and is this tool set best suited for the job?'
Yes you can strap a rocket onto a ford pinto, but it's probably not the right solution.
Regardless, I'll provide the rocket if you really need it... you can add to the top of the script.
ini_set('memory_limit','2048M');
This will set it for just the script. You will still need to tell apache to allow that much for a php script (I think).
Always have handy the un-minified CSS for bootstrap so you can see what styles they have on their components, then create a CSS file AFTER it, if you don't use LESS and over-write their mixins or whatever
This is the default modal css for 768px and up:
@media (min-width: 768px) {
.modal-dialog {
width: 600px;
margin: 30px auto;
}
...
}
They have a class modal-lg
for larger widths
@media (min-width: 992px) {
.modal-lg {
width: 900px;
}
}
If you need something twice the 600px size, and something fluid, do something like this in your CSS after the Bootstrap css and assign that class to the modal-dialog.
@media (min-width: 768px) {
.modal-xl {
width: 90%;
max-width:1200px;
}
}
HTML
<div class="modal-dialog modal-xl">
Demo: http://jsbin.com/yefas/1
Try this
The following code will definitely work
RewriteEngine on
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [NC,L]
String user = request.getParameter("uname");
out.println(user);
String pass = request.getParameter("pass");
out.println(pass);
Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/rental","root","root" ) ;
out.println("hello");
Statement st = conn.createStatement();
String sql = "insert into login (user,pass) values('" + user + "','" + pass + "')";
st.executeUpdate(sql);
@Component({
selector: 'key-up3',
template: `
<input #box (keyup.enter)="doSomething($event)">
<p>{{values}}</p>
`
})
export class KeyUpComponent_v3 {
doSomething(e) {
alert(e);
}
}
This works for me!
See this bug: https://bugs.launchpad.net/ubuntu/+source/mysql-5.6/+bug/1435823
There seems to be a temporary fix there
Create a newfile /etc/tmpfiles.d/mysql.conf:
# systemd tmpfile settings for mysql
# See tmpfiles.d(5) for details
d /var/run/mysqld 0755 mysql mysql -
After reboot, mysql should start normally.
For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.
You can apply a theme to any activity by including android:theme
inside <activity>
inside manifest file.
For example:
<activity android:theme="@android:style/Theme.Dialog">
<activity android:theme="@style/CustomTheme">
And if you want to set theme programatically then use setTheme()
before calling setContentView()
and super.onCreate()
method inside onCreate()
method.
Definition
Aggregate method is an extension method for generic collections. Aggregate method applies a function to each item of a collection. Not just only applies a function, but takes its result as initial value for the next iteration. So, as a result, we will get a computed value (min, max, avg, or other statistical value) from a collection.
Therefore, Aggregate method is a form of safe implementation of a recursive function.
Safe, because the recursion will iterate over each item of a collection and we can’t get any infinite loop suspension by wrong exit condition. Recursive, because the current function’s result is used as a parameter for the next function call.
Syntax:
collection.Aggregate(seed, func, resultSelector);
How it works:
var nums = new[]{1, 2};
var result = nums.Aggregate(1, (result, n) => result + n); //result = (1 + 1) + 2 = 4
var result2 = nums.Aggregate(0, (result, n) => result + n, response => (decimal)response/2.0); //result2 = ((0 + 1) + 2)*1.0/2.0 = 3*1.0/2.0 = 3.0/2.0 = 1.5
Practical usage:
int n = 7;
var numbers = Enumerable.Range(1, n);
var factorial = numbers.Aggregate((result, x) => result * x);
which is doing the same thing as this function:
public static int Factorial(int n)
{
if (n < 1) return 1;
return n * Factorial(n - 1);
}
var numbers = new[]{3, 2, 6, 4, 9, 5, 7};
var avg = numbers.Aggregate(0.0, (result, x) => result + x, response => (double)response/(double)numbers.Count());
var min = numbers.Aggregate((result, x) => (result < x)? result: x);
var path = @“c:\path-to-folder”;
string[] txtFiles = Directory.GetFiles(path).Where(f => f.EndsWith(“.txt”)).ToArray<string>();
var output = txtFiles.Select(f => File.ReadAllText(f, Encoding.Default)).Aggregate<string>((result, content) => result + content);
File.WriteAllText(path + “summary.txt”, output, Encoding.Default);
Console.WriteLine(“Text files merged into: {0}”, output); //or other log info
You are doing everything right by using a to_date function and specifying the time. The time is there in the database. The trouble is just that when you select a column of DATE datatype from the database, the default format mask doesn't show the time. If you issue a
alter session set nls_date_format = 'dd/MON/yyyy hh24:mi:ss'
or something similar including a time component, you will see that the time successfully made it into the database.
I prefer to use the ngModel and ngChange directives when dealing with checkboxes. ngModel allows you to bind the checked/unchecked state of the checkbox to a property on the entity:
<input type="checkbox" ng-model="entity.isChecked">
Whenever the user checks or unchecks the checkbox the entity.isChecked
value will change too.
If this is all you need then you don't even need the ngClick or ngChange directives. Since you have the "Check All" checkbox, you obviously need to do more than just set the value of the property when someone checks a checkbox.
When using ngModel with a checkbox, it's best to use ngChange rather than ngClick for handling checked and unchecked events. ngChange is made for just this kind of scenario. It makes use of the ngModelController for data-binding (it adds a listener to the ngModelController's $viewChangeListeners
array. The listeners in this array get called after the model value has been set, avoiding this problem).
<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">
... and in the controller ...
var model = {};
$scope.model = model;
// This property is bound to the checkbox in the table header
model.allItemsSelected = false;
// Fired when an entity in the table is checked
$scope.selectEntity = function () {
// If any entity is not checked, then uncheck the "allItemsSelected" checkbox
for (var i = 0; i < model.entities.length; i++) {
if (!model.entities[i].isChecked) {
model.allItemsSelected = false;
return;
}
}
// ... otherwise ensure that the "allItemsSelected" checkbox is checked
model.allItemsSelected = true;
};
Similarly, the "Check All" checkbox in the header:
<th>
<input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>
... and ...
// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
// Loop through all the entities and set their isChecked property
for (var i = 0; i < model.entities.length; i++) {
model.entities[i].isChecked = model.allItemsSelected;
}
};
CSS
What is the best way to... add a CSS class to the
<tr>
containing the entity to reflect its selected state?
If you use the ngModel approach for the data-binding, all you need to do is add the ngClass directive to the <tr>
element to dynamically add or remove the class whenever the entity property changes:
<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">
See the full Plunker here.