Dialects are removed in recent SQL so use
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect"/>
Running yarn on Windows Linux subsystem with Ubunto OS, error "running beyond virtual memory limits, Killing container" I resolved it by disabling virtual memory check in the file yarn-site.xml
<property> <name>yarn.nodemanager.vmem-check-enabled</name> <value>false</value> </property>
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
Mate, my advice is to change virtual device. Download "Genimotion" application, its easy to use and there are a lot of any devices you need
solution for Bootstrap 4
You can use it
Alignment
use this class justify-content-center
Change the alignment of pagination components with flexbox utilities.
and learn more about it pagination
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
_x000D_
<nav aria-label="Page navigation example">_x000D_
<ul class="pagination justify-content-center">_x000D_
<li class="page-item disabled">_x000D_
<a class="page-link" href="#" tabindex="-1">Previous</a>_x000D_
</li>_x000D_
<li class="page-item"><a class="page-link" href="#">1</a></li>_x000D_
<li class="page-item"><a class="page-link" href="#">2</a></li>_x000D_
<li class="page-item"><a class="page-link" href="#">3</a></li>_x000D_
<li class="page-item">_x000D_
<a class="page-link" href="#">Next</a>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>
_x000D_
Show dialog anonymously as chain of commands & without defining another object:
new AlertDialog.Builder(this).setTitle("Confirm Delete?")
.setMessage("Are you sure?")
.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Perform Action & Dismiss dialog
dialog.dismiss();
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
})
.create()
.show();
The same solution as for Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL? should work - send a CREATE USER …
to \gexec
.
SELECT 'CREATE USER my_user'
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec
echo "SELECT 'CREATE USER my_user' WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec" | psql
See accepted answer there for more details.
To reference a commit, simply write its SHA-hash, and it'll automatically get turned into a link.
On my case I solved the problem after 2 hours :
The sender (a tabBar item) wasn't having any Referencing Outlet. So it was pointing nowhere.
Juste create a referencing outlet corresponding to your function.
Hope this could help you guys.
When doing Flask Basic auth I got this error and then I realized I had wrapped_view(**kwargs) and it worked after changing it to wrapped_view(*args, **kwargs).
Try =index(ARRAY, ROW, COLUMN)
where: Array: select the whole sheet Row, Column: Your row and column references
That should be easier to understand to those looking at the formula.
I had a similar issue using like pattern '%_%'
did not work - as the question indicates :-)
Using '%\_%'
did not work either as this first \
is interpreted "before the like".
Using '%\\_%'
works. The \\
(double backslash) is first converted to single \
(backslash) and then used in the like pattern.
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("@id","abc");
command.Parameters.Add("@username","abc");
command.Parameters.Add("@password","abc");
command.Parameters.Add("@email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@id", "abc");
command.Parameters.AddWithValue("@username", "abc");
command.Parameters.AddWithValue("@password", "abc");
command.Parameters.AddWithValue("@email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
You Also wanna put some text (placeholder) in the empty input box for the
.myClass {_x000D_
::-webkit-input-placeholder {_x000D_
color: #f00;_x000D_
}_x000D_
::-moz-placeholder {_x000D_
color: #f00;_x000D_
}_x000D_
/* firefox 19+ */_x000D_
:-ms-input-placeholder {_x000D_
color: #f00;_x000D_
}_x000D_
/* ie */_x000D_
input:-moz-placeholder {_x000D_
color: #f00;_x000D_
}_x000D_
}
_x000D_
<input type="text" class="myClass" id="fname" placeholder="Enter First Name Here!">
_x000D_
user to understand what to type.
i have done a similar thing, think it might help u its actually working for me
int main(){ int co[8],i;char ch[8];printf("please enter the string:");scanf("%s",ch);for(i=0;i<=7;i++){if((ch[i]>='A')&&(ch[i]<='F')){co[i]=(unsigned int)ch[i]-'A'+10;}else if((ch[i]>='0')&&(ch[i]<='9')){co[i]=(unsigned int)ch[i]-'0'+0;}}
here i have only taken a string of 8 characters. if u want u can add similar logic for 'a' to 'f' to give their equivalent hex values,i haven't done that cause i didn't needed it.
All the below answers would return you the list.Your need to convert it to matrix
def MATMUL(X, Y):
rows_A = len(X)
cols_A = len(X[0])
rows_B = len(Y)
cols_B = len(Y[0])
if cols_A != rows_B:
print "Matrices are not compatible to Multiply. Check condition C1==R2"
return
# Create the result matrix
# Dimensions would be rows_A x cols_B
C = [[0 for row in range(cols_B)] for col in range(rows_A)]
print C
for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
C[i][j] += A[i][k] * B[k][j]
C = numpy.matrix(C).reshape(len(A),len(B[0]))
return C
I was lead here in my Google searching. In a show of good faith I have included what I pieced together from parts of this code and other code I've gathered along the way.
# This script is useful if you have attributes or properties that span across several commandlets_x000D_
# and you wish to export a certain data set but all of the properties you wish to export are not_x000D_
# included in only one commandlet so you must use more than one to export the data set you want_x000D_
#_x000D_
# Created: Joshua Biddle 08/24/2017_x000D_
# Edited: Joshua Biddle 08/24/2017_x000D_
#_x000D_
_x000D_
$A = Get-ADGroupMember "YourGroupName"_x000D_
_x000D_
# Construct an out-array to use for data export_x000D_
$Results = @()_x000D_
_x000D_
foreach ($B in $A)_x000D_
{_x000D_
# Construct an object_x000D_
$myobj = Get-ADuser $B.samAccountName -Properties ScriptPath,Office_x000D_
_x000D_
# Fill the object_x000D_
$Properties = @{_x000D_
samAccountName = $myobj.samAccountName_x000D_
Name = $myobj.Name _x000D_
Office = $myobj.Office _x000D_
ScriptPath = $myobj.ScriptPath_x000D_
}_x000D_
_x000D_
# Add the object to the out-array_x000D_
$Results += New-Object psobject -Property $Properties_x000D_
_x000D_
# Wipe the object just to be sure_x000D_
$myobj = $null_x000D_
}_x000D_
_x000D_
# After the loop, export the array to CSV_x000D_
$Results | Select "samAccountName", "Name", "Office", "ScriptPath" | Export-CSV "C:\Temp\YourData.csv"
_x000D_
Cheers
For me only excluding the following classes worked:
import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class}) {
// ...
}
Your code (vector1 == vector2
) is correct C++ syntax. There is an ==
operator for vectors.
If you want to compare short vector with a portion of a longer vector, you can use theequal()
operator for vectors. (documentation here)
Here's an example:
using namespace std;
if( equal(vector1.begin(), vector1.end(), vector2.begin()) )
DoSomething();
I'm not sure if I am correct, but from the request header that you post:
Request headers
Accept: Application/json
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8
it seems like you didn't config your request body to JSON type.
A compiled language is always going to require a bigger initial overhead than an interpreted language. In addition, perhaps you didn't structure your C++ code very well. For example:
#include "BigClass.h"
class SmallClass
{
BigClass m_bigClass;
}
Compiles a lot slower than:
class BigClass;
class SmallClass
{
BigClass* m_bigClass;
}
As I can see, you are comparing the message with the empty string using ==.
Its very hard to write the full code, but I can tell the flow of code - first, create db class & method inide that which will return the connection. second, create a servelet(ex-login.java) & import that db class onto that servlet. third, create instance of imported db class with the help of new operator & call the connection method of that db class. fourth, creaet prepared statement & execute statement & put this code in try catch block for exception handling.Use if-else condition in the try block to navigate your login page based on success or failure.
I hope, it will help you. If any problem, then please revert.
Nikhil Pahariya
Setting alpha to 1
before starting the animation worked for me:
AlphaAnimation animation1 = new AlphaAnimation(0.2f, 1.0f);
animation1.setDuration(500);
iv.setAlpha(1f);
iv.startAnimation(animation1);
At least on my tests, there's no flickering because of setting alpha before starting the animation. It just works fine.
A complete example.
<?php
$units = explode(' ','B KB MB GB TB PB');
echo("<html><body>");
echo('file size: ' . format_size(filesize("example.txt")));
echo("</body></html>");
function format_size($size) {
$mod = 1024;
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
$endIndex = strpos($size, ".")+3;
return substr( $size, 0, $endIndex).' '.$units[$i];
}
?>
If you are using Java 8, use the code below.
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
httpConn.setRequestProperty ("Authorization", "Basic "+basicAuth);
step by step
given you have a textbox as following,
<asp:TextBox ID="TextBox13" runat="server"
onkeypress="return functionx(event)" >
</asp:TextBox>
you create a JavaScript function like this:
<script type = "text/javascript">
function functionx(evt)
{
if (evt.charCode > 31 && (evt.charCode < 48 || evt.charCode > 57))
{
alert("Allow Only Numbers");
return false;
}
}
</script>
the first part of the if-statement excludes the ASCII control chars, the or statements exclued anything, that is not a number
This error you are receiving :
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
is because the number of elements in $values
& $matches
is not the same or $matches
contains more than 1 element.
If $matches
contains more than 1 element, than the insert will fail, because there is only 1 column name referenced in the query(hash
)
If $values
& $matches
do not contain the same number of elements then the insert will also fail, due to the query expecting x params but it is receiving y data $matches
.
I believe you will also need to ensure the column hash has a unique index on it as well.
Try the code here:
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$matches = array('1');
$count = count($matches);
for($i = 0; $i < $count; ++$i) {
$values[] = '?';
}
// INSERT INTO DATABASE
$sql = "INSERT INTO hashes (hash) VALUES (" . implode(', ', $values) . ") ON DUPLICATE KEY UPDATE hash='hash'";
$stmt = $dbh->prepare($sql);
$data = $stmt->execute($matches);
//Error reporting if something went wrong...
var_dump($dbh->errorInfo());
?>
You will need to adapt it a little.
Table structure I used is here:
CREATE TABLE IF NOT EXISTS `hashes` (
`hashid` int(11) NOT NULL AUTO_INCREMENT,
`hash` varchar(250) NOT NULL,
PRIMARY KEY (`hashid`),
UNIQUE KEY `hash1` (`hash`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Code was run on my XAMPP Server which is using PHP 5.3.8 with MySQL 5.5.16.
I hope this helps.
I used this for a reruning of a program. I don't know if it would help, but it is a simple if statement requiring only two different entry's. It worked in powershell for me.
$rerun = Read-Host "Rerun report (y/n)?"
if($rerun -eq "y") { Show-MemoryReport }
if($rerun -eq "n") { Exit }
Don't know if this helps, but i believe this would be along the lines of terminating a program after you have run it. However in this case, every defined input requires a listed and categorized output. You could also have the exit call up a new prompt line and terminate the program that way.
ColorTip is the most beautiful i've ever seen
how will I know that some tables are locked?
You can use SHOW OPEN TABLES command to view locked tables.
how do I unlock tables manually?
If you know the session ID that locked tables - 'SELECT CONNECTION_ID()', then you can run KILL command to terminate session and unlock tables.
if ($("input").is(":not(:checked)"))
AFAIK, this should work, tested against the latest stable jQuery (1.2.6).
If you still don't know, you can get back the original object by:
alert($("#deviceTypeRoot")[0] == $("#deviceTypeRoot")[0]); //True
alert($("#deviceTypeRoot")[0] === $("#deviceTypeRoot")[0]);//True
because $("#deviceTypeRoot")
also returns an array of objects which the selector has selected.
I generally like the shorthand version:
if (!!wlocation) { window.location = wlocation; }
I had the same issue. Adding maximum-scale=1 fixed it:
OLD: <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
NEW: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
P.S. Also I have been using commas between values. But it seems to work with semi-colon as well.
It's a convention in Ruby that methods that return boolean values end in a question mark. There's no more significance to it than that.
This is a supplement answer related to the OP:
An easy and reliable solution to add Javadocs comments in Eclipse:
To use this tool, right-click on class and click on JAutodoc.
This is really just an expansion of Freddy Rios' accepted answer only using Generics.
public static bool IsNullOrDefault<T>(this Nullable<T> value) where T : struct
{
return default(T).Equals( value.GetValueOrDefault() );
}
public static bool IsValue<T>(this Nullable<T> value, T valueToCheck) where T : struct
{
return valueToCheck.Equals((value ?? valueToCheck));
}
NOTE we don't need to check default(T) for null since we are dealing with either value types or structs! This also means we can safely assume T valueToCheck will not be null; Remember here that T? is shorthand Nullable<T> so by adding the extension to Nullable<T> we get the method in int?, double?, bool? etc.
Examples:
double? x = null;
x.IsNullOrDefault(); //true
int? y = 3;
y.IsNullOrDefault(); //false
bool? z = false;
z.IsNullOrDefault(); //true
This will remove any number of blank lines
CTRL + H to replace
Select Extended search mode
replace all \r\n
with (space)
then switch to regular expression and replace all \s+
with \n
It seems the docs/tool have been updated and you can now add the image
tag to your script. This was successful for me.
Example:
version: '2'
services:
baggins.api.rest:
image: my.image.name:rc2
build:
context: ../..
dockerfile: app/Docker/Dockerfile.release
ports:
...
The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:
m + geom_boxplot() + scale_y_continuous(trans='log10')
EDIT: Or if you don't like that, then either of these appears to give different but useful results:
m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot()
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()
EDIT2 & 3: Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):
fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) +
geom_boxplot() +
scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)
Note added mid 2017 in comment about package syntax change:
scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)
EDIT: If you're a designer then Papyrus is your best choice it's very advanced and full of features, but if you just want to sketch out some UML diagrams and easy installation then ObjectAid is pretty cool and it doesn't require any plugins I just installed it over Eclipse-Java EE and works great !.
UPDATE Oct 11th, 2013
My original post was in June 2012 a lot of things have changed many tools has grown and others didn't. Since I'm going back to do some modeling and also getting some replies to the post I decided to install papyrus again and will investigate other possible UML modeling solutions again. UML generation (with synchronization feature) is really important not to software designer but to the average developer.
I wish papyrus had straightforward way to Reverse Engineer classes into UML class diagram and It would be super cool if that reverse engineering had a synchronization feature, but unfortunately papyrus project is full of features and I think developers there have already much at hand since also many actions you do over papyrus might not give you any response and just nothing happens but that's out of this question scope anyway.
The Answer (Oct 11th, 2013)
Tools
Steps
Right click on MyProject_kdm.xmi -> Discovery -> Discoverer -> Discover UML model from KDM code again you'll get a property dialog set the serialization prop to TRUE to generate a file named MyProject.uml
Move generated MyProject.uml which was generated at root, to UML folder, Eclipse will ask you If you wanted to replace it click yes. What we did in here was that we replaced an empty model with a generated one.
ALT+W -> show view -> papyrus -> model explorer
In that view, you'll find your classes like in the picture
In the view Right click root model -> New diagram
Then start grabbing classes to the diagram from the view
Some features
To show the class elements (variables, functions etc) Right click on any class -> Filters -> show/hide contents Voila !!
You can have default friendly color settings from Window -> pereferences -> papyrus -> class diagram
one very important setting is Arrange when you drop the classes they get a cramped right click on any empty space at a class diagram and click Arrange All
Arrows in the model explorer view can be grabbed to the diagram to show generalization, realization etc
After all of that your settings will show diagrams like
Synchronization isn't available as far as I know you'll need to manually import any new classes.
That's all, And don't buy commercial products unless you really need it, papyrus is actually great and sophisticated instead donate or something.
Disclaimer: I've no relation to the papyrus people, in fact, I didn't like papyrus at first until I did lots of research and experienced it with some patience. And will get back to this post again when I try other free tools.
But that doesn't seem like the proper way to do it..
That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.
Example:
const promises = [_x000D_
new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
.then(data => {_x000D_
console.log("First handler", data);_x000D_
return data.map(entry => entry * 10);_x000D_
})_x000D_
.then(data => {_x000D_
console.log("Second handler", data);_x000D_
});
_x000D_
(catch
handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)
The output we see from that is:
First handler [1,2] Second handler [10,20]
...because the first handler gets the resolution of the two promises (1
and 2
) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.
If the additional work you're doing is synchronous, you can also put it in the first handler:
Example:
const promises = [_x000D_
new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
.then(data => {_x000D_
console.log("Initial data", data);_x000D_
data = data.map(entry => entry * 10);_x000D_
console.log("Updated data", data);_x000D_
return data;_x000D_
});
_x000D_
...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.
Extract jar file for ex. with winrar and use CAVAJ:
Cavaj Java Decompiler is a graphical freeware utility that reconstructs Java source code from CLASS files.
here is video tutorial if you need: https://www.youtube.com/watch?v=ByLUeem7680
You can use https://github.com/douzi8/ajax-request#download
request.download('http://res.m.ctrip.com/html5/Content/images/57.png',
function(err, res, body) {}
);
The better answers to this only work for specific lengths of lists that are provided.
Here's a version that works for any lengths of input. It also makes the algorithm clear in terms of the mathematical concepts of combination and permutation.
from itertools import combinations, permutations
list1 = ['1', '2']
list2 = ['A', 'B', 'C']
num_elements = min(len(list1), len(list2))
list1_combs = list(combinations(list1, num_elements))
list2_perms = list(permutations(list2, num_elements))
result = [
tuple(zip(perm, comb))
for comb in list1_combs
for perm in list2_perms
]
for idx, ((l11, l12), (l21, l22)) in enumerate(result):
print(f'{idx}: {l11}{l12} {l21}{l22}')
This outputs:
0: A1 B2
1: A1 C2
2: B1 A2
3: B1 C2
4: C1 A2
5: C1 B2
public class NonKeyboardEditText extends AppCompatEditText {
public NonKeyboardEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onCheckIsTextEditor() {
return false;
}
}
and add
NonKeyboardEditText.setTextIsSelectable(true);
A one-liner:
var encodedMsg = $('<div />').text(message).html();
See it work:
try $conn = mysql_connect("localhost", "root")
or $conn = mysql_connect("localhost", "root", "")
I used an approach similar to the one taken by Josh Fraser, which determines the browser time offset from UTC and whether it recognizes DST or not (but somewhat simplified from his code):
var ClientTZ = {
UTCoffset: 0, // Browser time offset from UTC in minutes
UTCoffsetT: '+0000S', // Browser time offset from UTC in '±hhmmD' form
hasDST: false, // Browser time observes DST
// Determine browser's timezone and DST
getBrowserTZ: function () {
var self = ClientTZ;
// Determine UTC time offset
var now = new Date();
var date1 = new Date(now.getFullYear(), 1-1, 1, 0, 0, 0, 0); // Jan
var diff1 = -date1.getTimezoneOffset();
self.UTCoffset = diff1;
// Determine DST use
var date2 = new Date(now.getFullYear(), 6-1, 1, 0, 0, 0, 0); // Jun
var diff2 = -date2.getTimezoneOffset();
if (diff1 != diff2) {
self.hasDST = true;
if (diff1 - diff2 >= 0)
self.UTCoffset = diff2; // East of GMT
}
// Convert UTC offset to ±hhmmD form
diff2 = (diff1 < 0 ? -diff1 : diff1) / 60;
var hr = Math.floor(diff2);
var min = diff2 - hr;
diff2 = hr * 100 + min * 60;
self.UTCoffsetT = (diff1 < 0 ? '-' : '+') + (hr < 10 ? '0' : '') + diff2.toString() + (self.hasDST ? 'D' : 'S');
return self.UTCoffset;
}
};
// Onload
ClientTZ.getBrowserTZ();
Upon loading, the ClientTZ.getBrowserTZ()
function is executed, which sets:
ClientTZ.UTCoffset
to the browser time offset from UTC in minutes (e.g., CST is -360 minutes, which is -6.0 hours from UTC);ClientTZ.UTCoffsetT
to the offset in the form '±hhmmD'
(e.g., '-0600D'
), where the suffix is D
for DST and S
for standard (non-DST);ClientTZ.hasDST
(to true or false).The ClientTZ.UTCoffset
is provided in minutes instead of hours, because some timezones have fractional hourly offsets (e.g., +0415).
The intent behind ClientTZ.UTCoffsetT
is to use it as a key into a table of timezones (not provided here), such as for a drop-down <select>
list.
Just to throw in another example. Imagine you have the following list:
nums = [4,2,2,1,3]
and you want to turn it into a dict where the key is the index and value is the element in the list. You can do so with the following line of code:
{index:nums[index] for index in range(0,len(nums))}
you don't.
the constructor is part of the class that can implement an interface. The interface is just a contract of methods the class must implement.
A cleaner alternative would be to use a Dictionary
to handle parameters. They are key-value pairs after all.
private static readonly HttpClient httpclient;
static MyClassName()
{
// HttpClient is intended to be instantiated once and re-used throughout the life of an application.
// Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.
// This will result in SocketException errors.
// https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
httpclient = new HttpClient();
}
var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);
var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
// Do something with response. Example get content:
// var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}
Also dont forget to Dispose()
httpclient, if you dont use the keyword using
As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.
Edit:
You may want to look into response.EnsureSuccessStatusCode();
instead of if (response.StatusCode == HttpStatusCode.OK)
.
You may want to keep your httpclient and dont Dispose()
it. See: Do HttpClient and HttpClientHandler have to be disposed?
Edit:
Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html
I like PodTech.io's answer to achieve this without additional tools. For me, it did not run out of the box, so I had to slightly change it. I am not sure if the command wScript.Sleep 12000
(12 sec delay) in the original script is required or not, so I kept it.
Here's the modified script Zip.cmd
based on his answer, which works fine on my end:
@echo off
if "%1"=="" goto end
setlocal
set TEMPDIR=%TEMP%\ZIP
set FILETOZIP=%1
set OUTPUTZIP=%2.zip
if "%2"=="" set OUTPUTZIP=%1.zip
:: preparing VBS script
echo Set objArgs = WScript.Arguments > _zipIt.vbs
echo InputFolder = objArgs(0) >> _zipIt.vbs
echo ZipFile = objArgs(1) >> _zipIt.vbs
echo Set fso = WScript.CreateObject("Scripting.FileSystemObject") >> _zipIt.vbs
echo Set objZipFile = fso.CreateTextFile(ZipFile, True) >> _zipIt.vbs
echo objZipFile.Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipIt.vbs
echo objZipFile.Close >> _zipIt.vbs
echo Set objShell = WScript.CreateObject("Shell.Application") >> _zipIt.vbs
echo Set source = objShell.NameSpace(InputFolder).Items >> _zipIt.vbs
echo Set objZip = objShell.NameSpace(fso.GetAbsolutePathName(ZipFile)) >> _zipIt.vbs
echo if not (objZip is nothing) then >> _zipIt.vbs
echo objZip.CopyHere(source) >> _zipIt.vbs
echo wScript.Sleep 12000 >> _zipIt.vbs
echo end if >> _zipIt.vbs
@ECHO Zipping, please wait...
mkdir %TEMPDIR%
xcopy /y /s %FILETOZIP% %TEMPDIR%
WScript _zipIt.vbs %TEMPDIR% %OUTPUTZIP%
del _zipIt.vbs
rmdir /s /q %TEMPDIR%
@ECHO ZIP Completed.
:end
Usage:
One parameter (no wildcards allowed here):
Zip FileToZip.txt
will create FileToZip.txt.zip
in the same folder containing the zipped file FileToZip.txt
.
Two parameters (optionally with wildcards for the first parameter), e.g.
Zip *.cmd Scripts
creates Scripts.zip
in the same folder containing all matching *.cmd
files.
Note: If you want to debug the VBS script, check out this hint, it describes how to activate the debugger to go through it step by step.
A multiple select is really just a select with a multiple
attribute. With that in mind, it should be as easy as...
Form::select('sports[]', $sports, null, array('multiple'))
The first parameter is just the name, but post-fixing it with the []
will return it as an array when you use Input::get('sports')
.
The second parameter is an array of selectable options.
The third parameter is an array of options you want pre-selected.
The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple
property to the actual select element..
//STEP01 EXEC SORT90MB
//SORTJNF1 DD DSN=INPUTFILE1,
// DISP=SHR
//SORTJNF2 DD DSN=INPUTFILE2,
// DISP=SHR
//SORTOUT DD DSN=MISMATCH_OUTPUT_FILE,
// DISP=(,CATLG,DELETE),
// UNIT=TAPE,
// DCB=(RECFM=FB,BLKSIZE=0),
// DSORG=PS
//SYSOUT DD SYSOUT=*
//SYSIN DD *
JOINKEYS FILE=F1,FIELDS=(1,79,A)
JOINKEYS FILE=F2,FIELDS=(1,79,A)
JOIN UNPAIRED,F1,ONLY
SORT FIELDS=COPY
/*
Use TOP 1
if the query returns multiple rows.
SELECT TOP 1 @ModelID = m.modelid
FROM MODELS m
WHERE m.areaid = 'South Coast'
I had the same issue with Python3.
My code was writing into io.BytesIO()
.
Replacing with io.StringIO()
solved.
Directory.GetFiles(@"C:\Users\AliBayat","*",SearchOption.AllDirectories)
.Select (d => new FileInfo(d))
.Select (d => new { Directory = d.DirectoryName,FileSize = d.Length} )
.ToLookup (d => d.Directory )
.Select (d => new { Directory = d.Key,TotalSizeInMB =Math.Round(d.Select (x =>x.FileSize)
.Sum () /Math.Pow(1024.0,2),2)})
.OrderByDescending (d => d.TotalSizeInMB).ToList();
Calling GetFiles
with SearchOption.AllDirectories
returns the full name of all the files in all the subdirectories
of the specified directory. The OS represents the size of files in bytes. You can retrieve the file’s size from its Length property. Dividing it by 1024 raised to the power of 2 gives you the size of the file in megabytes. Because a directory/folder can contain many files, d.Select(x => x.FileSize)
returns a collection of file sizes measured in megabytes. The final call to Sum()
finds the total size of the files in the specified directory.
Update: the filterMask="." does not work with files without extension
node recommends executing following:
sudo chown -R $USER:$(id -gn $USER) /home/venkatesh/.config
If you execute
npm config
You will see something like this
¦ npm update check failed ¦
¦ Try running with sudo or get access ¦
¦ to the local update config store via ¦
¦ sudo chown -R $USER:$(id -gn $USER) /home/venkatesh/.config ¦
It worked for me.
We don't know what server.properties file is that, we neither know what SimocoPoolSize means (do you?)
Let's guess you are using some custom pool of database connections. Then, I guess the problem is that your pool is configured to open 100 or 120 connections, but you Postgresql server is configured to accept MaxConnections=90
. These seem conflictive settings. Try increasing MaxConnections=120
.
But you should first understand your db layer infrastructure, know what pool are you using, if you really need so many open connections in the pool. And, specially, if you are gracefully returning the opened connections to the pool
Square brackets:
jsObj['key' + i] = 'example' + 1;
In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length
property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0"
, "5"
, "207"
, and so on, are all treated specially in that their existence determines the value of length
. And, on top of that, the value of length
can be set to remove such properties. Setting the length
of an array to 0
effectively removes all properties whose names look like whole numbers.
OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ]
operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.
Thus, the way the [ ]
operator works in a for
loop iterating through an array:
for (var i = 0; i < myArray.length; ++i) {
var value = myArray[i]; // property access
// ...
}
is really no different from the way [ ]
works when accessing a property whose name is some computed string:
var value = jsObj["key" + i];
The [ ]
operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.
When setting property values using [ ]
, the story is the same except for the special behavior around maintaining the length
property. If you set a property with a numeric key on an array instance:
myArray[200] = 5;
then (assuming that "200" is the biggest numeric property name) the length
property will be updated to 201
as a side-effect of the property assignment. If the same thing is done to a plain object, however:
myObj[200] = 5;
there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5
in otherwise the exact same way.
One might think that because that length
behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length
but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:
var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;
var objJSON = JSON.stringify(obj);
the value of "objJSON" will be a string containing just ["hello world"]
; the "something" property will be lost.
If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:
var key = 'DYNAMIC_KEY',
obj = {
[key]: 'ES6!'
};
console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }
If you have a module with a class you want to import, you can do it like this.
module = __import__(filename)
instance = module.MyClass()
If you do not know what the class is named, you can iterate through the classes available from a module.
import inspect
module = __import__(filename)
for c in module.__dict__.values():
if inspect.isclass(c):
# You may need do some additional checking to ensure
# it's the class you want
instance = c()
I had a similar task where I needed to delete multiple objects at once based on a property of the objects in the array.
So after a few iterations I end up with:
list = $.grep(list, function (o) { return !o.IsDeleted });
If you want to remove all lines in a file from your current line number, use dG
, it will delete all lines (shift g)
mean end of file
You can easily use ng-show such as :
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div ng-show="isExists(item)">available</div>
<div ng-show="!isExists(item)">oh no, you don't have it</div>
</div>
For more complex tests, you can use ng-switch statements :
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div ng-switch on="isExists(item)">
<span ng-switch-when="true">Available</span>
<span ng-switch-default>oh no, you don't have it</span>
</div>
</div>
I was just searching for an answer to this exact question, come to find out the command itself adjusts the buffer!
mode con:cols=140 lines=70
The lines=70 part actually adjusts the Height in the 'Screen Buffer Size' setting, NOT the Height in the 'Window Size' setting.
Easily proven by running the command with a setting for 'lines=2500' (or whatever buffer you want) and then check the 'Properties' of the window, you'll see that indeed the buffer is now set to 2500.
My batch script ends up looking like this:
@echo off cmd "mode con:cols=140 lines=2500"
I arrived here because I thought I should check in SO if there are adequate answers, after a syntax error that gave me this error, or if I could possibly post an answer myself.
OK, the answers here explain what this error is, so not much more to say, but nevertheless I will give my 2 cents using my words:
This error is caused by the fact that you basically generate a new table with your subquery for the FROM
command.
That's what a derived table
is, and as such, it needs to have an alias
(actually a name reference to it).
So given the following hypothetical query:
SELECT id, key1
FROM (
SELECT t1.ID id, t2.key1 key1, t2.key2 key2, t2.key3 key3
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
WHERE t2.key3 = 'some-value'
) AS tt
So, at the end, the whole subquery inside the FROM
command will produce the table that is aliased as tt
and it will have the following columns id
, key1
, key2
, key3
.
So, then with the initial SELECT
from that table we finally select the id
and key1
from the tt
.
You need to do encode
on tmp[0]
, not on tmp
.
tmp
is not a string. It contains a (Unicode) string.
Try running type(tmp)
and print dir(tmp)
to see it for yourself.
There are two ways to handle CGI scripts, SetHandler
and AddHandler
.
SetHandler cgi-script
applies to all files in a given context, no matter how they are named, even index.html
or style.css
.
AddHandler cgi-script .pl
is similar, but applies to files ending in .pl
, in a given context. You may choose another extension or several, if you like.
Additionally, the CGI module must be loaded and Options +ExecCGI
configured. To activate the module, issue
a2enmod cgi
and restart or reload Apache. Finally, the Perl CGI script must be executable. So the execute bits must be set
chmod a+x script.pl
and it should start with
#! /usr/bin/perl
as its first line.
When you use SetHandler
or AddHandler
(and Options +ExecCGI
) outside of any directive, it is applied globally to all files. But you may restrict the context to a subset by enclosing these directives inside, e.g. Directory
<Directory /path/to/some/cgi-dir>
SetHandler cgi-script
Options +ExecCGI
</Directory>
Now SetHandler
applies only to the files inside /path/to/some/cgi-dir instead of all files of the web site. Same is with AddHandler
inside a Directory
or Location
directive, of course. It then applies to the files inside /path/to/some/cgi-dir, ending in .pl
.
If you use jCanvas library you can use opacity property when drawing. If you need fade effect on top of that, simply redraw with different values.
You can catch it like any other exception:
try {
foo();
}
catch (const std::bad_alloc&) {
return -1;
}
Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.
In general you cannot, and should not try, to respond to this error. bad_alloc
indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.
Worse, modern operating systems often over-allocate: on such systems, malloc
and new
can return a valid pointer even if there is not enough free memory left – std::bad_alloc
will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).
The only thing you could do when catching std::bad_alloc
is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).
In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:
It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1
OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:
lru_cache<widget> widget_cache;
double perform_operation(int widget_id) {
std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
if (not maybe_widget) {
maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
}
return maybe_widget->frobnicate();
}
…
for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
try {
return perform_operation(widget_id);
} catch (std::bad_alloc const&) {
if (widget_cache.empty()) throw; // memory error elsewhere.
widget_cache.remove_oldest();
}
}
// Handle too many failed attempts here.
But even here, using std::set_new_handler
instead of handling std::bad_alloc
provides the same benefit and would be much simpler.
1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.
new
in c++?The usual notion is that if new
operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc
.
However, something more happens even before a bad_alloc
exception is thrown:
C++03 Section 3.7.4.1.3: says
An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.
Consider the following code sample:
#include <iostream>
#include <cstdlib>
// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
std::cerr << "Unable to satisfy request for memory\n";
std::abort();
}
int main()
{
//set the new_handler
std::set_new_handler(outOfMemHandler);
//Request huge memory size, that will cause ::operator new to fail
int *pBigDataArray = new int[100000000L];
return 0;
}
In the above example, operator new
(most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler()
will be called, and the program will abort after issuing an error message.
As seen here the default behavior of new
operator when unable to fulfill a memory request, is to call the new-handler
function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort()
, outOfMemHandler()
would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.
new_handler
and set_new_handler
?new_handler
is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler
is a function that takes and returns a new_handler
.
Something like:
typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();
set_new_handler's parameter is a pointer to the function operator new
should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.
Given the behavior of new
a well designed user program should handle out of memory conditions by providing a proper new_handler
which does one of the following:
Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.
Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler
). The next time operator new calls the new-handler function, it will get the one most recently installed.
(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)
Uninstall the new-handler: This is done by passing a null pointer to set_new_handler
. With no new-handler installed, operator new
will throw an exception ((convertible to) std::bad_alloc
) when memory allocation is unsuccessful.
Throw an exception convertible to std::bad_alloc
. Such exceptions are not be caught by operator new
, but will propagate to the site originating the request for memory.
Not return: By calling abort
or exit
.
With React Functional way
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import Button from "@material-ui/core/Button";
const App = () => {
const saySomething = (something) => {
console.log(something);
};
useEffect(() => {
saySomething("from useEffect");
});
const handleClick = (e) => {
saySomething("element clicked");
};
return (
<Button variant="contained" color="primary" onClick={handleClick}>
Hello World
</Button>
);
};
ReactDOM.render(<App />, document.querySelector("#app"));
The line that starts or ends the here-doc probably has some non-printable or whitespace characters (for example, carriage return) which means that the second "EOF" does not match the first, and doesn't end the here-doc like it should. This is a very common error, and difficult to detect with just a text editor. You can make non-printable characters visible for example with cat
:
cat -A myfile.sh
Once you see the output from cat -A
the solution will be obvious: remove the offending characters.
As you can see in the below source code, BeanUtils.copyProperties internally uses reflection and there's additional internal cache lookup steps as well which is going to add cost wrt performance
private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
@Nullable String... ignoreProperties) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
if (editable != null) {
if (!editable.isInstance(target)) {
throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
"] not assignable to Editable class [" + editable.getName() + "]");
}
actualEditable = editable;
}
**PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);**
List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
for (PropertyDescriptor targetPd : targetPds) {
Method writeMethod = targetPd.getWriteMethod();
if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null) {
Method readMethod = sourcePd.getReadMethod();
if (readMethod != null &&
ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
try {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
}
catch (Throwable ex) {
throw new FatalBeanException(
"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
}
}
}
}
}
}
So it's better to use plain setters given the cost reflection
I'm using the following in VC++ and it works like a charm for me.
CA2CT(charText)
For everyone coming to this thread with fractional seconds in your timestamp use:
to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')
You need to put that code into the constructor of your class:
private Reminders reminder = new Reminders();
private dynamic defaultReminder;
public YourClass()
{
defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}
The reason is that you can't use one instance variable to initialize another one using a field initializer.
Using:
SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
...will show you the ctn_no
value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:
SELECT t.ctn_no
FROM YOUR_TABLE t
WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
If you want to see the other column values associated with the duplicate, you'll want to use a self join:
SELECT x.*
FROM YOUR_TABLE x
JOIN (SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no
In my case, the solution is:
[ngModel]="X?.Y" (ngModelChange)="X.Y=$event"
Also, you may want to try Data::Dumper. Example:
use Data::Dumper;
# simple procedural interface
print Dumper($foo, $bar);
To give a more up-to-date approach.
package.json
"scripts": {
"eslint": "eslint index.js",
"pretest": "npm install",
"test": "npm run eslint",
"preversion": "npm run test",
"version": "",
"postversion": "git push && git push --tags && npm publish"
}
Then you run it:
npm version minor --force -m "Some message to commit"
Which will:
... run tests ...
change your package.json
to a next minor version (e.g: 1.8.1 to 1.9.0)
push your changes
create a new git tag release and
publish your npm package.
--force
is to show who is the boss! Jokes aside see https://github.com/npm/npm/issues/8620
DateTime now = DateTime.Now;
now.ToLongDateString(); // Wednesday, January 2, 2019
now.ToLongTimeString(); // 2:33:59 PM
now.ToShortDateString(); // 1/2/2019
now.ToShortTimeString(); // 2:16 PM
now.ToString(); // 1/2/2019 2:33:59 PM
plot
has a plot.function
method
plot(eq, 1, 1000)
Or
curve(eq, 1, 1000)
You could also check the request accept content type as specified in the rfc. That way you can render by default HTML and where your client accept application/jason you can return json in your response without a template being required
I've already commented it but I still think is a valid option, just test if in your environment is better one solution or the other. In my particular case, using source.ForEach(p => dest.Add(p))
performs better than the classic AddRange
but I've not investigated why at the low level.
You can see an example code here: https://gist.github.com/mcliment/4690433
So the option would be:
var allProducts = new List<Product>(productCollection1.Count +
productCollection2.Count +
productCollection3.Count);
productCollection1.ForEach(p => allProducts.Add(p));
productCollection2.ForEach(p => allProducts.Add(p));
productCollection3.ForEach(p => allProducts.Add(p));
Test it to see if it works for you.
Disclaimer: I'm not advocating for this solution, I find Concat
the most clear one. I just stated -in my discussion with Jon- that in my machine this case performs better than AddRange
, but he says, with far more knowledge than I, that this does not make sense. There's the gist if you want to compare.
I know it's a little late for an answer, but I've created a polyfill for the .live() method. I've tested it in jQuery 1.11, and it seems to work pretty well. I know that we're supposed to implement the .on() method wherever possible, but in big projects, where it's not possible to convert all .live() calls to the equivalent .on() calls for whatever reason, the following might work:
if(jQuery && !jQuery.fn.live) {
jQuery.fn.live = function(evt, func) {
$('body').on(evt, this.selector, func);
}
}
Just include it after you load jQuery and before you call live().
You can download a list of CA certificates from curl's website at http://curl.haxx.se/ca/cacert.pem
Then set the SSL_CERT_FILE environment variable to tell Ruby to use it. For example, in Linux:
$ SSL_CERT_FILE=~/cacert.pem bundle install
(Reference: https://gist.github.com/fnichol/867550)
The accepted answer will return all the parent nodes too. To get only the actual nodes with ABC even if the string is after
:
//*[text()[contains(.,'ABC')]]/text()[contains(.,"ABC")]
You can install any application/packages with brew on mac. If you want to know the exact command just search your package on https://brewinstall.org and you will get the set of commands needed to install that package.
First open terminal and install brew
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null
Now Install jq
brew install jq
Another simple way:
Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
I tried the following and it didn't work on my environment:
bindingProvider.getRequestContext().put("com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory", getCustomSocketFactory());
But different property worked like a charm:
bindingProvider.getRequestContext().put(JAXWSProperties.SSL_SOCKET_FACTORY, getCustomSocketFactory());
The rest of the code was taken from the first reply.
If all you want is to invoke foo
, and you prefer to propagate the exception as is (without wrapping), you can also just use Java's for
loop instead (after turning the Stream into an Iterable with some trickery):
for (A a : (Iterable<A>) as::iterator) {
a.foo();
}
This is, at least, what I do in my JUnit tests, where I don't want to go through the trouble of wrapping my checked exceptions (and in fact prefer my tests to throw the unwrapped original ones)
I've just set up a quick benchmarking exercise:
Function time to run 1 million iterations
--------------------------------------------
(int) "123": 0.55029
intval("123"): 1.0115 (183%)
(int) "0": 0.42461
intval("0"): 0.95683 (225%)
(int) int: 0.1502
intval(int): 0.65716 (438%)
(int) array("a", "b"): 0.91264
intval(array("a", "b")): 1.47681 (162%)
(int) "hello": 0.42208
intval("hello"): 0.93678 (222%)
On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.
I'd be interested to know why though.
Update: I've run the tests again, this time with coercion (0 + $var)
| INPUT ($x) | (int) $x |intval($x) | 0 + $x |
|-----------------|------------|-----------|-----------|
| "123" | 0.51541 | 0.96924 | 0.33828 |
| "0" | 0.42723 | 0.97418 | 0.31353 |
| 123 | 0.15011 | 0.61690 | 0.15452 |
| array("a", "b") | 0.8893 | 1.45109 | err! |
| "hello" | 0.42618 | 0.88803 | 0.1691 |
|-----------------|------------|-----------|-----------|
Addendum: I've just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods:
$x = "11";
(int) $x; // int(11)
intval($x); // int(11)
$x + 0; // int(11)
$x = "0x11";
(int) $x; // int(0)
intval($x); // int(0)
$x + 0; // int(17) !
$x = "011";
(int) $x; // int(11)
intval($x); // int(11)
$x + 0; // int(11) (not 9)
Tested using PHP 5.3.1
mysqli_error()
As in:
$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);
Trigger error is better than die because you can use it for development AND production, it's the permanent solution.
How about this solution for node.js https://github.com/mattbornski/tzwhere
And its Python counterpart: https://github.com/pegler/pytzwhere
When using Navicat you can go to types (under view -> others -> types) - get the design view of the type - and click the "add label" button.
Split it on the ,
character;
var string = "0,1";
var array = string.split(",");
alert(array[0]);
Something like this:
JSONObject songs= json.getJSONObject("songs");
Iterator x = songs.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(songs.get(key));
}
If you have the process ID (PID
) you can kill this process as follow:
Process processToKill = Process.GetProcessById(pid);
processToKill.Kill();
You could also do this:
#!/usr/bin/perl
use strict;
use warnings;
$^I = '.bak'; # create a backup copy
while (<>) {
s/<PREF>/ABCD/g; # do the replacement
print; # print to the modified file
}
Invoke the script with by
./script.pl input_file
You will get a file named input_file
, containing your changes, and a file named input_file.bak
, which is simply a copy of the original file.
I found it on this page: http://eslint.org/docs/user-guide/configuring
In package.json, this works:
"eslintConfig": {
"globals": {
"window": true
}
}
Well considering simplicity and speed as your primary criteria, you can add a small generic helper like this :-
// C++ rand generates random numbers between 0 and RAND_MAX. This is quite a big range
// Normally one would want the generated random number within a range to be really
// useful. So the arguments have default values which can be overridden by the caller
int nextRandomNum(int low = 0, int high = 100) const {
int range = (high - low) + 1;
// this modulo operation does not generate a truly uniformly distributed random number
// in the span (since in most cases lower numbers are slightly more likely),
// but it is generally a good approximation for short spans. Use it if essential
//int res = ( std::rand() % high + low );
int res = low + static_cast<int>( ( range * std::rand() / ( RAND_MAX + 1.0) ) );
return res;
}
Random number generation is a well studied, complex and advanced topic. You can find some simple but useful algorithms here apart from the ones mentioned in other answers:-
ASP.NET Core will automatically bind form values
, route values
and query strings
by name. This means you can simply do this:
[HttpGet()]
public IActionResult Get(int page)
{ ... }
MVC will try to bind request data to the action parameters by name ... below is a list of the data sources in the order that model binding looks through them
Form values
: These are form values that go in the HTTP request using the POST method. (including jQuery POST requests).
Route values
: The set of route values provided by Routing
Query strings
: The query string part of the URI.
Source: Model Binding in ASP.NET Core
FYI, you can also combine the automatic and explicit approaches:
[HttpGet()]
public IActionResult Get(int page
, [FromQuery(Name = "page-size")] int pageSize)
{ ... }
What is meta_key
? Strip out all of the meta_value
conditionals, reduce, and you end up with this:
SELECT
*
FROM
meta_data
WHERE
(
(meta_key = 'lat')
)
AND
(
(meta_key = 'long')
)
GROUP BY
item_id
Since meta_key
can never simultaneously equal two different values, no results will be returned.
Based on comments throughout this question and answers so far, it sounds like you're looking for something more along the lines of this:
SELECT
*
FROM
meta_data
WHERE
(
(meta_key = 'lat')
AND
(
(meta_value >= '60.23457047672217')
OR
(meta_value <= '60.23457047672217')
)
)
OR
(
(meta_key = 'long')
AND
(
(meta_value >= '24.879140853881836')
OR
(meta_value <= '24.879140853881836')
)
)
GROUP BY
item_id
Note the OR
between the top-level conditionals. This is because you want records which are lat
or long
, since no single record will ever be lat
and long
.
I'm still not sure what you're trying to accomplish by the inner conditionals. Any non-null value will match those numbers. So maybe you can elaborate on what you're trying to do there. I'm also not sure about the purpose of the GROUP BY
clause, but that might be outside the context of this question entirely.
The collection.count is deprecated, and will be removed in a future version. Use collection.countDocuments or collection.estimatedDocumentCount instead.
userModel.countDocuments(query).exec((err, count) => {
if (err) {
res.send(err);
return;
}
res.json({ count: count });
});
e.currentTarget
is always the element the event is actually bound do. e.target
is the element the event originated from, so e.target
could be a child of e.currentTarget
, or e.target
could be === e.currentTarget
, depending on how your markup is structured.
Using an ORDER BY
in a subquery is not the best solution to this problem.
The best solution to get the max(post_date)
by author is to use a subquery to return the max date and then join that to your table on both the post_author
and the max date.
The solution should be:
SELECT p1.*
FROM wp_posts p1
INNER JOIN
(
SELECT max(post_date) MaxPostDate, post_author
FROM wp_posts
WHERE post_status='publish'
AND post_type='post'
GROUP BY post_author
) p2
ON p1.post_author = p2.post_author
AND p1.post_date = p2.MaxPostDate
WHERE p1.post_status='publish'
AND p1.post_type='post'
order by p1.post_date desc
If you have the following sample data:
CREATE TABLE wp_posts
(`id` int, `title` varchar(6), `post_date` datetime, `post_author` varchar(3))
;
INSERT INTO wp_posts
(`id`, `title`, `post_date`, `post_author`)
VALUES
(1, 'Title1', '2013-01-01 00:00:00', 'Jim'),
(2, 'Title2', '2013-02-01 00:00:00', 'Jim')
;
The subquery is going to return the max date and author of:
MaxPostDate | Author
2/1/2013 | Jim
Then since you are joining that back to the table, on both values you will return the full details of that post.
See SQL Fiddle with Demo.
To expand on my comments about using a subquery to accurate return this data.
MySQL does not force you to GROUP BY
every column that you include in the SELECT
list. As a result, if you only GROUP BY
one column but return 10 columns in total, there is no guarantee that the other column values which belong to the post_author
that is returned. If the column is not in a GROUP BY
MySQL chooses what value should be returned.
Using the subquery with the aggregate function will guarantee that the correct author and post is returned every time.
As a side note, while MySQL allows you to use an ORDER BY
in a subquery and allows you to apply a GROUP BY
to not every column in the SELECT
list this behavior is not allowed in other databases including SQL Server.
Just to add another option to the mix, there are several useful constants within the string
module. While more useful in other cases, they can be used here.
>>> from string import digits
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'
There are several constants in the module, including:
ascii_letters
(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ)hexdigits
(0123456789abcdefABCDEF)If you are using these constants heavily, it can be worthwhile to covert them to a frozenset
. That enables O(1) lookups, rather than O(n), where n is the length of the constant for the original strings.
>>> digits = frozenset(digits)
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'
When you #include
a header, it's exactly as if you put the code into the source file itself. In both cases the varGlobal
variable is defined in the source so it will work no matter how it's declared.
Also as pointed out in the comments, C++ variables at file scope are not static in scope even though they will be assigned to static storage. If the variable were a class member for example, it would need to be accessible to other compilation units in the program by default and non-class members are no different.
To send json to the server, you first have to create json
function sendData() {
$.ajax({
url: '/helloworld',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
name:"Bob",
...
}),
dataType: 'json'
});
}
This is how you would structure the ajax request to send the json as a post var.
function sendData() {
$.ajax({
url: '/helloworld',
type: 'POST',
data: { json: JSON.stringify({
name:"Bob",
...
})},
dataType: 'json'
});
}
The json will now be in the json
post var.
Try using the property ForeColor. Like this :
TextBox1.ForeColor = Color.Red;
Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.
In the code. I have used VBScript and embedded it in HTML. Try it out!
<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--
Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset
Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString
dim form1
Set form1 = document.Register
Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value
connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")
End Sub
//-->
</script>
</head>
<body>
<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name: <input type="text" name="Name">
Age: <input type="text" name="Age">
Address: <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form>
</p>
</pre>
</body>
</html>
using select-object
for example:
Get-ADUser -Filter * -SearchBase 'OU=Users & Computers, DC=aaaaaaa, DC=com' -Properties DisplayName | select -expand displayname | Export-CSV "ADUsers.csv"
Have you tried Autodia yet? Last time I tried it it wasn't perfect, but it was good enough.
I see two problems here, one with sourceSet
another with mainClassName
.
Either move java source files to src/main/java
instead of just src
. Or set sourceSet
properly by adding the following to build.gradle.
sourceSets.main.java.srcDirs = ['src']
mainClassName
should be fully qualified class name, not path.
mainClassName = "hello.HelloWorld"
Try to create a php.ini
file in root and write the following command in and save it.
disable_functions =
Using this code will enable the phpinfo() function for you if it is disabled by the global PHP configuration.
We also had this problem when upgrading our system to Revive. After turning of GZIP we found the problem still persisted. Upon further investigation we found the file permissions where not correct after the upgrade. A simple recursive chmod did the trick.
Be careful, -
has a special meaning with regexp. In a []
, you can put it without problem if it is placed at the end. In your case, ,-:
is taken as from ,
to :
.
Cast the datetime to a date, then GROUP BY using this syntax:
SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate);
Or you can GROUP BY the alias as @orlandu63 suggested:
SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly;
Though I don't think it'll make any difference to performance, it is a little clearer.
The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[]
with an index read from stream. Try vector::at()
instead of vector::operator[]
. This won't solve your problem, but will show which assignment to the vector causes error.
Another possibility is that setting dataType: json
causes JQuery to send the Content-Type: application/json
header. This is considered a non-standard header by CORS, and requires a CORS preflight request. So a few things to try:
1) Try configuring your server to send the proper preflight responses. This will be in the form of additional headers like Access-Control-Allow-Methods
and Access-Control-Allow-Headers
.
2) Drop the dataType: json
setting. JQuery should request Content-Type: application/x-www-form-urlencoded
by default, but just to be sure, you can replace dataType: json
with contentType: 'application/x-www-form-urlencoded'
I think you need the SCHEDULER_ADMIN role to see the dba_scheduler tables (however this may grant you too may rights)
see: http://download.oracle.com/docs/cd/B28359_01/server.111/b28310/schedadmin001.htm
You might not be able to change npm registry using .bat
file as Gntem pointed out.
But I understand that you need the ability to automate changing registries.
You can do so by having your .npmrc
configs in separate files (say npmrc_jfrog & npmrc_default) and have your .bat
files do the copying task.
For example (in Windows):
Your default_registry.bat
will have
xcopy /y npmrc_default .npmrc
and your jfrog_registry.bat
will have
xcopy /y npmrc_jfrog .npmrc
Note: /y
suppresses prompting to confirm that you want to overwrite an existing destination file.
This will make sure that all the config properties (registry, proxy, apiKeys, etc.) get copied over to .npmrc
.
You can read more about xcopy here.
Disable swipe progmatically by-
final View touchView = findViewById(R.id.Pager);
touchView.setOnTouchListener(new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
return true;
}
});
and use this to swipe manually
touchView.setCurrentItem(int index);
In Windows 7, make sure Event Viewer closed before deleting.
Try the following:
java -cp jar1:jar2:jar3:dir1:. HelloWorld
The default classpath (unless there is a CLASSPATH environment variable) is the current directory so if you redefine it, make sure you're adding the current directory (.) to the classpath as I have done.
For split string by space like in Python lang, can be used:
var w = "hello my brothers ;";
w.split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
output:
["hello", "my", "brothers", ";"]
or similar:
w.split(/(\s+)/).filter( e => e.trim().length > 0)
(output some)
In Windows 10 I had to run the batch file as an administrator.
With library(lubridate)
, numeric representations of date and time saved as the number of seconds since
1970-01-01 00:00:00 UTC, can be coerced into dates with as_datetime()
:
lubridate::as_datetime(1352068320)
[1] "2012-11-04 22:32:00 UTC"
If you have removed package using Uninstall-Package utility and deleted the desired package from package directory under solution (and you are still getting error), just open up the *.csproj file in code editor and remove the tag manually. Like for instance, I wanted to get rid of Nuget package Xamarin.Forms.Alias and I removed these lines from *.csproj file.
And finally, don't forget to reload your project once prompted in Visual Studio (after changing project file). I tried it on Visual Studio 2015, but it should work on Visual Studio 2010 and onward too.
Hope this helps.
Answer 1 : Yes it called upcasting but the way you do it is not modern way. Upcasting can be performed implicitly you don't need any conversion. So just writing Employee emp = mgr; is enough for upcasting.
Answer 2 : If you create object of Manager class we can say that manager is an employee. Because class Manager : Employee depicts Is-A relationship between Employee Class and Manager Class. So we can say that every manager is an employee.
But if we create object of Employee class we can not say that this employee is manager because class Employee is a class which is not inheriting any other class. So you can not directly downcast that Employee Class object to Manager Class object.
So answer is, if you want to downcast from Employee Class object to Manager Class object, first you must have object of Manager Class first then you can upcast it and then you can downcast it.
DNS server is obtained via
getprop net.dns1
UPDATE: as of Android Nougat 7.x, ifconfig is present, and netcfg is gone. So ifconfig can be used to find the IP and netmask.
SELECT *
FROM DBA_OBJECTS
WHERE OBJECT_TYPE = 'VIEW'
The runtime type of the object is a relatively arbitrary condition to filter on. I suggest keeping such muckiness away from your collection. This is simply achieved by having your collection delegate to a filter passed in a construction.
public interface FilterObject {
boolean isAllowed(Object obj);
}
public class FilterOptimizedList<E> implements List<E> {
private final FilterObject filter;
...
public FilterOptimizedList(FilterObject filter) {
if (filter == null) {
throw NullPointerException();
}
this.filter = filter;
}
...
public int indexOf(Object obj) {
if (!filter.isAllows(obj)) {
return -1;
}
...
}
...
}
final List<String> longStrs = new FilterOptimizedList<String>(
new FilterObject() { public boolean isAllowed(Object obj) {
if (obj == null) {
return true;
} else if (obj instanceof String) {
String str = (String)str;
return str.length() > = 4;
} else {
return false;
}
}}
);
If you go here you can find a comprehensive matrix that includes both the NLog and Log4Net libs as well as Enterprise Lib and other products.
Somebody could argue that the matrix is done in a way to underline the features of the only commercial lib present in the matrix. I think it's true but it was useful anyway to drive my choice versus NLog.
Regards
The code in my previous answer can be simplified to:
def test_afunction_throws_exception(self):
self.assertRaises(ExpectedException, afunction)
And if afunction takes arguments, just pass them into assertRaises like this:
def test_afunction_throws_exception(self):
self.assertRaises(ExpectedException, afunction, arg1, arg2)
All you need to do is put a type tag and make the type button.
<button id="btnId" type="button">Hide/Show</button>
_x000D_
That solves the issue
ESLint defaults to ES5 syntax-checking. You'll want to override to the latest well-supported version of JavaScript.
Try adding a .eslintrc
file to your project. Inside it:
{
"parserOptions": {
"ecmaVersion": 2017
},
"env": {
"es6": true
}
}
Hopefully this helps.
EDIT: I also found this example .eslintrc
which might help.
contains
method uses equals
internally. So you need to override the equals
method for your class as per your need.
Btw this does not look syntatically correct:
new Object().setName("John")
While you should certainly provide more information, if you are trying to go through each row, you can just iterate with a for loop:
import numpy
m = numpy.ones((3,5),dtype='int')
for row in m:
print str(row)
the best way for me :
$data=[
'var1'=>'something',
'var2'=>'something',
'var3'=>'something',
];
return View::make('view',$data);
Add another option, maybe not the most lightweight.
dayjs.extend(dayjs_plugin_customParseFormat)
console.log(dayjs('2018-09-06 17:00:00').format( 'YYYY-MM-DDTHH:mm:ss.000ZZ'))
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/plugin/customParseFormat.js"></script>
_x000D_
You actually cannot draw Container Elements
But you can use a "foreignObject" with a "SVG" inside it to simulate what you need.
<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
<foreignObject id="G" width="300" height="200">
<svg>
<rect fill="blue" stroke-width="2" height="112" width="84" y="55" x="55" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000"/>
<ellipse fill="#FF0000" stroke="#000000" stroke-width="5" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" cx="155" cy="65" id="svg_7" rx="64" ry="56"/>
</svg>
<style>
#G {
background: #cff; border: 1px dashed black;
}
#G:hover {
background: #acc; border: 1px solid black;
}
</style>
</foreignObject>
</svg>
For me it worked by adding android:textAllCaps="true" and android:inputType="textCapCharacters"
<android.support.design.widget.TextInputEditText
android:layout_width="fill_parent"
android:layout_height="@dimen/edit_text_height"
android:textAllCaps="true"
android:inputType="textCapCharacters"
/>
Based on the op voted solution, the following should be a bit more efficient:
public static byte [] hexStringToByteArray (final String s) {
if (s == null || (s.length () % 2) == 1)
throw new IllegalArgumentException ();
final char [] chars = s.toCharArray ();
final int len = chars.length;
final byte [] data = new byte [len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit (chars[i], 16) << 4) + Character.digit (chars[i + 1], 16));
}
return data;
}
Because: the initial conversion to a char array spares the length checks in charAt
you can wrap the content of the <tbody>
in a scrollable <div>
:
html
....
<tbody>
<tr>
<td colspan="2">
<div class="scrollit">
<table>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
...
css
.scrollit {
overflow:scroll;
height:100px;
}
see my jsfiddle, forked from yours: http://jsfiddle.net/VTNax/2/
I target the 1024 pixel monitors (but don't use 100% of that space). I've given up on those with 800x600. I'd rather punish the few with outdated hardware by making them scroll if they need to, versus punishing everyone with new equipment by wasting space.
I suppose it depends on your audience, and the nature of you app though.
I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->
return .Cell(i,1) <> Empty
It's very very simple when you use a library to do that for you. Try this library
You can call like this:
Icon.on(holderView).color(R.color.your_color).icon(R.mipmap.your_icon).put();
Change it to
public static class LinqHelper
Properties that are database specific are:
hibernate.connection.driver_class
: JDBC driver classhibernate.connection.url
: JDBC URLhibernate.connection.username
: database userhibernate.connection.password
: database passwordhibernate.dialect
: The class name of a Hibernate org.hibernate.dialect.Dialect
which allows Hibernate to generate SQL optimized for a particular relational database. To change the database, you must:
Dialect
used by Hibernate to talk to the databaseThere are two drivers to connect to SQL Server; the open source jTDS and the Microsoft one. The driver class and the JDBC URL depend on which one you use.
The driver class name is net.sourceforge.jtds.jdbc.Driver
.
The URL format for sqlserver is:
jdbc:jtds:sqlserver://<server>[:<port>][/<database>][;<property>=<value>[;...]]
So the Hibernate configuration would look like (note that you can skip the hibernate.
prefix in the properties):
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="connection.url">jdbc:jtds:sqlserver://<server>[:<port>][/<database>]</property>
<property name="connection.username">sa</property>
<property name="connection.password">lal</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
...
</session-factory>
</hibernate-configuration>
The driver class name is com.microsoft.sqlserver.jdbc.SQLServerDriver
.
The URL format is:
jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
So the Hibernate configuration would look like:
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://[serverName[\instanceName][:portNumber]];databaseName=<databaseName></property>
<property name="connection.username">sa</property>
<property name="connection.password">lal</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
...
</session-factory>
</hibernate-configuration>
do a phpinfo(), and look for session.save_path. the directory there needs to have the correct permissions for the user and/or group that your webserver runs as
I created a function for a Volley Request. You just need to pass the arguments :
public void callvolly(final String username, final String password){
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = "http://your_url.com/abc.php"; // <----enter your post url here
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
@Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("username", username);
MyData.put("password", password);
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}
To send $scope object
from one controller to another, I will discuss about $rootScope.$broadcast
and $rootScope.$emit
here as they are used most.
Case 1:
$rootScope.$broadcast:-
$rootScope.$broadcast('myEvent',$scope.data);//Here `myEvent` is event name
$rootScope.$on('myEvent', function(event, data) {} //listener on `myEvent` event
$rootScope
listener are not destroyed automatically. You need to destroy it using $destroy
. It is better to use $scope.$on
as listeners on $scope
are destroyed automatically i.e. as soon as $scope is destroyed.
$scope.$on('myEvent', function(event, data) {}
Or,
var customeEventListener = $rootScope.$on('myEvent', function(event, data) {
}
$scope.$on('$destroy', function() {
customeEventListener();
});
Case 2:
$rootScope.$emit:
$rootScope.$emit('myEvent',$scope.data);
$rootScope.$on('myEvent', function(event, data) {}//$scope.$on not works
The major difference in $emit and $broadcast is that $rootScope.$emit event must be listened using $rootScope.$on, because the emitted event never comes down through the scope tree..
In this case also you must destroy the listener as in the case of $broadcast.
Edit:
I prefer not to use
$rootScope.$broadcast + $scope.$on
but use$rootScope.$emit+ $rootScope.$on
. The$rootScope.$broadcast + $scope.$on
combo can cause serious performance problems. That is because the event will bubble down through all scopes.
Edit 2:
The issue addressed in this answer have been resolved in angular.js version 1.2.7. $broadcast now avoids bubbling over unregistered scopes and runs just as fast as $emit.
This is a bit late, but I think you could use the --limit or -l
command to limit the pattern to more specific hosts. (version 2.3.2.0)
You could have
- hosts: all (or group)
tasks:
- some_task
and then ansible-playbook playbook.yml -l some_more_strict_host_or_pattern
and use the --list-hosts
flag to see on which hosts this configuration would be applied.
The initial issue is solved by changing lat
and lon
to double.
I want to add comment to solution with Location location = locationManager.getLastKnownLocation(bestProvider);
It works to find out last known location when other app was lisnerning for that. If, for example, no app did that since device start, the code will return zeros (spent some time myself recently to figure that out).
Also, it's a good practice to stop listening when there is no need for that by locationManager.removeUpdates(this);
Also, even with permissions in manifest
, the code works when location service is enabled in Android settings on a device.
I was having the same issue, as everyone else I suppose.. adding the System.setProperties(....) didn't fix it for me.
So my email client is in a separate project uploaded to an artifactory. I'm importing this project into other projects as a gradle dependency. My problem was that I was using implementation
in my build.gradle for javax.mail
, which was causing issues downstream.
I changed this line from implementation
to api
and my downstream project started working and connecting again.
Here's a simple example..
List<char> c = new List<char>() { 'A', 'B', 'C' };
List<string> s = c.Select(x => x.ToString()).ToList();
I typically use
:%s/\r/\r/g
which seems a little odd, but works because of the way that Vim matches linefeeds. I also find it easier to remember :)
The reason for the collision seems to be because, by default, the context root, "/", is to be handled by org.apache.catalina.servlets.DefaultServlet. This servlet is intended to handle requests for static resources.
If you decide to bump it out of the way with your own servlet, with the intent of handling dynamic requests, that top-level servlet must also carry out any tasks accomplished by catalina's original "DefaultServlet" handler.
If you read through the tomcat docs, they make mention that True Apache (httpd) is better than Apache Tomcat for handling static content, since it is purpose built to do just that. My guess is because Tomcat by default uses org.apache.catalina.servlets.DefaultServlet to handle static requests. Since it's all wrapped up in a JVM, and Tomcat is intended to as a Servlet/JSP container, they probably didn't write that class as a super-optimized static content handler. It's there. It gets the job done. Good enough.
But that's the thing that handles static content and it lives at "/". So if you put anything else there, and that thing doesn't handle static requests, WHOOPS, there goes your static resources.
I've been searching high and low for the same answer and the answer I'm getting everywhere is "if you don't want it to do that, don't do that".
So long story short, your configuration is displacing the default static resource handler with something that isn't a static resource handler at all. You'll need to try a different configuration to get the results you're looking for (as will I).
SQL 2008 also allows you to disable lock escalation on specific tables. I have found this very useful on small frequently updated tables where locks can escalate causing concurrency issues. In SQL 2005, even with the ROWLOCK hint on delete statements locks can be escalated which can lead to deadlocks. In my testing, an application which I have developed had concurrency issues during small table manipulation due to lock escalation on SQL 2005. In SQL 2008 this problem went away.
It is still important to bear in mind the potential overhead of handling large numbers of row locks, but having the option to stop escalation when you want to is very useful.
using vector::insert (const_iterator position, initializer_list il); http://www.cplusplus.com/reference/vector/vector/insert/
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec;
vec.insert(vec.end(),{1,2,3,4});
return 0;
}
If you want to use SelectedValue then your combobox must be databound.
To set up the combobox:
ComboBox1.DataSource = GetMailItems()
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
To get the data:
Function GetMailItems() As List(Of MailItem)
Dim mailItems = New List(Of MailItem)
Command = New MySqlCommand("SELECT * FROM `maillist` WHERE l_id = '" & id & "'", connection)
Command.CommandTimeout = 30
Reader = Command.ExecuteReader()
If Reader.HasRows = True Then
While Reader.Read()
mailItems.Add(New MailItem(Reader("ID"), Reader("name")))
End While
End If
Return mailItems
End Function
Public Class MailItem
Public Sub New(ByVal id As Integer, ByVal name As String)
mID = id
mName = name
End Sub
Private mID As Integer
Public Property ID() As Integer
Get
Return mID
End Get
Set(ByVal value As Integer)
mID = value
End Set
End Property
Private mName As String
Public Property Name() As String
Get
Return mName
End Get
Set(ByVal value As String)
mName = value
End Set
End Property
End Class
For Typescript users, the "atom-typescript" package adds a typescript aware symbols view, you can trigger it with Cmd+R, and it works great to jump to methods-
https://atom.io/packages/atom-typescript#alternative-to-symbols-view
I ran into this exact issue and couldn't get around it by any of the solutions mentioned.
Then I finally found a solution. It appears that the serializer needs not only the type, but the nested types as well. Changing this:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
To this:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T).GetNestedTypes());
Fixed the issue for me. No more exceptions or anything.
For Windows 8 client computers, turn on "IIS-ASPNET45" in "Turn Windows Features On/Off" under "Internet Information Services-> World Wide Web Services -> Application Development Features -> ASP.NET 4.5".
If the imagestr was bitmap data (which we now know it isn't) you could use this
imagestr
is the base64 encoded string
width
is the width of the image
height
is the height of the image
from PIL import Image
from base64 import decodestring
image = Image.fromstring('RGB',(width,height),decodestring(imagestr))
image.save("foo.png")
Since the imagestr is just the encoded png data
from base64 import decodestring
with open("foo.png","wb") as f:
f.write(decodestring(imagestr))
You are better off just generating a random long value, then all the bits are random. In Java 6, new Random() uses the System.nanoTime() plus a counter as a seed.
There are different levels of uniqueness.
If you need uniqueness across many machines, you could have a central database table for allocating unique ids, or even batches of unique ids.
If you just need to have uniqueness in one app you can just have a counter (or a counter which starts from the currentTimeMillis()*1000 or nanoTime() depending on your requirements)
const absolutePath = path.join(__dirname, some, dir);
vs.
const absolutePath = path.resolve(__dirname, some, dir);
path.join
will concatenate __dirname
which is the directory name of the current file concatenated with values of some
and dir
with platform-specific separator.
Whereas
path.resolve
will process __dirname
, some
and dir
i.e. from right to left prepending it by processing it.
If any of the values of some
or dir
corresponds to a root path then the previous path will be omitted and process rest by considering it as root
In order to better understand the concept let me explain both a little bit more detail as follows:-
The path.join
and path.resolve
are two different methods or functions of the path module provided by nodejs.
Where both accept a list of paths but the difference comes in the result i.e. how they process these paths.
path.join
concatenates all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. While the path.resolve()
process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.
When no arguments supplied
The following example will help you to clearly understand both concepts:-
My filename is index.js
and the current working directory is E:\MyFolder\Pjtz\node
const path = require('path');
console.log("path.join() : ", path.join());
// outputs .
console.log("path.resolve() : ", path.resolve());
// outputs current directory or equivalent to __dirname
Result
? node index.js
path.join() : .
path.resolve() : E:\MyFolder\Pjtz\node
path.resolve()
method will output the absolute path whereas the path.join()
returns . representing the current working directory if nothing is provided
When some root path is passed as arguments
const path=require('path');
console.log("path.join() : " ,path.join('abc','/bcd'));
console.log("path.resolve() : ",path.resolve('abc','/bcd'));
Result i
? node index.js
path.join() : abc\bcd
path.resolve() : E:\bcd
path.join()
only concatenates the input list with platform-specific separator while the path.resolve()
process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.
For me worked the following:
sudo gitlab-ctl stop
sudo gitlab-ctl start gitaly
sudo gitlab-rake gitlab:setup [type yes and let it finish]
sudo gitlab-ctl start
I am using:
gitlab_edition: "gitlab-ce"
gitlab_version: '12.4.0-ce.0.el7'
My 'hack' solution is
<div class="col-sm-5">
<laps
[lapsData]="rawLapsData"
[selectedTps]="selectedTps"
(lapsHandler)="lapsHandler($event)">
</laps>
</div>
<map
[lapsData]="rawLapsData"
[selectedTps]="selectedTps" // <--------
class="col-sm-7">
</map>
selectedTps changes at the same time as rawLapsData and that gives map another chance to detect the change through a simpler object primitive type. It is NOT elegant, but it works.
Here is my solution:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select The Difficulty Level");
builder.setCancelable(false);
This is another thread pool implementation that is very simple, easy to understand and use, uses only C++11 standard library, and can be looked at or modified for your uses, should be a nice starter if you want to get into using thread pools:
To get the negation, do this ...
df.filter(not( ..expression.. ))
eg
df.filter(not($"state" === "TX"))
I don't think the real difference became clear in the above answers.
First to get the terms right:
Martin's answer is right so far. However, the actual question is: What is the purpose of declaring a nested class static or not?
You use static nested classes if you just want to keep your classes together if they belong topically together or if the nested class is exclusively used in the enclosing class. There is no semantic difference between a static nested class and every other class.
Non-static nested classes are a different beast. Similar to anonymous inner classes, such nested classes are actually closures. That means they capture their surrounding scope and their enclosing instance and make that accessible. Perhaps an example will clarify that. See this stub of a Container:
public class Container {
public class Item{
Object data;
public Container getContainer(){
return Container.this;
}
public Item(Object data) {
super();
this.data = data;
}
}
public static Item create(Object data){
// does not compile since no instance of Container is available
return new Item(data);
}
public Item createSubItem(Object data){
// compiles, since 'this' Container is available
return new Item(data);
}
}
In this case you want to have a reference from a child item to the parent container. Using a non-static nested class, this works without some work. You can access the enclosing instance of Container with the syntax Container.this
.
More hardcore explanations following:
If you look at the Java bytecodes the compiler generates for an (non-static) nested class it might become even clearer:
// class version 49.0 (49)
// access flags 33
public class Container$Item {
// compiled from: Container.java
// access flags 1
public INNERCLASS Container$Item Container Item
// access flags 0
Object data
// access flags 4112
final Container this$0
// access flags 1
public getContainer() : Container
L0
LINENUMBER 7 L0
ALOAD 0: this
GETFIELD Container$Item.this$0 : Container
ARETURN
L1
LOCALVARIABLE this Container$Item L0 L1 0
MAXSTACK = 1
MAXLOCALS = 1
// access flags 1
public <init>(Container,Object) : void
L0
LINENUMBER 12 L0
ALOAD 0: this
ALOAD 1
PUTFIELD Container$Item.this$0 : Container
L1
LINENUMBER 10 L1
ALOAD 0: this
INVOKESPECIAL Object.<init>() : void
L2
LINENUMBER 11 L2
ALOAD 0: this
ALOAD 2: data
PUTFIELD Container$Item.data : Object
RETURN
L3
LOCALVARIABLE this Container$Item L0 L3 0
LOCALVARIABLE data Object L0 L3 2
MAXSTACK = 2
MAXLOCALS = 3
}
As you can see the compiler creates a hidden field Container this$0
. This is set in the constructor which has an additional parameter of type Container to specify the enclosing instance. You can't see this parameter in the source but the compiler implicitly generates it for a nested class.
Martin's example
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
would so be compiled to a call of something like (in bytecodes)
new InnerClass(outerObject)
For the sake of completeness:
An anonymous class is a perfect example of a non-static nested class which just has no name associated with it and can't be referenced later.
I've faced this same problem recently and came across to this thread but my problem was with React
App. Below changes in the node start command solved my issues.
node --max-old-space-size=<size> path-to/fileName.js
node --max-old-space-size=16000 scripts/build.js
Basically, it varies depends on the allocated memory to that thread and your node settings.
This is basically stay in our engine v8
. below code helps you to understand the Heap Size of your local node v8 engine.
const v8 = require('v8');
const totalHeapSize = v8.getHeapStatistics().total_available_size;
const totalHeapSizeGb = (totalHeapSize / 1024 / 1024 / 1024).toFixed(2);
console.log('totalHeapSizeGb: ', totalHeapSizeGb);
It's also possible to pre-allocate large enough memory size. Here is a simple stack implementation: the program is supposed to output 3 and 5.
class Stk {
static public final int STKSIZ = 256;
public int[] info = new int[STKSIZ];
public int sp = 0; // stack pointer
public void push(int value) {
info[sp++] = value;
}
}
class App {
public static void main(String[] args) {
Stk stk = new Stk();
stk.push(3);
stk.push(5);
System.out.println(stk.info[0]);
System.out.println(stk.info[1]);
}
}
For me, this is the best autofit and autoresize for table and its columns (use css !important ... only if you can't without)
.myclass table {
table-layout: auto !important;
}
.myclass th, .myclass td, .myclass thead th, .myclass tbody td, .myclass tfoot td, .myclass tfoot th {
width: auto !important;
}
Don't specify css width for table or for table columns. If table content is larger it will go over screen size to.
Try this, it will convert True into 1 and False into 0:
data.frame$column.name.num <- as.numeric(data.frame$column.name)
Then you can convert into factor if you want:
data.frame$column.name.num.factor <- as .factor(data.frame$column.name.num)
You might want Python's UUID functions:
21.15. uuid — UUID objects according to RFC 4122
eg:
import uuid
print uuid.uuid4()
7d529dd4-548b-4258-aa8e-23e34dc8d43d
Group By X
means put all those with the same value for X in the one group.
Group By X, Y
means put all those with the same values for both X and Y in the one group.
To illustrate using an example, let's say we have the following table, to do with who is attending what subject at a university:
Table: Subject_Selection
+---------+----------+----------+
| Subject | Semester | Attendee |
+---------+----------+----------+
| ITB001 | 1 | John |
| ITB001 | 1 | Bob |
| ITB001 | 1 | Mickey |
| ITB001 | 2 | Jenny |
| ITB001 | 2 | James |
| MKB114 | 1 | John |
| MKB114 | 1 | Erica |
+---------+----------+----------+
When you use a group by
on the subject column only; say:
select Subject, Count(*)
from Subject_Selection
group by Subject
You will get something like:
+---------+-------+
| Subject | Count |
+---------+-------+
| ITB001 | 5 |
| MKB114 | 2 |
+---------+-------+
...because there are 5 entries for ITB001, and 2 for MKB114
If we were to group by
two columns:
select Subject, Semester, Count(*)
from Subject_Selection
group by Subject, Semester
we would get this:
+---------+----------+-------+
| Subject | Semester | Count |
+---------+----------+-------+
| ITB001 | 1 | 3 |
| ITB001 | 2 | 2 |
| MKB114 | 1 | 2 |
+---------+----------+-------+
This is because, when we group by two columns, it is saying "Group them so that all of those with the same Subject and Semester are in the same group, and then calculate all the aggregate functions (Count, Sum, Average, etc.) for each of those groups". In this example, this is demonstrated by the fact that, when we count them, there are three people doing ITB001 in semester 1, and two doing it in semester 2. Both of the people doing MKB114 are in semester 1, so there is no row for semester 2 (no data fits into the group "MKB114, Semester 2")
Hopefully that makes sense.
I know its 2 months but yeah
replace your code
Private TextView err;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enviar_mensaje);
err = (TextView)findViewById(R.id.texto);
err.setText("Escriba su mensaje y luego seleccione el canal.");
}
Use LIKE ANY(ARRAY['AAA%', 'BBB%', 'CCC%'])
as per this cool trick @maniek showed earlier today.
When you share for Facebook, you have to add in your html into the head section next meta tags:
<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />
And that's it!
Add the button as you should according to what FB tells you.
All the info you need is in www.facebook.com/share/
1) The function returns a cell for a table view yes? So, the returned object is of type UITableViewCell
. These are the objects that you see in the table's rows. This function basically returns a cell, for a table view.
But you might ask, how the function would know what cell to return for what row, which is answered in the 2nd question
2)NSIndexPath
is essentially two things-
Because your table might be divided to many sections and each with its own rows, this NSIndexPath
will help you identify precisely which section and which row. They are both integers. If you're a beginner, I would say try with just one section.
It is called if you implement the UITableViewDataSource
protocol in your view controller. A simpler way would be to add a UITableViewController
class. I strongly recommend this because it Apple has some code written for you to easily implement the functions that can describe a table. Anyway, if you choose to implement this protocol yourself, you need to create a UITableViewCell
object and return it for whatever row. Have a look at its class reference to understand re-usablity because the cells that are displayed in the table view are reused again and again(this is a very efficient design btw).
As for when you have two table views, look at the method. The table view is passed to it, so you should not have a problem with respect to that.
After searching and giving hit and trial session I am able to solove it by first specifying url like
$window.location.href = '/#/home/stats';
then reload
$window.location.reload();
Check example link below and click on the div to get the color value in hex.
var color = '';_x000D_
$('div').click(function() {_x000D_
var x = $(this).css('backgroundColor');_x000D_
hexc(x);_x000D_
console.log(color);_x000D_
})_x000D_
_x000D_
function hexc(colorval) {_x000D_
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);_x000D_
delete(parts[0]);_x000D_
for (var i = 1; i <= 3; ++i) {_x000D_
parts[i] = parseInt(parts[i]).toString(16);_x000D_
if (parts[i].length == 1) parts[i] = '0' + parts[i];_x000D_
}_x000D_
color = '#' + parts.join('');_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class='div' style='background-color: #f5b405'>Click me!</div>
_x000D_
Check working example at http://jsfiddle.net/DCaQb/
For everyone that has Android problems in the string.xml, use \'\' instead of single quote.
I got an error in Eclipse Mars version as "Build path specifies execution environment J2SE-1.5. There are no JREs installed in the workspace that are strictly compatible with this environment.
To resolve this issue, please do the following steps, "Right click on Project Choose Build path Choose Configure Build path Choose Libraries tab Select JRE System Library and click on Edit button Choose workspace default JRE and Finish
Problem will be resolved.
For me, I was accessing my XLS
file from a network share. Moving the file for my connection manager to a local folder fixed the issue.
The code I use for all browser gradients:
background: #0A284B;
background: -webkit-gradient(linear, left top, left bottom, from(#0A284B), to(#135887));
background: -webkit-linear-gradient(#0A284B, #135887);
background: -moz-linear-gradient(top, #0A284B, #135887);
background: -ms-linear-gradient(#0A284B, #135887);
background: -o-linear-gradient(#0A284B, #135887);
background: linear-gradient(#0A284B, #135887);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0A284B', endColorstr='#135887');
zoom: 1;
You will need to specify a height or zoom: 1
to apply hasLayout
to the element for this to work in IE.
Update:
Here is a LESS Mixin (CSS) version for all you LESS users out there:
.gradient(@start, @end) {
background: mix(@start, @end, 50%);
filter: ~"progid:DXImageTransform.Microsoft.gradient(startColorStr="@start~", EndColorStr="@end~")";
background: -webkit-gradient(linear, left top, left bottom, from(@start), to(@end));
background: -webkit-linear-gradient(@start, @end);
background: -moz-linear-gradient(top, @start, @end);
background: -ms-linear-gradient(@start, @end);
background: -o-linear-gradient(@start, @end);
background: linear-gradient(@start, @end);
zoom: 1;
}
Not directly answering your question but something to remember:
When using includes with allow_url_include on in your ini beware that, when accessing sessions from included files, if from a script you include one file using an absolute file reference and then include a second file from on your local server using a url file reference that they have different variable scope and the same session will not be seen from both included files. The original session won't be seen from the url included file.
from: http://us2.php.net/manual/en/function.include.php#84052
The @SqlZim's answer is correct but just to explain why this possibly have happened. I've had similar issue and this was caused by very innocent thing: adding default value to a column
ALTER TABLE MySchema.MyTable ADD
MyColumn int DEFAULT NULL;
But in the realm of MS SQL Server a default value on a colum is a CONSTRAINT. And like every constraint it has an identifier. And you cannot drop a column if it is used in a CONSTRAINT.
So what you can actually do avoid this kind of problems is always give your default constraints a explicit name, for example:
ALTER TABLE MySchema.MyTable ADD
MyColumn int NULL,
CONSTRAINT DF_MyTable_MyColumn DEFAULT NULL FOR MyColumn;
You'll still have to drop the constraint before dropping the column, but you will at least know its name up front.
The stdout
stream is line buffered by default, so will only display what's in the buffer after it reaches a newline (or when it's told to). You have a few options to print immediately:
Print to stderr
instead using fprintf
(stderr
is unbuffered by default):
fprintf(stderr, "I will be printed immediately");
Flush stdout whenever you need it to using fflush
:
printf("Buffered, will be flushed");
fflush(stdout); // Will now print everything in the stdout buffer
Edit: From Andy Ross's comment below, you can also disable buffering on stdout by using setbuf
:
setbuf(stdout, NULL);
or its secure version setvbuf
as explained here
setvbuf(stdout, NULL, _IONBF, 0);
As I keep repeating these days: semantics first.
Adding noexcept
, noexcept(true)
and noexcept(false)
is first and foremost about semantics. It only incidentally condition a number of possible optimizations.
As a programmer reading code, the presence of noexcept
is akin to that of const
: it helps me better grok what may or may not happen. Therefore, it is worthwhile spending some time thinking about whether or not you know if the function will throw. For a reminder, any kind of dynamic memory allocation may throw.
Okay, now on to the possible optimizations.
The most obvious optimizations are actually performed in the libraries. C++11 provides a number of traits that allows knowing whether a function is noexcept
or not, and the Standard Library implementation themselves will use those traits to favor noexcept
operations on the user-defined objects they manipulate, if possible. Such as move semantics.
The compiler may only shave a bit of fat (perhaps) from the exception handling data, because it has to take into account the fact that you may have lied. If a function marked noexcept
does throw, then std::terminate
is called.
These semantics were chosen for two reasons:
noexcept
even when dependencies do not use it already (backward compatibility)noexcept
when calling functions that may theoretically throw, but are not expected to for the given argumentsTry this :-
try{
String valuee="25/04/2013";
Date currentDate =new SimpleDateFormat("dd/MM/yyyy").parse(valuee);
System.out.println("Date is ::"+currentDate);
}catch(Exception e){
System.out.println("Error::"+e);
e.printStackTrace();
}
Output:-
Date is ::Thu Apr 25 00:00:00 GMT+05:30 2013
Your value should be proper format.
In your question also you have asked for this below :-
Date currentDate = new Date(value);
This style of date constructor is already deprecated.So, its no more use.Being we know that Date has 6 constructor.Read more
Consider the below definition in web.xml
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>TestServlet</servlet-class>
<init-param>
<param-name>myprop</param-name>
<param-value>value</param-value>
</init-param>
</servlet>
You can see that init-param is defined inside a servlet element. This means it is only available to the servlet under declaration and not to other parts of the web application. If you want this parameter to be available to other parts of the application say a JSP this needs to be explicitly passed to the JSP. For instance passed as request.setAttribute(). This is highly inefficient and difficult to code.
So if you want to get access to global values from anywhere within the application without explicitly passing those values, you need to use Context Init parameters.
Consider the following definition in web.xml
<web-app>
<context-param>
<param-name>myprop</param-name>
<param-value>value</param-value>
</context-param>
</web-app>
This context param is available to all parts of the web application and it can be retrieved from the Context object. For instance, getServletContext().getInitParameter(“dbname”);
From a JSP you can access the context parameter using the application implicit object. For example, application.getAttribute(“dbname”);
Javax used to be only for extensions. Yet later sun added it to the java libary forgetting to remove the x. Developers started making code with javax. Yet later on in time suns decided to change it to java. Developers didn't like the idea because they're code would be ruined... so javax was kept.