For issue related to code igniter project upload,
go to the base directory index.php and add this code:
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
if (defined('ENVIRONMENT')){
switch (ENVIRONMENT){
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
begin()
returns the first pair, (precisely, an iterator to the first pair, and you can access the key/value as ->first
and ->second
of that iterator)
Well, I tried to measure it up with the code below:
For runs = 1 and iterations = 1 the URL method is fastest most times followed by channel. I run this with some pause fresh about 10 times. So for one time access, using the URL is the fastest way I can think of:
LENGTH sum: 10626, per Iteration: 10626.0
CHANNEL sum: 5535, per Iteration: 5535.0
URL sum: 660, per Iteration: 660.0
For runs = 5 and iterations = 50 the picture draws different.
LENGTH sum: 39496, per Iteration: 157.984
CHANNEL sum: 74261, per Iteration: 297.044
URL sum: 95534, per Iteration: 382.136
File must be caching the calls to the filesystem, while channels and URL have some overhead.
Code:
import java.io.*;
import java.net.*;
import java.util.*;
public enum FileSizeBench {
LENGTH {
@Override
public long getResult() throws Exception {
File me = new File(FileSizeBench.class.getResource(
"FileSizeBench.class").getFile());
return me.length();
}
},
CHANNEL {
@Override
public long getResult() throws Exception {
FileInputStream fis = null;
try {
File me = new File(FileSizeBench.class.getResource(
"FileSizeBench.class").getFile());
fis = new FileInputStream(me);
return fis.getChannel().size();
} finally {
fis.close();
}
}
},
URL {
@Override
public long getResult() throws Exception {
InputStream stream = null;
try {
URL url = FileSizeBench.class
.getResource("FileSizeBench.class");
stream = url.openStream();
return stream.available();
} finally {
stream.close();
}
}
};
public abstract long getResult() throws Exception;
public static void main(String[] args) throws Exception {
int runs = 5;
int iterations = 50;
EnumMap<FileSizeBench, Long> durations = new EnumMap<FileSizeBench, Long>(FileSizeBench.class);
for (int i = 0; i < runs; i++) {
for (FileSizeBench test : values()) {
if (!durations.containsKey(test)) {
durations.put(test, 0l);
}
long duration = testNow(test, iterations);
durations.put(test, durations.get(test) + duration);
// System.out.println(test + " took: " + duration + ", per iteration: " + ((double)duration / (double)iterations));
}
}
for (Map.Entry<FileSizeBench, Long> entry : durations.entrySet()) {
System.out.println();
System.out.println(entry.getKey() + " sum: " + entry.getValue() + ", per Iteration: " + ((double)entry.getValue() / (double)(runs * iterations)));
}
}
private static long testNow(FileSizeBench test, int iterations)
throws Exception {
long result = -1;
long before = System.nanoTime();
for (int i = 0; i < iterations; i++) {
if (result == -1) {
result = test.getResult();
//System.out.println(result);
} else if ((result = test.getResult()) != result) {
throw new Exception("variance detected!");
}
}
return (System.nanoTime() - before) / 1000;
}
}
If you need to use https, then use the https library
https = require('https');
// options
var options = {
host: 'eternagame.wikia.com',
path: '/wiki/EteRNA_Dictionary'
}
// get
https.get(options, callback);
Insert an element at very beginning position. case-1 when the list is empty. case-2 When the list is not empty.
#include<iostream>
using namespace std;
struct Node{
int data;
Node* next; //link == head =stored the address of the next node
};
Node* head; //pointer to Head node with empty list
void Insert(int y);
void print();
int main(){
head = nullptr; //empty list
int n,y;
cout<<"how many number do you want to enter?"<<endl;
cin>>n;
for (int i=0;i<n;i++){
cout<<"Enter the number "<<i+1<<endl;
cin>>y;
Insert(y);
print();
}
}
void Insert(int y){
Node* temp = new Node(); //create dynamic memory allocation
temp->data = y;
temp->next = head; // temp->next = null; when list is empty
head = temp;
}
void print(){
Node* temp = head;
cout<<"List is: "<<endl;
while(temp!= nullptr){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
CSS properties should be set by cssText
property or setAttribute
method.
// Set multiple styles in a single statement
elt.style.cssText = "color: blue; border: 1px solid black";
// Or
elt.setAttribute("style", "color:red; border: 1px solid blue;");
Styles should not be set by assigning a string directly to the style
property (as in elt.style = "color: blue;"
), since it is considered read-only, as the style
attribute returns a CSSStyleDeclaration
object which is also read-only.
There's another post here. Try looking at this.
BTW, you're looking for the .lower()
method:
string1 = "hi"
string2 = "HI"
if string1.lower() == string2.lower():
print "Equals!"
else:
print "Different!"
try $conn = mysql_connect("localhost", "root")
or $conn = mysql_connect("localhost", "root", "")
@Anthony answer works for devices that support ActionBar
and for those devices which support only Sherlock Action Bar
following method must be used
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
if(actionBarHeight ==0 && getTheme().resolveAttribute(com.actionbarsherlock.R.attr.actionBarSize, tv, true)){
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
//OR as stated by @Marina.Eariel
TypedValue tv = new TypedValue();
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}else if(getTheme().resolveAttribute(com.actionbarsherlock.R.attr.actionBarSize, tv, true){
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.
DECLARE @Parmdef nvarchar (500)
DECLARE @SQL nvarchar (max)
DECLARE @xTxt1 nvarchar (100) = 'test1'
DECLARE @xTxt2 nvarchar (500) = 'test2'
SET @parmdef = '@text1 nvarchar (100), @text2 nvarchar (500)'
SET @SQL = 'PRINT @text1 + '' '' + @text2'
EXEC sp_executeSQL @SQL, @Parmdef, @xTxt1, @xTxt2
PyMySQL gives MySQLDb like interface as well. You could try in your initialization:
import pymysql
pymysql.install_as_MySQLdb()
Also there is a port of mysql-python on github for python3.
You can use the util library that comes with nodejs to get a promise from the exec command and can use that output as you need. Use restructuring to store the stdout and stderr in variables.
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function lsExample() {
const {
stdout,
stderr
} = await exec('ls');
console.log('stdout:', stdout);
console.error('stderr:', stderr);
}
lsExample();
_x000D_
Seems like it is not possible out of the box. Looks like someone attempted a solution
See this forum post http://code.google.com/p/moq/issues/detail?id=176
this question Verify value of reference parameter with Moq
As of 13 April 2020 there is no such functionality unless you are able to use different scopes, but you may use the postinstall script as a workaround. It is always executed, well, after each npm install:
Say you have your .npmrc configured to install @foo-org/foo-pack-private from your private github repo, but the @foo-org/foo-pack-public public package is on npm (under the same scope: foo-org).
Your postinstall might look like this:
"scripts": {
...
"postinstall": "mv .npmrc .npmrcc && npm i @foo-org/foo-pack --dry-run && mv .npmrcc .npmrc".
}
Don't forget to remove @foo-pack/foo-org from the dependencies array to make sure npm install does not try and get it from github and to add the --dry-run flag that makes sure package.json and package-lock.json stay unchanged after npm install.
It seems that docker-compose has native support now for default environment variables in file.
all you need to do is declare your variables in a file named .env
and they will be available in docker-compose.yml.
For example, for .env
file with contents:
MY_SECRET_KEY=SOME_SECRET
IMAGE_NAME=docker_image
You could access your variable inside docker-compose.yml
or forward them into the container:
my-service:
image: ${IMAGE_NAME}
environment:
MY_SECRET_KEY: ${MY_SECRET_KEY}
Late answer, and there are many good answers already.
In case you want a simple script to check if the maximum file watches is big enough, and if not, increase the limit, here it is:
#!/usr/bin/env bash
let current_watches=`sysctl -n fs.inotify.max_user_watches`
if (( current_watches < 80000 ))
then
echo "Current max_user_watches ${current_watches} is less than 80000."
else
echo "Current max_user_watches ${current_watches} is already equal to or greater than 80000."
exit 0
fi
if sudo sysctl -w fs.inotify.max_user_watches=80000 && sudo sysctl -p && echo fs.inotify.max_user_watches=80000 | sudo tee /etc/sysctl.d/10-user-watches.conf
then
echo "max_user_watches changed to 80000."
else
echo "Could not change max_user_watches."
exit 1
fi
The script increases the limit to 80000
, but feel free to set a limit that you want.
Since version 3.3 of ggplot2, we have access to the convenient after_stat()
function.
We can do something similar to @Andrew's answer, but without using the ..
syntax:
# original example data
mydata <- c("aa", "bb", NULL, "bb", "cc", "aa", "aa", "aa", "ee", NULL, "cc")
# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
y = after_stat(count/sum(count)))) +
geom_bar() +
scale_y_continuous(labels = scales::percent)
You can find all the "computed variables" available to use in the documentation of the geom_
and stat_
functions. For example, for geom_bar()
, you can access the count
and prop
variables. (See the documentation for computed variables.)
One comment about your NULL
values: they are ignored when you create the vector (i.e. you end up with a vector of length 9, not 11). If you really want to keep track of missing data, you will have to use NA
instead (ggplot2 will put NAs at the right end of the plot):
# use NA instead of NULL
mydata <- c("aa", "bb", NA, "bb", "cc", "aa", "aa", "aa", "ee", NA, "cc")
length(mydata)
#> [1] 11
# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
y = after_stat(count/sum(count)))) +
geom_bar() +
scale_y_continuous(labels = scales::percent)
Created on 2021-02-09 by the reprex package (v1.0.0)
(Note that using chr
or fct
data will not make a difference for your example.)
If you have it, the lam (laminate) utility can do it, for example:
$ lam filename -s "string after each line"
I create the database myself using the command line. Then try to import again, it works.
Since this is a readability issue, I have used the following code:
MySql = ""
MySql = MySql & "SELECT myTable.id"
MySql = MySql & " FROM myTable"
MySql = MySql & " WHERE myTable.id_equipment = " & lblId.Text
Using the :before
pseudo-element,
CSS3's border-radius
,
and some transparency is quite easy:
<div class="circle"></div>
CSS:
.circle, .circle:before{
position:absolute;
border-radius:150px;
}
.circle{
width:200px;
height:200px;
z-index:0;
margin:11%;
padding:40px;
background: hsla(0, 100%, 100%, 0.6);
}
.circle:before{
content:'';
display:block;
z-index:-1;
width:200px;
height:200px;
padding:44px;
border: 6px solid hsla(0, 100%, 100%, 0.6);
/* 4px more padding + 6px border = 10 so... */
top:-10px;
left:-10px;
}
The :before
attaches to our .circle
another element which you only need to make (ok, block, absolute, etc...) transparent and play with the border opacity.
Most answers are pertaining to doing it on code. But I'll give you one that works on Storyboard. Yes! You read it right.
Click on main UINavigationController
and navigate to it's Identity Inspector
tab.
Under User Defined Runtime Attributes
, set a single runtime property called interactivePopGestureRecognizer.enabled
to true
. Or graphically, you'd have to enable the checkbox as shown in the image below.
That's it. You're good to go. Your back gesture will work as if it was there all along.
We had the same issue with our sites. We were able to fix this all inside of Visual Studio. We are using 2012 Ultimate.
The underlying issue we saw was that with SSL enabled, for some reason, VS was assigning the same port for the standard and secure URLs. This issue seemed to arise when we were pulling the code down from TFS.
To remedy it, we undertook the following steps:
Make sure that the check box for Override application root URL is unchecked.
As of SQL Server 2012+, you can use FORMAT(value, format [, culture ])
Where the format
param takes any valid standard format string or custom formatting string
Example:
SELECT FORMAT(GETDATE(), 'MM/dd/yyyy')
Further Reading:
A small addition to the solutions before:
object_id(@TableName)
works only if you are in the default schema.
(Select id from sysobjects where name = @TableName)
works in any schema provided @tableName is unique.
this method compares two Integer with null check, see tests
public static boolean compare(Integer int1, Integer int2) {
if(int1!=null) {
return int1.equals(int2);
} else {
return int2==null;
}
//inline version:
//return (int1!=null) ? int1.equals(int2) : int2==null;
}
//results:
System.out.println(compare(1,1)); //true
System.out.println(compare(0,1)); //false
System.out.println(compare(1,0)); //false
System.out.println(compare(null,0)); //false
System.out.println(compare(0,null)); //false
System.out.println(compare(null,null)); //true
Simply put, don't use DateTime.MinVaue
as a default value.
There are a couple of different MinValues
out there, depending which environment you are in.
I once had a project, where I was implementing a Windows CE project, I was using the Framework's DateTime.MinValue
(year 0001), the database MinValue
(1753) and a UI control DateTimePicker
(i think it was 1970). So there were at least 3 different MinValues that were leading to strange behavior and unexpected results. (And I believe that there was even a fourth (!) version, I just do not recall where it came from.).
Use a nullable database field and change your value into a Nullable<DateTime>
instead. Where there is no valid value in your code, there should not be a value in the database as well. :-)
You could use an image submit button:
<input type="image" id="saveform" src="logg.png " alt="Submit Form" />
It depends on your definition of "inherit". Does the subclass still have the fields in memory? Definitely. Can it access them directly? No. It's just subtleties of the definition; the point is to understand what's really happening.
How about a shorthand notation?
{overflow: auto hidden;}
In order to resolve
Gem::Ext::BuildError: ERROR: Failed to build gem native extension error for mysql2,
I think libmysql-ruby got changed with ruby-mysql
Simply try with following commands,
sudo apt-get install ruby-mysql
& then
sudo apt-get install libmysqlclient-dev
One thing to keep in mind:
Changing the system time affects time.time()
but not time.clock()
.
I needed to control some automatic tests executions. If one step of the test case took more than a given amount of time, that TC was aborted to go on with the next one.
But sometimes a step needed to change the system time (to check the scheduler module of the application under test), so after setting the system time a few hours in the future, the TC timeout expired and the test case was aborted. I had to switch from time.time()
to time.clock()
to handle this properly.
here is code:
<?php echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>'; ?>
The simplest way especially if you don't have a context, if you're using RxAndroid you can do:
AndroidSchedulers.mainThread().scheduleDirect {
runCodeHere()
}
This is taken from the MVC sample project
@if (ViewBag.ShowRemoveButton)
{
using (Html.BeginForm("RemoveLogin", "Manage"))
{
@Html.AntiForgeryToken()
<div>
@Html.Hidden("company_name", account)
@Html.Hidden("returnUrl", Model.returnUrl)
<input type="submit" class="btn btn-default" value="Remove" title="Remove your email address from @account" />
</div>
}
}
A slight modification to Manish M Demblani's contribution above handles 4am (I got rid of the seconds section as I don't need it in my application)
^(([0-1]{0,1}[0-9]( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[1-9]|1[0-2])(:|\.)[0-5][0-9]( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[0-9]|1[0-9]|2[0-3])(:|\.)[0-5][0-9]))$
handles: 4am 4 am 4:00 4:00am 4:00 pm 4.30 am etc..
You can use ObjectMapper.convertValue()
, either value by value or even for the whole list. But you need to know the type to convert to:
POJO pojo = mapper.convertValue(singleObject, POJO.class);
// or:
List<POJO> pojos = mapper.convertValue(listOfObjects, new TypeReference<List<POJO>>() { });
this is functionally same as if you did:
byte[] json = mapper.writeValueAsBytes(singleObject);
POJO pojo = mapper.readValue(json, POJO.class);
but avoids actual serialization of data as JSON, instead using an in-memory event sequence as the intermediate step.
If you want to call something like this NSString.newLine;
from objective c, and you want it to be static constant, you can create something like this in swift:
public extension NSString {
@objc public static let newLine = "\n"
}
And you have nice readable constant definition, and available from within a type of your choice while stile bounded to context of type.
You can use the following attributes for webkit, which reach into the shadow DOM:
::-webkit-scrollbar { /* 1 */ }
::-webkit-scrollbar-button { /* 2 */ }
::-webkit-scrollbar-track { /* 3 */ }
::-webkit-scrollbar-track-piece { /* 4 */ }
::-webkit-scrollbar-thumb { /* 5 */ }
::-webkit-scrollbar-corner { /* 6 */ }
::-webkit-resizer { /* 7 */ }
Here's a working fiddle with a red scrollbar, based on code from this page explaining the issues.
http://jsfiddle.net/hmartiro/Xck2A/1/
Using this and your solution, you can handle all browsers except Firefox, which at this point I think still requires a javascript solution.
minimumFontSize
is deprecated in iOS 6.
So use minimumScaleFactor
instead of minmimumFontSize
.
lbl.adjustsFontSizeToFitWidth = YES
lbl.minimumScaleFactor = 0.5
Swift 5
lbl.adjustsFontSizeToFitWidth = true
lbl.minimumScaleFactor = 0.5
Check if a given key already exists in a dictionary
To get the idea how to do that we first inspect what methods we can call on dictionary. Here are the methods:
d={'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}
Python Dictionary clear() Removes all Items
Python Dictionary copy() Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys() Creates dictionary from given sequence
Python Dictionary get() Returns Value of The Key
Python Dictionary items() Returns view of dictionary (key, value) pair
Python Dictionary keys() Returns View Object of All Keys
Python Dictionary pop() Removes and returns element having given key
Python Dictionary popitem() Returns & Removes Element From Dictionary
Python Dictionary setdefault() Inserts Key With a Value if Key is not Present
Python Dictionary update() Updates the Dictionary
Python Dictionary values() Returns view of all values in dictionary
The brutal method to check if the key already exists may be the get()
method:
d.get("key")
The other two interesting methods items()
and keys()
sounds like too much of work. So let's examine if get()
is the right method for us. We have our dict d
:
d= {'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}
Printing shows the key we don't have will return None
:
print(d.get('key')) #None
print(d.get('clear')) #0
print(d.get('copy')) #1
We may use that to get the info if the key is present or no.
But consider this if we create a dict with a single key:None
:
d= {'key':None}
print(d.get('key')) #None
print(d.get('key2')) #None
Leading that get()
method is not reliable in case some values may be None
.
This story should have a happier ending. If we use the in
comparator:
print('key' in d) #True
print('key2' in d) #False
We get the correct results. We may examine the Python byte code:
import dis
dis.dis("'key' in d")
# 1 0 LOAD_CONST 0 ('key')
# 2 LOAD_NAME 0 (d)
# 4 COMPARE_OP 6 (in)
# 6 RETURN_VALUE
dis.dis("d.get('key2')")
# 1 0 LOAD_NAME 0 (d)
# 2 LOAD_METHOD 1 (get)
# 4 LOAD_CONST 0 ('key2')
# 6 CALL_METHOD 1
# 8 RETURN_VALUE
This shows that in
compare operator is not just more reliable but even faster than get()
.
I too had this problem when I was doing unit Testing. A very Simple Solution to this problem is to use @Transactional annotation which keeps the session open till the end of the execution.
Well you are trying to compare Date with Nvarchar which is wrong. Should be
Where dates between date1 And date2
-- both date1 & date2 should be date/datetime
If date1,date2 strings; server will convert them to date type before filtering.
If the data read from the stream is large, I would recommend using a TeeInputStream from Apache Commons IO. That way you can essentially replicate the input and pass a t'd pipe as your clone.
You have to correctly override method equals() from class Object
Edit: I think that my first response was misunderstood probably because I was not too precise. So I decided to to add more explanations.
Why do you have to override equals()? Well, because this is in the domain of a developer to decide what does it mean for two objects to be equal. Reference equality is not enough for most of the cases.
For example, imagine that you have a HashMap whose keys are of type Person. Each person has name and address. Now, you want to find detailed bean using the key. The problem is, that you usually are not able to create an instance with the same reference as the one in the map. What you do is to create another instance of class Person. Clearly, operator == will not work here and you have to use equals().
But now, we come to another problem. Let's imagine that your collection is very large and you want to execute a search. The naive implementation would compare your key object with every instance in a map using equals(). That, however, would be very expansive. And here comes the hashCode(). As others pointed out, hashcode is a single number that does not have to be unique. The important requirement is that whenever equals() gives true for two objects, hashCode() must return the same value for both of them. The inverse implication does not hold, which is a good thing, because hashcode separates our keys into kind of buckets. We have a small number of instances of class Person in a single bucket. When we execute a search, the algorithm can jump right away to a correct bucket and only now execute equals for each instance. The implementation for hashCode() therefore must distribute objects as evenly as possible across buckets.
There is one more point. Some collections require a proper implementation of a hashCode() method in classes that are used as keys not only for performance reasons. The examples are: HashSet and LinkedHashSet. If they don’t override hashCode(), the default Object hashCode() method will allow multiple objects that you might consider "meaningfully equal" to be added to your "no duplicates allowed" set.
Some of the collections that use hashCode()
Have a look at those two classes from apache commons that will allow you to implement equals() and hashCode() easily
how do you get
"\u6f22\u5b57"
from??
in JavaScript?
These are JavaScript Unicode escape sequences e.g. \u12AB
. To convert them, you could iterate over every code unit in the string, call .toString(16)
on it, and go from there.
However, it is more efficient to also use hexadecimal escape sequences e.g. \xAA
in the output wherever possible.
Also note that ASCII symbols such as A
, b
, and -
probably don’t need to be escaped.
I’ve written a small JavaScript library that does all this for you, called jsesc
. It has lots of options to control the output.
Here’s an online demo of the tool in action: http://mothereff.in/js-escapes#1%E6%BC%A2%E5%AD%97
Your question was tagged as utf-8
. Reading the rest of your question, UTF-8 encoding/decoding didn’t seem to be what you wanted here, but in case you ever need it: use utf8.js
(online demo).
Step 1) Remove the semi-colon, it's an object you're creating...
a(this).next().css({
left : c,
transition : 'opacity 1s ease-in-out';
});
to
a(this).next().css({
left : c,
transition : 'opacity 1s ease-in-out'
});
Step 2) Vendor-prefixes... no browsers use transition
since it's the standard and this is an experimental feature even in the latest browsers:
a(this).next().css({
left : c,
WebkitTransition : 'opacity 1s ease-in-out',
MozTransition : 'opacity 1s ease-in-out',
MsTransition : 'opacity 1s ease-in-out',
OTransition : 'opacity 1s ease-in-out',
transition : 'opacity 1s ease-in-out'
});
Here is a demo: http://jsfiddle.net/83FsJ/
Step 3) Better vendor-prefixes... Instead of adding tons of unnecessary CSS to elements (that will just be ignored by the browser) you can use jQuery to decide what vendor-prefix to use:
$('a').on('click', function () {
var myTransition = ($.browser.webkit) ? '-webkit-transition' :
($.browser.mozilla) ? '-moz-transition' :
($.browser.msie) ? '-ms-transition' :
($.browser.opera) ? '-o-transition' : 'transition',
myCSSObj = { opacity : 1 };
myCSSObj[myTransition] = 'opacity 1s ease-in-out';
$(this).next().css(myCSSObj);
});?
Here is a demo: http://jsfiddle.net/83FsJ/1/
Also note that if you specify in your transition
declaration that the property to animate is opacity
, setting a left
property won't be animated.
->> works for me.
postgres version:
<postgres.version>11.6</postgres.version>
Query:
select object_details->'valuationDate' as asofJson, object_details->>'valuationDate' as asofText from MyJsonbTable;
Output:
asofJson asofText
"2020-06-26" 2020-06-26
"2020-06-25" 2020-06-25
"2020-06-25" 2020-06-25
"2020-06-25" 2020-06-25
Probably for the same reason that there is no tree container in boost. There are many ways to implement such a container, and there is no good way to satisfy everyone who would use it.
Some issues to consider:
In the end, the problem ends up being that a tree container that would be useful enough to everyone, would be too heavyweight to satisfy most of the people using it. If you are looking for something powerful, Boost Graph Library is essentially a superset of what a tree library could be used for.
Here are some other generic tree implementations:
The dependency versions that I needed to use when compiling for Java 8 target. Tested application in Java 8, 11, and 12 JREs.
<!-- replace dependencies that have been removed from JRE's starting with Java v11 -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.8</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.8-b01</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.8-b01</version>
</dependency>
<!-- end replace dependencies that have been removed from JRE's starting with Java v11 -->
Solution
id
is unsigned integer, auto_incrementid
columnBam, immediate 10x+ insert improvement.
I would like to extend nice answer of Jerome Dalbert. I found very easy to write your own annotation validators in JSR-303 way. You are not limited to have "one field" validation. You can create your own annotation on type level and have complex validation (see examples below). I prefer this way because I don't need mix different types of validation (Spring and JSR-303) like Jerome do. Also this validators are "Spring aware" so you can use @Inject/@Autowire out of box.
Example of custom object validation:
@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { YourCustomObjectValidator.class })
public @interface YourCustomObjectValid {
String message() default "{YourCustomObjectValid.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class YourCustomObjectValidator implements ConstraintValidator<YourCustomObjectValid, YourCustomObject> {
@Override
public void initialize(YourCustomObjectValid constraintAnnotation) { }
@Override
public boolean isValid(YourCustomObject value, ConstraintValidatorContext context) {
// Validate your complex logic
// Mark field with error
ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
cvb.addNode(someField).addConstraintViolation();
return true;
}
}
@YourCustomObjectValid
public YourCustomObject {
}
Example of generic fields equality:
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { FieldsEqualityValidator.class })
public @interface FieldsEquality {
String message() default "{FieldsEquality.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* Name of the first field that will be compared.
*
* @return name
*/
String firstFieldName();
/**
* Name of the second field that will be compared.
*
* @return name
*/
String secondFieldName();
@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface List {
FieldsEquality[] value();
}
}
import java.lang.reflect.Field;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
public class FieldsEqualityValidator implements ConstraintValidator<FieldsEquality, Object> {
private static final Logger log = LoggerFactory.getLogger(FieldsEqualityValidator.class);
private String firstFieldName;
private String secondFieldName;
@Override
public void initialize(FieldsEquality constraintAnnotation) {
firstFieldName = constraintAnnotation.firstFieldName();
secondFieldName = constraintAnnotation.secondFieldName();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value == null)
return true;
try {
Class<?> clazz = value.getClass();
Field firstField = ReflectionUtils.findField(clazz, firstFieldName);
firstField.setAccessible(true);
Object first = firstField.get(value);
Field secondField = ReflectionUtils.findField(clazz, secondFieldName);
secondField.setAccessible(true);
Object second = secondField.get(value);
if (first != null && second != null && !first.equals(second)) {
ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
cvb.addNode(firstFieldName).addConstraintViolation();
ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
cvb.addNode(someField).addConstraintViolation(secondFieldName);
return false;
}
} catch (Exception e) {
log.error("Cannot validate fileds equality in '" + value + "'!", e);
return false;
}
return true;
}
}
@FieldsEquality(firstFieldName = "password", secondFieldName = "confirmPassword")
public class NewUserForm {
private String password;
private String confirmPassword;
}
Update react v16.8 (16 Feb 2019 realease)
Since react 16.8 released with hooks, function components are now have the ability to hold persistent state
. With that ability you can now mimic a forceUpdate
:
function App() {_x000D_
const [, updateState] = React.useState();_x000D_
const forceUpdate = React.useCallback(() => updateState({}), []);_x000D_
console.log("render");_x000D_
return (_x000D_
<div>_x000D_
<button onClick={forceUpdate}>Force Render</button>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
_x000D_
const rootElement = document.getElementById("root");_x000D_
ReactDOM.render(<App />, rootElement);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>_x000D_
<div id="root"/>
_x000D_
Note that this approach should be re-considered and in most cases when you need to force an update you probably doing something wrong.
Before react 16.8.0
No you can't, State-Less function components are just normal functions
that returns jsx
, you don't have any access to the React life cycle methods as you are not extending from the React.Component
.
Think of function-component as the render
method part of the class components.
As of v 0.7.0 of the private registry you can do:
$ curl -X GET http://localhost:5000/v1/search?q=postgresql
and you will get a json payload:
{"num_results": 1, "query": "postgresql", "results": [{"description": "", "name": "library/postgresql"}]}
to give more background here is how I started my registry:
docker run \
-e SETTINGS_FLAVOR=local \
-e STORAGE_PATH=/registry \
-e SEARCH_BACKEND=sqlalchemy \
-e LOGLEVEL=DEBUG \
-p 5000:5000 \
registry
yourView.setLayoutParams(new LinearLayout.LayoutParams(width, height));
The to_yaml
method seems to be useful sometimes:
$foo = {:name => "Clem", :age => 43}
puts $foo.to_yaml
returns
---
:age: 43
:name: Clem
(Does this depend on some YAML
module being loaded? Or would that typically be available?)
Since the originating port 4200 is different than 8080,So before angular sends a create (PUT) request,it will send an OPTIONS request to the server to check what all methods and what all access-controls are in place. Server has to respond to that OPTIONS request with list of allowed methods and allowed origins.
Since you are using spring boot, the simple solution is to add ".allowedOrigins("http://localhost:4200");"
In your spring config,class
@Configuration
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:4200");
}
}
However a better approach will be to write a Filter(interceptor) which adds the necessary headers to each response.
The definition of "scripting language" is pretty fuzzy. I'd base it on the following considerations:
Scripting languages don't usually have user-visible compile steps. Typically the user can just run programs in one easy command.
Programs in scripting languages are normally passed around in source form.
Scripting languages normally have runtimes that are present on a large number of systems, and the runtimes can be installed easily on most systems.
Scripting languages tend to be cross-platform and not machine-specific.
Scripting languages make it easy to call other programs and interface with the operating system.
Scripting languages are usually easily embeddable into larger systems written in more conventional programming languages.
Scripting languages are normally designed for ease of programming, and with much less regard for execution speed. (If you want fast execution, the usual advice is to code the time-consuming parts in something like C, and either embed the language into C or call C bits from the language.)
Some of the characteristics I listed above are true of implementations, in which case I'm referring to the more common implementations. There have been C interpreters, with (AFAIK) no obvious compile step, but that's not true of most C implementations. You could certainly compile a Perl program to native code, but that's not how it's normally used. Some other characteristics are social in nature. Some of the above criteria overlap somewhat. As I said, the definition is fuzzy.
Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile
type qualifier.
// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];
The volatile
type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile
is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.
This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma
or __attribute__
syntax.
**What's the best way to avoid a fixed size, i.e., to have the embedded website scale responsively to the browser's window size? I'd like to avoid scroll bars within my website. – CGFoX Feb 2 '19 at 15:52
**Is it possible to set width and height to percentages instead of absolute pixels? – CGFoX Mar 16 at 11:53
ANSWER: <embed src="https://YOURDOMAIN.com/PAGE.HTM" style="width:100%; height: 50vw;">
For me this setting was working.
In my windows 8.1 the path for php7 is
C:\user\test\tools\php7\php.exe
settings.json
{
"php.executablePath":"/user/test/tools/php7/php.exe",
"php.validate.executablePath": "/user/test/tools/php7/php.exe"
}
Often there are questions about the java settings in vsCode
. This is a big question and can involve advanced user knowledge to accmplish. But there is simple way to get the existing java settings from vsCode
and copy these setting for use on another PC. This post is using recent versions of vsCode and JDK in mid-December 2020.
There are several screen shots (below) that accompany this post which should provide enough information for the visual learners.
First things first, open vsCode
and either open an existing java folder-file or create a new java file in vsCode
. Then look at the lower right corner of vsCode
(on the blue command bar). The vsCode
should be displaying an icon showing the version of the Java Standard Edition
( Java SE ) being used. The version being on this PC today is JavaSE-15. (link 1)
Click on that icon (JAVASE-15
) which then opens a new window named "java.configuration.runtimes
". There should be two tabs below this name: User
and Workspace
. Below these tabs is a link named, "Edit in settings.json
". Click on that link. (link 2)
Two json
files should then open: Default settings
and settings.json
. This post only focuses on the "settings.json
" file. The settings.json
file shows various settings used for coding different programming languages (Python, R, and java). Near the bottom of the settings.json
file shows the settings this User uses in vsCode
for programming java.
These java settings are the settings that can be "backed up" - meaning these settings get copied and pasted to another PC for creating a java programming environment similar to the java programming environment on this PC. (link 3)
In my case, detach
and attach
worked:
getSupportFragmentManager()
.beginTransaction()
.detach(contentFragment)
.attach(contentFragment)
.commit();
For some strange reason, you can use the += operator to add shorts.
short answer = 0;
short firstNo = 1;
short secondNo = 2;
answer += firstNo;
answer += secondNo;
Try from your dedicated server to telnet to smtp.gmail.com on port 465. It might be blocked by your internet provider
In Win 7, navigate to the directory where your text files are. On the command prompt use:
copy *.txt combined.txt
Where combined.txt
is the name of the newly created text file.
For SQL Server 2008, the best and index friendly way is
DELETE from Table WHERE Date > CAST(GETDATE() as DATE);
For prior SQL Server versions, date maths will work faster than a convert to varchar. Even converting to varchar can give you the wrong result, because of regional settings.
DELETE from Table WHERE Date > DATEDIFF(d, 0, GETDATE());
Note: it is unnecessary to wrap the DATEDIFF
with another DATEADD
Almost every to-ISO method on the web drops the timezone information by applying a convert to "Z"ulu time (UTC) before outputting the string. Browser's native .toISOString() also drops timezone information.
This discards valuable information, as the server, or recipient, can always convert a full ISO date to Zulu time or whichever timezone it requires, while still getting the timezone information of the sender.
The best solution I've come across is to use the Moment.js javascript library and use the following code:
To get the current ISO time with timezone information and milliseconds
now = moment().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
// "2013-03-08T20:11:11.234+0100"
now = moment().utc().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
// "2013-03-08T19:11:11.234+0000"
now = moment().utc().format("YYYY-MM-DDTHH:mm:ss") + "Z"
// "2013-03-08T19:11:11Z" <- better use the native .toISOString()
To get the ISO time of a native JavaScript Date object with timezone information but without milliseconds
var current_time = Date.now();
moment(current_time).format("YYYY-MM-DDTHH:mm:ssZZ")
This can be combined with Date.js to get functions like Date.today() whose result can then be passed to moment.
A date string formatted like this is JSON compilant, and lends itself well to get stored into a database. Python and C# seem to like it.
I just had this issue after installing and removing some npm packages and spent almost 5 hours to figure out what was going on.
What I did is basically copied my src/components in a different directory, then removed all the node modules and package-lock.json (if you are running your app in the Docker container, remove images and rebuild it just to be safe); then reset it to my last commit and then put back my src/components then ran npm i
.
I hope it helps.
Python 3 ints do not have a maximum.
If your purpose is to determine the maximum size of an int in C when compiled the same way Python was, you can use the struct module to find out:
>>> import struct
>>> platform_c_maxint = 2 ** (struct.Struct('i').size * 8 - 1) - 1
If you are curious about the internal implementation details of Python 3 int objects, Look at sys.int_info
for bits per digit and digit size details. No normal program should care about these.
<div ng-hide="myvar == null"></div>
or
<div ng-show="myvar != null"></div>
I had the same issue when I changed the home directory of one use. In my case it was because of selinux
. I used the below to fix the issue:
selinuxenabled 0
setenforce 0
Write a microcontroller OS. I recommend an x86 based microcontroller. A modern OS is just huge. Learn the basics first.
To close your current window using JS, do this. First open the current window to trick your current tab into thinking it has been opened by a script. Then close it using window.close(). The below script should go into the parent window, not the child window. You could run this after running the script to open the child.
<script type="text/javascript">
window.open('','_parent','');
window.close();
</script>
class Program
{
static void Main()
{
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("White on blue.");
Console.WriteLine("Another line.");
Console.ResetColor();
}
}
Taken from here.
Why would you use reduce()
for this when Python has a perfectly cromulent sum()
function?
print sum(l) / float(len(l))
(The float()
is necessary to force Python to do a floating-point division.)
An analytic solution with only one nested query:
SELECT * FROM
(
SELECT t.*, Row_Number() OVER (ORDER BY name) MyRow FROM sometable t
)
WHERE MyRow BETWEEN 10 AND 20;
Rank()
could be substituted for Row_Number()
but might return more records than you are expecting if there are duplicate values for name.
With Apache Commons Lang3 lib is it very easy.
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
public String getName(String text) {
return StringUtils.remove(WordUtils.capitalizeFully(text, '_'), "_");
}
Example:
getName("SOME_CONSTANT");
Gives:
"SomeConstant"
I think this works:
int roundUp(int numToRound, int multiple) {
return multiple? !(numToRound%multiple)? numToRound : ((numToRound/multiple)+1)*multiple: numToRound;
}
$(document).ready(function() {
$('select#select_2').change(function() {
var selectedText = $(this).find('option:selected').text();
alert(selectedText);
});
});
There is a straight forward clean solution available. Use the wholeTextFiles() method. This will take a directory and forms a key value pair. The returned RDD will be a pair RDD. Find below the description from Spark docs:
SparkContext.wholeTextFiles lets you read a directory containing multiple small text files, and returns each of them as (filename, content) pairs. This is in contrast with textFile, which would return one record per line in each file
we can do it in more easy way like by adding a function on button and on click we call that function for append.
<div id="Content">
<button id="Add" onclick="append();">Add Text</button>
</div>
<script type="text/javascript">
function append()
{
$('<p>Text</p>').appendTo('#Content');
}
</script>
Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.
You only need to make sure that the button inputs have type="submit"
as in <input type="submit">
and <button type="submit">
and not type="button"
, which only renders a "dead" button purely for onclick
stuff and all.
E.g.
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<input type="submit" name="button1" value="Button 1" />
<input type="submit" name="button2" value="Button 2" />
<input type="submit" name="button3" value="Button 3" />
</form>
with
@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MyClass myClass = new MyClass();
if (request.getParameter("button1") != null) {
myClass.method1();
} else if (request.getParameter("button2") != null) {
myClass.method2();
} else if (request.getParameter("button3") != null) {
myClass.method3();
} else {
// ???
}
request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
}
}
Alternatively, use <button type="submit">
instead of <input type="submit">
, then you can give them all the same name, but an unique value. The value of the <button>
won't be used as label, you can just specify that yourself as child.
E.g.
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<button type="submit" name="button" value="button1">Button 1</button>
<button type="submit" name="button" value="button2">Button 2</button>
<button type="submit" name="button" value="button3">Button 3</button>
</form>
with
@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MyClass myClass = new MyClass();
String button = request.getParameter("button");
if ("button1".equals(button)) {
myClass.method1();
} else if ("button2".equals(button)) {
myClass.method2();
} else if ("button3".equals(button)) {
myClass.method3();
} else {
// ???
}
request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
}
}
The greatest value of an integer has little to do with the maximum number of rows you can store in a table.
It's true that if you use an int or bigint as your primary key, you can only have as many rows as the number of unique values in the data type of your primary key, but you don't have to make your primary key an integer, you could make it a CHAR(100). You could also declare the primary key over more than one column.
There are other constraints on table size besides number of rows. For instance you could use an operating system that has a file size limitation. Or you could have a 300GB hard drive that can store only 300 million rows if each row is 1KB in size.
The limits of database size is really high:
http://dev.mysql.com/doc/refman/5.1/en/source-configuration-options.html
The MyISAM storage engine supports 232 rows per table, but you can build MySQL with the --with-big-tables
option to make it support up to 264 rows per table.
http://dev.mysql.com/doc/refman/5.1/en/innodb-restrictions.html
The InnoDB storage engine has an internal 6-byte row ID per table, so there are a maximum number of rows equal to 248 or 281,474,976,710,656.
An InnoDB tablespace also has a limit on table size of 64 terabytes. How many rows fits into this depends on the size of each row.
The 64TB limit assumes the default page size of 16KB. You can increase the page size, and therefore increase the tablespace up to 256TB. But I think you'd find other performance factors make this inadvisable long before you grow a table to that size.
Since you want to append elements to existing list, you can use var List[Int] and then keep on adding elements to the same list. Note -> You have to make sure that you insert an element into existing list as follows:-
var l: List[int] = List() // creates an empty list
l = 3 :: l // adds 3 to the head of the list
l = 4 :: l // makes int 4 as the head of the list
// Now when you will print l, you will see two elements in the list ( 4, 3)
As BalusC indicated, the actionListener
by default swallows exceptions, but in JSF 2.0 there is a little more to this. Namely, it doesn't just swallows and logs, but actually publishes the exception.
This happens through a call like this:
context.getApplication().publishEvent(context, ExceptionQueuedEvent.class,
new ExceptionQueuedEventContext(context, exception, source, phaseId)
);
The default listener for this event is the ExceptionHandler
which for Mojarra is set to com.sun.faces.context.ExceptionHandlerImpl
. This implementation will basically rethrow any exception, except when it concerns an AbortProcessingException, which is logged. ActionListeners wrap the exception that is thrown by the client code in such an AbortProcessingException which explains why these are always logged.
This ExceptionHandler
can be replaced however in faces-config.xml with a custom implementation:
<exception-handlerfactory>
com.foo.myExceptionHandler
</exception-handlerfactory>
Instead of listening globally, a single bean can also listen to these events. The following is a proof of concept of this:
@ManagedBean
@RequestScoped
public class MyBean {
public void actionMethod(ActionEvent event) {
FacesContext.getCurrentInstance().getApplication().subscribeToEvent(ExceptionQueuedEvent.class, new SystemEventListener() {
@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {
ExceptionQueuedEventContext content = (ExceptionQueuedEventContext)event.getSource();
throw new RuntimeException(content.getException());
}
@Override
public boolean isListenerForSource(Object source) {
return true;
}
});
throw new RuntimeException("test");
}
}
(note, this is not how one should normally code listeners, this is only for demonstration purposes!)
Calling this from a Facelet like this:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:body>
<h:form>
<h:commandButton value="test" actionListener="#{myBean.actionMethod}"/>
</h:form>
</h:body>
</html>
Will result in an error page being displayed.
Error: 10060 Adding a timeout parameter to request solved the issue for me.
import urllib
import urllib2
g = "http://www.google.com/"
read = urllib2.urlopen(g, timeout=20)
A similar error also occurred while I was making a GET request. Again, passing a timeout
parameter solved the 10060 Error.
response = requests.get(param_url, timeout=20)
here's for SQL server, Oracle, PostgreSQL
which support window functions.
SELECT ROW_NUMBER() OVER (ORDER BY first_name, last_name) Sequence_no,
first_name,
last_name
FROM tableName
When a client connects to an Oracle server, it first connnects to the Oracle listener service. It often redirects the client to another port. So the client has to open another connection on a different port, which is blocked by the firewall.
So you might in fact have encountered a firewall problem due to Oracle port redirection. It should be possible to diagnose it with a network monitor on the client machine or with the firewall management software on the firewall.
Take a look at http://git-scm.com/book/en/Git-Internals-Transfer-Protocols for info on how to do this over some transport protocols. Note this won't work for standard git over SSH.
For git over SSH, an up-to-date server-side git should allow you to git-archive directly from the remote, which you could then e.g. pipe to "tar t" to get a list of all files in a given commit.
You, can also try like this, PictureBox1.Image = Image.FromFile("<your ImagePath>" or <Dialog box result>);
Use this its work fine for me to reload the same page:
<button onClick="window.location.reload();">
If you want to add the elements in a list (list2) to the end of other list (list), then you can use the list extend method
list = [1, 2, 3]
list2 = [4, 5, 6]
list.extend(list2)
print list
[1, 2, 3, 4, 5, 6]
Or if you want to concatenate two list then you can use + sign
list3 = list + list2
print list3
[1, 2, 3, 4, 5, 6]
The selector should not be #input
. That means a field with id="input"
which is not your case. You want:
$('#chag_sort').val(sort2);
Or if your hidden input didn't have an unique id but only a name="chag_sort"
:
$('input[name="chag_sort"]').val(sort2);
public static List<T> ListCompare<T>(List<T> List1 , List<T> List2 , string key )
{
return List1.Select(t => t.GetType().GetProperty(key).GetValue(t))
.Intersect(List2.Select(t => t.GetType().GetProperty(key).GetValue(t))).ToList();
}
Operators like <=
in Python are generally not overriden to mean something significantly different than "less than or equal to". It's unusual for the standard library does this--it smells like legacy API to me.
Use the equivalent and more clearly-named method, set.issubset
. Note that you don't need to convert the argument to a set; it'll do that for you if needed.
set(['a', 'b']).issubset(['a', 'b', 'c'])
View the fully working code on CodePen. Given the following HTML:
<div class="container">
<p>Several paragraphs of text...</p>
</div>
You can use CSS Grid to create three columns and tell the container to take a maximum width of 70 characters for the middle column which contains our paragraph.
.container
{
display: grid;
grid-template-columns: 1fr, 70ch 1fr;
}
p {
grid-column: 2 / 3;
}
This is what it looks like (Checkout CodePen for a fully working example):
Here is another example where you can use minmax to set a range of values. On small screens the width will be set to 50 characters wide and on large screens it will be 70 characters wide.
.container
{
display: grid;
grid-template-columns: 1fr minmax(50ch, 70ch) 1fr;
}
p {
grid-column: 2 / 3;
}
JDK: The complete package which you need to write and run java code
OpenJDK: An independent implementation of JDK for making it much better
JVM: Converts Java code into bytecode and provides the specifications which tells how should a Java code be compiled, loaded, verified, checked for errors and executed.
JRE: Implementation of the JVM with which some Java libraries are used to Run the program
By default, np.genfromtxt
uses dtype=float
: that's why you string columns are converted to NaNs because, after all, they're Not A Number...
You can ask np.genfromtxt
to try to guess the actual type of your columns by using dtype=None
:
>>> from StringIO import StringIO
>>> test = "a,1,2\nb,3,4"
>>> a = np.genfromtxt(StringIO(test), delimiter=",", dtype=None)
>>> print a
array([('a',1,2),('b',3,4)], dtype=[('f0', '|S1'),('f1', '<i8'),('f2', '<i8')])
You can access the columns by using their name, like a['f0']
...
Using dtype=None
is a good trick if you don't know what your columns should be. If you already know what type they should have, you can give an explicit dtype
. For example, in our test, we know that the first column is a string, the second an int, and we want the third to be a float. We would then use
>>> np.genfromtxt(StringIO(test), delimiter=",", dtype=("|S10", int, float))
array([('a', 1, 2.0), ('b', 3, 4.0)],
dtype=[('f0', '|S10'), ('f1', '<i8'), ('f2', '<f8')])
Using an explicit dtype
is much more efficient than using dtype=None
and is the recommended way.
In both cases (dtype=None
or explicit, non-homogeneous dtype
), you end up with a structured array.
[Note: With dtype=None
, the input is parsed a second time and the type of each column is updated to match the larger type possible: first we try a bool, then an int, then a float, then a complex, then we keep a string if all else fails. The implementation is rather clunky, actually. There had been some attempts to make the type guessing more efficient (using regexp), but nothing that stuck so far]
You might also think about taking a different approach, and replacing the call to the network resource with a stub or mock object. Using Sinon, you can decouple the app from the network service, focusing your development efforts.
Either declare set1 and set2 as floats instead of integers or cast them to floats as part of the calculation:
SET @weight= CAST(@set1 AS float) / CAST(@set2 AS float);
Form correlation matrix, in my case zdf is the dataframe which i need perform correlation matrix.
corrMatrix =zdf.corr()
corrMatrix.to_csv('sm_zscaled_correlation_matrix.csv');
html = corrMatrix.style.background_gradient(cmap='RdBu').set_precision(2).render()
# Writing the output to a html file.
with open('test.html', 'w') as f:
print('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-widthinitial-scale=1.0"><title>Document</title></head><style>table{word-break: break-all;}</style><body>' + html+'</body></html>', file=f)
Then we can take screenshot. or convert html to an image file.
.item .content{
width: 94.1%;
background: #2d2d2d;
padding: 3%;
border-top: solid 1px #000;
position: relative;
}
.item .content:before{
content: "";
display: block;
position: absolute;
top: 0px;
left: 0;
width: 100%;
height: 1px;
-webkit-box-shadow: 0px 1px 13px rgba(255,255,255,1);
-moz-box-shadow: 0px 1px 13px rgba(255,255,255,1);
box-shadow: 0px 1px 13px rgba(255,255,255,1);
z-index: 100;
}
I am like using something like it for it.
I know this is not possible for alert(), so I guess it is not possible for confirm either. Reason is security: it is not allowed for you to change it so you wouldn't present yourself as some system process or something.
$url = "http://www.example/images/image.gif";
$save_name = "image.gif";
$save_directory = "/var/www/example/downloads/";
if(is_writable($save_directory)) {
file_put_contents($save_directory . $save_name, file_get_contents($url));
} else {
exit("Failed to write to directory "{$save_directory}");
}
Run ./mnistCUDNN
in /usr/src/cudnn_samples_v7/mnistCUDNN
Here is an example:
cudnnGetVersion() : 7005 , CUDNN_VERSION from cudnn.h : 7005 (7.0.5)
Host compiler version : GCC 5.4.0
There are 1 CUDA capable devices on your machine :
device 0 : sms 30 Capabilities 6.1, SmClock 1645.0 Mhz, MemSize (Mb) 24446, MemClock 4513.0 Mhz, Ecc=0, boardGroupID=0
Using device 0
Double equals ==
will always check based on object identity, regardless of the objects' implementation of hashCode or equals. Of course - make sure the object references you are comparing are volatile
(in a 1.5+ JVM).
If you really must have the original Object toString result (although it's not the best solution for your example use-case), the Commons Lang library has a method ObjectUtils.identityToString(Object) that will do what you want. From the JavaDoc:
public static java.lang.String identityToString(java.lang.Object object)
Gets the toString that would be produced by Object if a class did not override toString itself. null will return null.
ObjectUtils.identityToString(null) = null
ObjectUtils.identityToString("") = "java.lang.String@1e23"
ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
use the scan method e.g.
curl -XGET 'localhost:9200/_search?search_type=scan&scroll=10m&size=50' -d '
{
"query" : {
"match_all" : {}
}
}
see here
You have a process that is already using that port. netstat -tulpn
will enable one to find the process ID of that is using a particular port.
Note: This answer applies to Windows PowerShell; by contrast, in the cross-platform PowerShell Core edition (v6+), UTF-8 without BOM is the default encoding, across all cmdlets.
In other words: If you're using PowerShell [Core] version 6 or higher, you get BOM-less UTF-8 files by default (which you can also explicitly request with -Encoding utf8
/ -Encoding utf8NoBOM
, whereas you get with-BOM encoding with -utf8BOM
).
If you're running Windows 10 and you're willing to switch to BOM-less UTF-8 encoding system-wide - which can have side effects - even Windows PowerShell can be made to use BOM-less UTF-8 consistently - see this answer.
To complement M. Dudley's own simple and pragmatic answer (and ForNeVeR's more concise reformulation):
For convenience, here's advanced function Out-FileUtf8NoBom
, a pipeline-based alternative that mimics Out-File
, which means:
Out-File
in a pipeline.Out-File
.-UseLF
switch allows you transform Windows-style CRLF newlines to Unix-style LF-only newlines.Example:
(Get-Content $MyPath) | Out-FileUtf8NoBom $MyPath # Add -UseLF for Unix newlines
Note how (Get-Content $MyPath)
is enclosed in (...)
, which ensures that the entire file is opened, read in full, and closed before sending the result through the pipeline. This is necessary in order to be able to write back to the same file (update it in place).
Generally, though, this technique is not advisable for 2 reasons: (a) the whole file must fit into memory and (b) if the command is interrupted, data will be lost.
A note on memory use:
Source code of function Out-FileUtf8NoBom
:
Note: The function is also available as an MIT-licensed Gist, and only it will be maintained going forward.
You can install it directly with the following command (while I can personally assure you that doing so is safe, you should always check the content of a script before directly executing it this way):
# Download and define the function.
irm https://gist.github.com/mklement0/8689b9b5123a9ba11df7214f82a673be/raw/Out-FileUtf8NoBom.ps1 | iex
function Out-FileUtf8NoBom {
<#
.SYNOPSIS
Outputs to a UTF-8-encoded file *without a BOM* (byte-order mark).
.DESCRIPTION
Mimics the most important aspects of Out-File:
* Input objects are sent to Out-String first.
* -Append allows you to append to an existing file, -NoClobber prevents
overwriting of an existing file.
* -Width allows you to specify the line width for the text representations
of input objects that aren't strings.
However, it is not a complete implementation of all Out-File parameters:
* Only a literal output path is supported, and only as a parameter.
* -Force is not supported.
* Conversely, an extra -UseLF switch is supported for using LF-only newlines.
Caveat: *All* pipeline input is buffered before writing output starts,
but the string representations are generated and written to the target
file one by one.
.NOTES
The raison d'être for this advanced function is that Windows PowerShell
lacks the ability to write UTF-8 files without a BOM: using -Encoding UTF8
invariably prepends a BOM.
Copyright (c) 2017, 2020 Michael Klement <[email protected]> (http://same2u.net),
released under the [MIT license](https://spdx.org/licenses/MIT#licenseText).
#>
[CmdletBinding()]
param(
[Parameter(Mandatory, Position=0)] [string] $LiteralPath,
[switch] $Append,
[switch] $NoClobber,
[AllowNull()] [int] $Width,
[switch] $UseLF,
[Parameter(ValueFromPipeline)] $InputObject
)
#requires -version 3
# Convert the input path to a full one, since .NET's working dir. usually
# differs from PowerShell's.
$dir = Split-Path -LiteralPath $LiteralPath
if ($dir) { $dir = Convert-Path -ErrorAction Stop -LiteralPath $dir } else { $dir = $pwd.ProviderPath}
$LiteralPath = [IO.Path]::Combine($dir, [IO.Path]::GetFileName($LiteralPath))
# If -NoClobber was specified, throw an exception if the target file already
# exists.
if ($NoClobber -and (Test-Path $LiteralPath)) {
Throw [IO.IOException] "The file '$LiteralPath' already exists."
}
# Create a StreamWriter object.
# Note that we take advantage of the fact that the StreamWriter class by default:
# - uses UTF-8 encoding
# - without a BOM.
$sw = New-Object System.IO.StreamWriter $LiteralPath, $Append
$htOutStringArgs = @{}
if ($Width) {
$htOutStringArgs += @{ Width = $Width }
}
# Note: By not using begin / process / end blocks, we're effectively running
# in the end block, which means that all pipeline input has already
# been collected in automatic variable $Input.
# We must use this approach, because using | Out-String individually
# in each iteration of a process block would format each input object
# with an indvidual header.
try {
$Input | Out-String -Stream @htOutStringArgs | % {
if ($UseLf) {
$sw.Write($_ + "`n")
}
else {
$sw.WriteLine($_)
}
}
} finally {
$sw.Dispose()
}
}
With jQuery (and without FormData API) you can use something like this:
function readFile(file){
var loader = new FileReader();
var def = $.Deferred(), promise = def.promise();
//--- provide classic deferred interface
loader.onload = function (e) { def.resolve(e.target.result); };
loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
loader.onerror = loader.onabort = function (e) { def.reject(e); };
promise.abort = function () { return loader.abort.apply(loader, arguments); };
loader.readAsBinaryString(file);
return promise;
}
function upload(url, data){
var def = $.Deferred(), promise = def.promise();
var mul = buildMultipart(data);
var req = $.ajax({
url: url,
data: mul.data,
processData: false,
type: "post",
async: true,
contentType: "multipart/form-data; boundary="+mul.bound,
xhr: function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
def.notify(percent);
}
}, false);
}
return xhr;
}
});
req.done(function(){ def.resolve.apply(def, arguments); })
.fail(function(){ def.reject.apply(def, arguments); });
promise.abort = function(){ return req.abort.apply(req, arguments); }
return promise;
}
var buildMultipart = function(data){
var key, crunks = [], bound = false;
while (!bound) {
bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
}
for (var key = 0, l = data.length; key < l; key++){
if (typeof(data[key].value) !== "string") {
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
"Content-Type: application/octet-stream\r\n"+
"Content-Transfer-Encoding: binary\r\n\r\n"+
data[key].value[0]);
}else{
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
data[key].value);
}
}
return {
bound: bound,
data: crunks.join("\r\n")+"\r\n--"+bound+"--"
};
};
//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
var formData = form.find(":input:not('#file')").serializeArray();
formData.file = [fileData, $file[0].files[0].name];
upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});
With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})
The warning comes up because Tomcat scans all Jars for TLDs (Tagging Library Definitions).
Step1: To see which JARs are throwing up this warning, insert he following line to tomcat/conf/logging.properties
org.apache.jasper.servlet.TldScanner.level = FINE
Now you should be able to see warnings with a detail of which JARs are causing the intial warning
Step2 Since skipping unneeded JARs during scanning can improve startup time and JSP compilation time, we will skip un-needed JARS in the catalina.properties
file. You have two options here -
tomcat.util.scan.StandardJarScanFilter.jarsToSkip
. But this can get cumbersome if you have a lot jars or if the jars keep changing.tomcat.util.scan.StandardJarScanFilter.jarsToSkip=*
to skip all the jarsYou should now not see the above warnings and if you have a considerably large application, it should save you significant time in deploying an application.
Note: Tested in Tomcat8
In Python, functions are first-class objects, this means: function references can be passed in inputs to other functions and/or methods, and executed from inside them.
Instances of Classes (aka Objects), can be treated as if they were functions: pass them to other methods/functions and call them. In order to achieve this, the __call__
class function has to be specialized.
def __call__(self, [args ...])
It takes as an input a variable number of arguments. Assuming x
being an instance of the Class X
, x.__call__(1, 2)
is analogous to calling x(1,2)
or the instance itself as a function.
In Python, __init__()
is properly defined as Class Constructor (as well as __del__()
is the Class Destructor). Therefore, there is a net distinction between __init__()
and __call__()
: the first builds an instance of Class up, the second makes such instance callable as a function would be without impacting the lifecycle of the object itself (i.e. __call__
does not impact the construction/destruction lifecycle) but it can modify its internal state (as shown below).
Example.
class Stuff(object):
def __init__(self, x, y, range):
super(Stuff, self).__init__()
self.x = x
self.y = y
self.range = range
def __call__(self, x, y):
self.x = x
self.y = y
print '__call__ with (%d,%d)' % (self.x, self.y)
def __del__(self):
del self.x
del self.y
del self.range
>>> s = Stuff(1, 2, 3)
>>> s.x
1
>>> s(7, 8)
__call__ with (7,8)
>>> s.x
7
Oracle 11g R2:
create table table1 (
id number,
name varchar2(10),
desc_ varchar2(10)
);
create table table2 (
id number,
name varchar2(10),
desc_ varchar2(10)
);
insert into table1 values(1, 'a', 'abc');
insert into table1 values(2, 'b', 'def');
insert into table1 values(3, 'c', 'ghi');
insert into table2 values(1, 'x', '123');
insert into table2 values(2, 'y', '456');
merge into table1 t1
using (select * from table2) t2
on (t1.id = t2.id)
when matched then update set t1.name = t2.name, t1.desc_ = t2.desc_;
select * from table1;
ID NAME DESC_
---------- ---------- ----------
1 x 123
2 y 456
3 c ghi
You might be needing a cleanup:
git gc --prune=now
or you might be needing a prune:
git remote prune public
prune
Deletes all stale tracking branches under <name>. These stale branches have already been removed from the remote repository referenced by <name>, but are still locally available in "remotes/<name>".
With --dry-run option, report what branches will be pruned, but do no actually prune them.
However, it appears these should have been cleaned up earlier with
git remote rm public
rm
Remove the remote named <name>. All remote tracking branches and configuration settings for the remote are removed.
So it might be you hand-edited your config file and this did not occur, or you have privilege problems.
Maybe run that again and see what happens.
If you take a look in the revision logs, you'll note I suggested more "correct" techniques, which for whatever reason didn't want to work on their repository.
I suspected the OP had done something that left their tree in an inconsistent state that caused it to behave a bit strangely, and git gc
was required to fix up the left behind cruft.
Usually git branch -rd origin/badbranch
is sufficient for nuking a local tracking branch , or git push origin :badbranch
for nuking a remote branch, and usually you will never need to call git gc
This is more of an xpath question, but like this, assuming the context is the parent element:
<xsl:value-of select="name/@attribute1" />
First make sure you have at least gem version 2.1.0
gem update --system
gem --version
# 2.6.4
To uninstall simply run:
gem uninstall --all
You may need to use the sudo
command:
sudo gem uninstall --all
Compare date only instead of date + time (NOW) with:
CURDATE()
Here is a talk about the differences between web sockets and server sent events. Since Java EE 7 a WebSocket API is already part of the specification and it seems that server sent events will be released in the next version of the enterprise edition.
if ( window.onsubmit ) {
//
} else {
alert("Function does not exist.");
}
I recently needed to document how to get a version of it installed, so I've copied my steps here, as the other answers were using different sources from what I recommend, which is Cygwin. I like Cygwin because it is well maintained and provides a wealth of other utilities for Windows. Cygwin also allows you to easily update the versions as needed when vulnerabilities are fixed. Please update your version of OpenSSL often!
Open a Windows Command prompt and check to see if you have OpenSSL installed by entering: openssl version
If you get an error message that the command is NOT recognized, then install OpenSSL by referring to Cygwin following the summary steps below:
Basically, download and run the Cygwin Windows Setup App to install and to update as needed the OpenSSL application:
C:\Program Files\mosquitto>openssl versionOpenSSL 1.1.1f 31 Mar 2020
Why not making your form a dialogue box:
myForm.ShowDialog();
There is a trick, Arithmetic exceptions only happen when you are playing around with integers and only during / or % operation.
If there is any floating point number in an arithmetic operation, internally all integers will get converted into floating point. This may help you to remember things easily.
Don't forget to enable tcp/ip connections in SQL SERVER Configuration tools
to link dynamic and static library within one line, you must put static libs after dynamic libs and object files, like this:
gcc -lssl main.o -lFooLib -o main
otherwise, it will not work. it does take me sometime to figure it out.
Maybe your file contains CRLF terminator. Every lines followed by \r\n.
awk
recognizes the $2
actually $2\r
. The \r
means goto the start of the line.
{print $2\r$1}
will print $2
first, then return to the head, then print $1
. So the field 2 is overlaid by the field 1.
A view represents a virtual table. You can join multiple tables in a view and use the view to present the data as if the data were coming from a single table.
A stored procedure uses parameters to do a function... whether it is updating and inserting data, or returning single values or data sets.
Creating Views and Stored Procedures - has some information from Microsoft as to when and why to use each.
Say I have two tables:
tbl_user
, with columns: user_id
, user_name
, user_pw
tbl_profile
, with columns: profile_id
, user_id
, profile_description
So, if I find myself querying from those tables A LOT... instead of doing the join in EVERY piece of SQL, I would define a view like:
CREATE VIEW vw_user_profile
AS
SELECT A.user_id, B.profile_description
FROM tbl_user A LEFT JOIN tbl_profile B ON A.user_id = b.user_id
GO
Thus, if I want to query profile_description
by user_id
in the future, all I have to do is:
SELECT profile_description FROM vw_user_profile WHERE user_id = @ID
That code could be used in a stored procedure like:
CREATE PROCEDURE dbo.getDesc
@ID int
AS
BEGIN
SELECT profile_description FROM vw_user_profile WHERE user_id = @ID
END
GO
So, later on, I can call:
dbo.getDesc 25
and I will get the description for user_id
25, where the 25
is your parameter.
There is obviously a lot more detail, this is just the basic idea.
Yes, it a vice versa. It depends on which side of the relationship the entity is present on.
For example, if one department can employ for several employees then, department to employee is a one to many relationship (1 department employs many employees), while employee to department relationship is many to one (many employees work in one department).
More info on the relationship types:
This does it without regexps, but requires the PECL HTTP extension.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
curl_close($ch);
$headers = http_parse_headers($result);
$cookobjs = Array();
foreach($headers AS $k => $v){
if (strtolower($k)=="set-cookie"){
foreach($v AS $k2 => $v2){
$cookobjs[] = http_parse_cookie($v2);
}
}
}
$cookies = Array();
foreach($cookobjs AS $row){
$cookies[] = $row->cookies;
}
$tmp = Array();
// sort k=>v format
foreach($cookies AS $v){
foreach ($v AS $k1 => $v1){
$tmp[$k1]=$v1;
}
}
$cookies = $tmp;
print_r($cookies);
I found that the following worked better...
private void EndResponse()
{
try
{
Context.Response.End();
}
catch (System.Threading.ThreadAbortException err)
{
System.Threading.Thread.ResetAbort();
}
catch (Exception err)
{
}
}
You need to fix your include_path
system variable to point to the correct location.
To fix it edit the php.ini
file. In that file you will find a line that says, "include_path = ...
". (You can find out what the location of php.ini by running phpinfo()
on a page.) Fix the part of the line that says, "\xampplite\php\pear\PEAR
" to read "C:\xampplite\php\pear
". Make sure to leave the semi-colons before and/or after the line in place.
Restart PHP and you should be good to go. To restart PHP in IIS you can restart the application pool assigned to your site or, better yet, restart IIS all together.
Implementing interfaces with abstract base classes is much simpler in modern Python 3 and they serve a purpose as an interface contract for plug-in extensions.
Create the interface/abstract base class:
from abc import ABC, abstractmethod
class AccountingSystem(ABC):
@abstractmethod
def create_purchase_invoice(self, purchase):
pass
@abstractmethod
def create_sale_invoice(self, sale):
log.debug('Creating sale invoice', sale)
Create a normal subclass and override all abstract methods:
class GizmoAccountingSystem(AccountingSystem):
def create_purchase_invoice(self, purchase):
submit_to_gizmo_purchase_service(purchase)
def create_sale_invoice(self, sale):
super().create_sale_invoice(sale)
submit_to_gizmo_sale_service(sale)
You can optionally have common implementation in the abstract methods as in create_sale_invoice()
, calling it with super()
explicitly in the subclass as above.
Instantiation of a subclass that does not implement all the abstract methods fails:
class IncompleteAccountingSystem(AccountingSystem):
pass
>>> accounting = IncompleteAccountingSystem()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class IncompleteAccountingSystem with abstract methods
create_purchase_invoice, create_sale_invoice
You can also have abstract properties, static and class methods by combining corresponding annotations with @abstractmethod
.
Abstract base classes are great for implementing plugin-based systems. All imported subclasses of a class are accessible via __subclasses__()
, so if you load all classes from a plugin directory with importlib.import_module()
and if they subclass the base class, you have direct access to them via __subclasses__()
and you can be sure that the interface contract is enforced for all of them during instantiation.
Here's the plugin loading implementation for the AccountingSystem
example above:
...
from importlib import import_module
class AccountingSystem(ABC):
...
_instance = None
@classmethod
def instance(cls):
if not cls._instance:
module_name = settings.ACCOUNTING_SYSTEM_MODULE_NAME
import_module(module_name)
subclasses = cls.__subclasses__()
if len(subclasses) > 1:
raise InvalidAccountingSystemError('More than one '
f'accounting module: {subclasses}')
if not subclasses or module_name not in str(subclasses[0]):
raise InvalidAccountingSystemError('Accounting module '
f'{module_name} does not exist or does not '
'subclass AccountingSystem')
cls._instance = subclasses[0]()
return cls._instance
Then you can access the accounting system plugin object through the AccountingSystem
class:
>>> accountingsystem = AccountingSystem.instance()
(Inspired by this PyMOTW-3 post.)
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("new").show();
$("new").hide();
You could use the regular expression library which accepts the Posix standard [[:ASCII:]] definition.
jQuery's attr
method returns the value of the attribute:
The
.attr()
method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's.each()
or.map()
method.
All you need is:
$('html').attr('lang') == 'fr-FR'
However, you might want to do a case-insensitive match:
$('html').attr('lang').toLowerCase() === 'fr-fr'
jQuery's val
method returns the value of a form element.
The
.val()
method is primarily used to get the values of form elements such asinput
,select
andtextarea
. In the case of<select multiple="multiple">
elements, the.val()
method returns an array containing each selected option; if no option is selected, it returnsnull
.
You can't really force the optimizer to do anything, but you can guide it.
UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93
Visual Studio Express 2012 has different paths.
Visual Studio Express
With Visual Studio Express 2012 for Web
I did not have to re-install Visual Studio Express
I am not sure I understood your question, but if you write:
mask_data[:3, :3] = 1
mask_data[3:, 3:] = 0
This will make all values of mask data whose x and y indexes are less than 3 to be equal to 1 and all rest to be equal to 0
Scott Murray wrote a great explanation of this[1]. For instance, for the code snippet:
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
He explains using the following:
Note that we use attr() to apply transform as an attribute of g. SVG transforms are quite powerful, and can accept several different kinds of transform definitions, including scales and rotations. But we are keeping it simple here with only a translation transform, which simply pushes the whole g group over and down by some amount.
Translation transforms are specified with the easy syntax of translate(x,y), where x and y are, obviously, the number of horizontal and vertical pixels by which to translate the element.
[1]: From Chapter 8, "Cleaning it up" of Interactive Data Visualization for the Web, which used to be freely available and is now behind a paywall.
As @ J_F answered in the comments, using {r echo = T, results = 'hide'}
.
I wanted to expand on their answer - there are great resources you can access to determine all possible options for your chunk and output display - I keep a printed copy at my desk!
You can find them either on the RStudio Website under Cheatsheets (look for the R Markdown cheatsheet and R Markdown Reference Guide) or, in RStudio, navigate to the "Help" tab, choose "Cheatsheets", and look for the same documents there.
Finally to set default chunk options, you can run (in your first chunk) something like the following code if you want most chunks to have the same behavior:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T,
results = "hide")
```
Later, you can modify the behavior of individual chunks like this, which will replace the default value for just the results option.
```{r analysis, results="markup"}
# code here
```
One more thing to check is that you have spelled the named instance correctly!
This article is very helpful in troubleshooting connection problems: How to Troubleshoot Connecting to the SQL Server Database Engine
May be below approach will be helpful for someone TS with reactjs
interface Event {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent<T> extends Event<T> {
UserId: string;
}
Swift 3
let vc0 : ViewController1 = ViewController1()
let vc2: NavigationController1 = NavigationController1(rootViewController: vc0)
self.present(vc2, animated: true, completion: nil)
Faced the same problem, I was not able to run wordpress docker container with mysql version 8 as its default authentication mechanism is caching_sha2_password instead of mysql_native_password.
In order to fix this problem we must reset default authentication mechanism to mysql_native_password.
Find my.cnf file in your mysql installation, usually on a linux machine it is at the following location - /etc/mysql
Edit my.cnf file and add following line just under heading [mysqld]
default_authentication_plugin= mysql_native_password
Save the file then log into mysql command line using root user
run command FLUSH PRIVILEGES;
$('#abc span').html('A new text for the span.');
Solution with no extra packages:
var min = lst.OrderBy(i => i.StartDate).FirstOrDefault();
var max = lst.OrderBy(i => i.StartDate).LastOrDefault();
also you can wrap it into extension:
public static class LinqExtensions
{
public static T MinBy<T, TProp>(this IEnumerable<T> source, Func<T, TProp> propSelector)
{
return source.OrderBy(propSelector).FirstOrDefault();
}
public static T MaxBy<T, TProp>(this IEnumerable<T> source, Func<T, TProp> propSelector)
{
return source.OrderBy(propSelector).LastOrDefault();
}
}
and in this case:
var min = lst.MinBy(i => i.StartDate);
var max = lst.MaxBy(i => i.StartDate);
By the way... O(n^2) is not the best solution. Paul Betts gave fatster solution than my. But my is still LINQ solution and it's more simple and more short than other solutions here.
For PHP's own session cookies on Apache:
add this to your Apache configuration or .htaccess
<IfModule php5_module>
php_flag session.cookie_httponly on
</IfModule>
This can also be set within a script, as long as it is called before session_start()
.
ini_set( 'session.cookie_httponly', 1 );
edit: I just saw you meant in c#. Here is a better way with unmanaged code:
ManagementClass oMClass = new ManagementClass ("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection colMObj = oMCLass.GetInstances();
foreach(ManagementObject objMO in colMObj)
Console.WriteLine(objMO["MacAddress"].ToString());
First of all, stay away from Arraylist
or Hashtable
. Those classes are to be considered deprecated, in favor of generics. They are still in the language for legacy purposes.
Now, what you are looking for is the List<T>
class. Note that if T is a value type you will have contiguos memory, but not if T is a reference type, for obvious reasons.
Remove ng.ps1
from the directory C:\Users\%username%\AppData\Roaming\npm\
then try clearing the npm cache at C:\Users\%username%\AppData\Roaming\npm-cache\
Just push to the branch that the pull request references. As long as the pull request is still open, it should get updated with any added commits automatically.
you have to use the 'prop' function :
.prop('checked', true);
Before jQuery 1.6 (see user2063626's answer):
.attr('checked','checked')
The simplest solution would be (using 'upstream
' as the remote name referencing the original repo forked):
git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master
git push origin master --force
(Similar to this GitHub page, section "What should I do if I’m in a bad situation?")
Be aware that you can lose changes done on the master
branch (both locally, because of the reset --hard
, and on the remote side, because of the push --force
).
An alternative would be, if you want to preserve your commits on master
, to replay those commits on top of the current upstream/master
.
Replace the reset part by a git rebase upstream/master
. You will then still need to force push.
See also "What should I do if I’m in a bad situation?"
A more complete solution, backing up your current work (just in case) is detailed in "Cleanup git master branch and move some commit to new branch".
See also "Pull new updates from original GitHub repository into forked GitHub repository" for illustrating what "upstream
" is.
Note: recent GitHub repos do protect the master
branch against push --force
.
So you will have to un-protect master
first (see picture below), and then re-protect it after force-pushing).
Note: on GitHub specifically, there is now (February 2019) a shortcut to delete forked repos for pull requests that have been merged upstream.
If your class2 looks like this having static members
public class2
{
static int var = 1;
public static void myMethod()
{
// some code
}
}
Then you can simply call them like
class2.myMethod();
class2.var = 1;
If you want to access non-static members then you would have to instantiate an object.
class2 object = new class2();
object.myMethod(); // non static method
object.var = 1; // non static variable
Windows
1- Find: CTRL + F
2- Select-in: Alt + Enter
Now you can change all the selection in one shot like "seen-on-tv" ST homepage Spot.
Credit goes to : https://superuser.com/a/921806/342825
String input = EditTextinput.getText().toString();
input = input.replace(" ", "");
Sometimes you would want to remove only the spaces at the beginning or end of the String (not the ones in the middle). If that's the case you can use trim
:
input = input.trim();
As definition of "Foo" has lot's of meanings:
bar, and baz are often compounded together to make such words as foobar, barbaz, and foobaz. www.nationmaster.com/encyclopedia/Metasyntactic-variable
Major concepts in CML, usually mapped directly onto XMLElements (to be discussed later). wwmm.ch.cam.ac.uk/blogs/cml/
Measurement of the total quantity of pasture in a paddock, expressed in kilograms of pasture dry matter per hectare (kg DM/ha) www.lifetimewool.com.au/glossary.aspx
Forward Observation Officer. An artillery officer who remained with infantry and tank battalions to set up observation posts in the front lines from which to observe enemy positions and radio the coordinates of targets to the guns further in the rear. members.fortunecity.com/lniven/definition.htm
is the first metasyntactic variable commonly used. It is sometimes combined with bar to make foobar. This suggests that foo may have originated with the World War II slang term fubar, as an acronym for fucked/fouled up beyond all recognition, although the Jargon File makes a pretty good case ... explanation-guide.info/meaning/Metasyntactic-variable.html
Foo is a metasyntactic variable used heavily in computer science to represent concepts abstractly and can be used to represent any part of a ... en.wikipedia.org/wiki/FOo
Foo is the world of dreams (no its not) in Obert Skye's Leven Thumps series. Although it has many original inhabitants, most of its current dwellers are from Reality, and are known as nits. ... en.wikipedia.org/wiki/Foo (place)
Also foo’. Representation of fool (foolish person), in a Mr. T accent en.wiktionary.org/wiki/foo
Resource: google
There is no difference between US ASCII and UTF-8, so there isn't any need to reconvert it.
But here a little hint, if you have trouble with special-chars while recoding.
Add //TRANSLIT after the source-charset-Parameter.
Example:
iconv -f ISO-8859-1//TRANSLIT -t UTF-8 filename.sql > utf8-filename.sql
This helps me with strange types of quotes, which are always breaking the character set reencode process.
map <int , char>::iterator itr;
for(itr = MyMap.begin() ; itr!= MyMap.end() ; itr++)
{
if (itr->second == 'c')
{
cout<<itr->first<<endl;
}
}
SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.
Let's suppose you have two databases on the same server - Db1
and Db2
. Db1
has a table called Clients
with a column ClientId
and Db2
has a table called Messages
with a column ClientId
(let's leave asside why those tables are in different databases).
Now, to perform a join on the above-mentioned tables you will be using this query:
select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId
Once you have the indexPath of your cell, you can do something like:
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
In Xcode 4.6 and higher:
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:@[indexPathOfYourCell] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
You can set whatever your like as animation effect, of course.
Suppose we have variable date , month and year then we can write it in the java like this.
int date=15,month=4,year=2016;
System.out.println(date+ "/"+month+"/"+year);
output of this will be like below:
15/4/2016
I suspect you did not know that there are different &
escapes in HTML. The W3C you can see the codes. ×
means ×
in HTML code. Use &times
instead.
For bootstrap 4
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<form class="form-inline my-2 my-lg-0">
<div class="input-group">
<input class="form-control" type="search" placeholder="Search">
<div class="input-group-append">
<div class="input-group-text"><i class="fa fa-search"></i></div>
</div>
</div>
</form>
I had this error and then I realized that my package.json file was mostly empty. Make sure you have all the dependencies you have first.
use yarn add DEPENDENCY_NAME
to add dependencies.
I'm updating my answer...
antMatcher()
is a method of HttpSecurity
, it doesn't have anything to do with authorizeRequests()
. Basically, http.antMatcher()
tells Spring to only configure HttpSecurity
if the path matches this pattern.
The authorizeRequests().antMatchers()
is then used to apply authorization to one or more paths you specify in antMatchers()
. Such as permitAll()
or hasRole('USER3')
. These only get applied if the first http.antMatcher()
is matched.
This seems to be a bug in the newly added support for nested fragments. Basically, the child FragmentManager
ends up with a broken internal state when it is detached from the activity. A short-term workaround that fixed it for me is to add the following to onDetach()
of every Fragment
which you call getChildFragmentManager()
on:
@Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
UPDATE:
All of the above answers won't work for the repeated values, @BenBolker's answer using duplicated()
predicate solves this:
full_vector[!full_vector %in% searched_vector | duplicated(full_vector)]
Original Answer: here I write a little function for this:
exclude_val<-function(full_vector,searched_vector){
found=c()
for(i in full_vector){
if(any(is.element(searched_vector,i))){
searched_vector[(which(searched_vector==i))[1]]=NA
}
else{
found=c(found,i)
}
}
return(found)
}
so, let's say full_vector=c(1,2,3,4,1)
and searched_vector=c(1,2,3)
.
exclude_val(full_vector,searched_vector)
will return (4,1), however above answers will return just (4)
.
If you have a Decimal or similar numeric type, you can use:
Math.Round(myNumber, 2)
EDIT: So, in your case, it would be:
Public Class Form1
Private Sub btncalc_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btncalc.Click
txtA.Text = Math.Round((Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)), 2)
txtB.Text = Math.Round((Val(txtA.Text) * 1000 / Val(txtG.Text)), 2)
End Sub
End Class
For me, for Chrome/Webkit, document.width / jQuery(document).width()
did not work. When I made my window small and zoomed into my site such that horizontal scrollbars appeared, document.width / jQuery(document).width()
did not equal 1 at the default zoom. This is because document.width
includes part of the document outside the viewport.
Using window.innerWidth
and window.outerWidth
worked. For some reason in Chrome, outerWidth is measured in screen pixels and innerWidth is measured in css pixels.
var screenCssPixelRatio = (window.outerWidth - 8) / window.innerWidth;
if (screenCssPixelRatio >= .46 && screenCssPixelRatio <= .54) {
zoomLevel = "-4";
} else if (screenCssPixelRatio <= .64) {
zoomLevel = "-3";
} else if (screenCssPixelRatio <= .76) {
zoomLevel = "-2";
} else if (screenCssPixelRatio <= .92) {
zoomLevel = "-1";
} else if (screenCssPixelRatio <= 1.10) {
zoomLevel = "0";
} else if (screenCssPixelRatio <= 1.32) {
zoomLevel = "1";
} else if (screenCssPixelRatio <= 1.58) {
zoomLevel = "2";
} else if (screenCssPixelRatio <= 1.90) {
zoomLevel = "3";
} else if (screenCssPixelRatio <= 2.28) {
zoomLevel = "4";
} else if (screenCssPixelRatio <= 2.70) {
zoomLevel = "5";
} else {
zoomLevel = "unknown";
}
Try this from the command line to change the git config details.
git config --global --replace-all user.name "Your New Name"
git config --global --replace-all user.email "Your new email"
You can pass any number of arguments to the function that apply
is calling through either unnamed arguments, passed as a tuple to the args
parameter, or through other keyword arguments internally captured as a dictionary by the kwds
parameter.
For instance, let's build a function that returns True for values between 3 and 6, and False otherwise.
s = pd.Series(np.random.randint(0,10, 10))
s
0 5
1 3
2 1
3 1
4 6
5 0
6 3
7 4
8 9
9 6
dtype: int64
s.apply(lambda x: x >= 3 and x <= 6)
0 True
1 True
2 False
3 False
4 True
5 False
6 True
7 True
8 False
9 True
dtype: bool
This anonymous function isn't very flexible. Let's create a normal function with two arguments to control the min and max values we want in our Series.
def between(x, low, high):
return x >= low and x =< high
We can replicate the output of the first function by passing unnamed arguments to args
:
s.apply(between, args=(3,6))
Or we can use the named arguments
s.apply(between, low=3, high=6)
Or even a combination of both
s.apply(between, args=(3,), high=6)
An Internet Information Services (IIS) worker process is a windows process (w3wp.exe) which runs Web applications, and is responsible for handling requests sent to a Web Server for a specific application pool.
It is the worker process for IIS. Each application pool creates at least one instance of w3wp.exe
and that is what actually processes requests in your application. It is not dangerous to attach to this, that is just a standard windows message.
Well, despite of this entry being very old. I was using bootstrap's modal this week and came along this "issue". My solution was somehow a mix of everything, just posting it as it may help someone :)
First check the Z-index war to get a fix there!
The first thing you can do is deactivate the modal backdrop, I had the Stackoverflow post before but I lost it, so I wont take the credit for it, keep that in mind; but it goes like this in the HTML code:
<!-- from the bootstrap's docs -->_x000D_
<div class="modal fade" tabindex="-1" role="dialog" data-backdrop="false">_x000D_
<!-- mind the data-backdrop="false" -->_x000D_
<div class="modal-dialog" role="document">_x000D_
<!-- ... modal content -->_x000D_
</div>_x000D_
</div>
_x000D_
The second approach was to have an event listener attached to the bootstrap's shown modal event. This is somehow not so pretty as you may think but maybe with some tricks by your own may somehow work. The advantage of this is that the element attaches the event listener and you can completely forget about it as long as you have the event listener attached :)
var element = $('selector-to-your-modal');_x000D_
_x000D_
// also taken from bootstrap 3 docs_x000D_
$(element).on('shown.bs.modal', function(e) {_x000D_
// keep in mind this only works as long as Bootstrap only supports 1 modal at a time, which is the case in Bootstrap 3 so far..._x000D_
var backDrop = $('.modal-backdrop');_x000D_
$(element).append($(backDrop));_x000D_
});
_x000D_
The second.1 approach is basically the same than the previous but without the event listener.
Hope it helps someone!
There can be one more reason for such behavior - you delete current working directory.
For example:
# in terminal #1
cd /home/user/myJavaApp
# in terminal #2
rm -rf /home/user/myJavaApp
# in terminal #1
java -jar myJar.jar
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
What is the newline character in the C language: \r or \n?
The new-line may be thought of a some char
and it has the value of '\n'
. C11 5.2.1
This C new-line comes up in 3 places: C source code, as a single char
and as an end-of-line in file I/O when in text mode.
Many compilers will treat source text as ASCII. In that case, codes 10, sometimes 13, and sometimes paired 13,10 as new-line for source code. Had the source code been in another character set, different codes may be used. This new-line typically marks the end of a line of source code (actually a bit more complicated here), // comment, and # directives.
In source code, the 2 characters \
and n
represent the char
new-line as \n
. If ASCII is used, this char
would have the value of 10.
In file I/O, in text mode, upon reading the bytes of the input file (and stdin), depending on the environment, when bytes with the value(s) of 10 (Unix), 13,10, (*1) (Windows), 13 (Old Mac??) and other variations are translated in to a '\n'. Upon writing a file (or stdout), the reverse translation occurs.
Note: File I/O in binary mode makes no translation.
The '\r'
in source code is the carriage return char
.
(*1) A lone 13 and/or 10 may also translate into \n
.
getimagesize() returns an array containing the image properties.
list($width, $height) = getimagesize("path/to/image.jpg");
to just get the width and height or
list($width, $height, $type, $attr)
to get some more information.
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
Example
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)
Install
Available on npm as escape-string-regexp
npm install --save escape-string-regexp
Note
See MDN: Javascript Guide: Regular Expressions
Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.
.
.
.
.
escapeRegExp("/path/to/resource.html?search=query");
>>> "\/path\/to\/resource\.html\?search=query"
If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.
var escapeRegExp;
(function () {
// Referring to the table here:
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
// these characters should be escaped
// \ ^ $ * + ? . ( ) | { } [ ]
// These characters only have special meaning inside of brackets
// they do not need to be escaped, but they MAY be escaped
// without any adverse effects (to the best of my knowledge and casual testing)
// : ! , =
// my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)
var specials = [
// order matters for these
"-"
, "["
, "]"
// order doesn't matter for any of these
, "/"
, "{"
, "}"
, "("
, ")"
, "*"
, "+"
, "?"
, "."
, "\\"
, "^"
, "$"
, "|"
]
// I choose to escape every character with '\'
// even though only some strictly require it when inside of []
, regex = RegExp('[' + specials.join('\\') + ']', 'g')
;
escapeRegExp = function (str) {
return str.replace(regex, "\\$&");
};
// test escapeRegExp("/path/to/res?search=this.that")
}());
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
"Vanilla JS” is an expression that got popular after the publishing of a satire website in 2012 (http://vanilla-js.com/). There’s a section covering its story/meaning in this post.
So why the joke? It kind of came as a modern response to the old school knee-jerk reflex of relying on jQuery and additional JS libraries. With the ECMAScript spec and modern browsers capabilities, the need to bypass plain JS with external libraries to maintain consistency across browsers just isn’t there anymore. Here’s a site that shows you how true this is with concrete examples: http://youmightnotneedjquery.com/
Note that all of the stringstream
methods may involve locking around the use of the locale object for formatting. This may be something to be wary of if you're using this conversion from multiple threads...
See here for more. Convert a number to a string with specified length in C++
HTML
<img src="images/bg.jpg" id="bg" alt="">
CSS
#bg {
position: fixed;
top: 0;
left: 0;
/* Preserve aspet ratio */
min-width: 100%;
min-height: 100%;
}
The argument to remove()
is a filter document, so passing in an empty document means 'remove all':
db.user.remove({})
However, if you definitely want to remove everything you might be better off dropping the collection. Though that probably depends on whether you have user defined indexes on the collection i.e. whether the cost of preparing the collection after dropping it outweighs the longer duration of the remove()
call vs the drop()
call.
More details in the docs.
In Java 8,
IntStream.range(0,jsonArray.length()).mapToObj(i->jsonArray.getString(i)).collect(Collectors.toList())
The slightly modified version of COPY
below worked better for me, where I specify the CSV
format. This format treats backslash characters in text without any fuss. The default format is the somewhat quirky TEXT
.
COPY myTable FROM '/path/to/file/on/server' ( FORMAT CSV, DELIMITER('|') );
There are many ways to get jQuery AJAX response. I am sharing with you two common approaches:
First:
use async=false and within function return ajax-object and later get response ajax-object.responseText
/**
* jQuery ajax method with async = false, to return response
* @param {mix} selector - your selector
* @return {mix} - your ajax response/error
*/
function isSession(selector) {
return $.ajax({
type: "POST",
url: '/order.html',
data: {
issession: 1,
selector: selector
},
dataType: "html",
async: !1,
error: function() {
alert("Error occured")
}
});
}
// global param
var selector = !0;
// get return ajax object
var ajaxObj = isSession(selector);
// store ajax response in var
var ajaxResponse = ajaxObj.responseText;
// check ajax response
console.log(ajaxResponse);
// your ajax callback function for success
ajaxObj.success(function(response) {
alert(response);
});
Second:
use $.extend method and make a new function like ajax
/**
* xResponse function
*
* xResponse method is made to return jQuery ajax response
*
* @param {string} url [your url or file]
* @param {object} your ajax param
* @return {mix} [ajax response]
*/
$.extend({
xResponse: function(url, data) {
// local var
var theResponse = null;
// jQuery ajax
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: "html",
async: false,
success: function(respText) {
theResponse = respText;
}
});
// Return the response text
return theResponse;
}
});
// set ajax response in var
var xData = $.xResponse('temp.html', {issession: 1,selector: true});
// see response in console
console.log(xData);
you can make it as large as you want...
I dont know why u have to use that, doesnt sound so good to me at all, but if there are only a small amount of functions, you could use a if/elseif construct. I dont know if a direct solution is possible.
something like $foo = "bar"; $test = "foo"; echo $$test;
should return bar, you can try around but i dont think this will work for functions
You must check the String length. You assume that you can do substring(0,38)
as long as String is not null
, but you actually need the String to be of at least 38 characters length.
What you could do is create a new class, similar to @Gregoire's example, however, you would want to override the ToString()
method so it appears correctly in the combo box e.g.
public class Language
{
private string _name;
private string _code;
public Language(string name, string code)
{
_name = name;
_code = code;
}
public string Name { get { return _name; } }
public string Code { get { return _code; } }
public override void ToString()
{
return _name;
}
}
Your problem is that you have to change:
printf("%");
to
printf("%%");
Or you could use ASCII code and write:
printf("%c", 37);
:)
Write yourself a Helper function:
public static bool IsBewteenTwoDates(this DateTime dt, DateTime start, DateTime end)
{
return dt >= start && dt <= end;
}
Then call: .IsBewteenTwoDates(DateTime.Today ,new DateTime(,,));
I should like to contribute the modern answer. The SimpleDateFormat
class is notoriously troublesome, and while it was reasonable to fight one’s way through with it when this question was asked six and a half years ago, today we have much better in java.time, the modern Java date and time API. SimpleDateFormat
and its friend Date
are now considered long outdated, so don’t use them anymore.
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MM/uuuu");
String dateformat = "2012-11-17T00:00:00.000-05:00";
OffsetDateTime dateTime = OffsetDateTime.parse(dateformat);
String monthYear = dateTime.format(monthFormatter);
System.out.println(monthYear);
Output:
11/2012
I am exploiting the fact that your string is in ISO 8601 format, the international standard, and that the classes of java.time parse this format as their default, that is, without any explicit formatter. It’s stil true what the other answers say, you need to parse the original string first, then format the resulting date-time object into a new string. Usually this requires two formatters, only in this case we’re lucky and can do with just one formatter.
SimpleDateFormat.format
cannot accept a String
argument, also when the parameter type is declared to be Object
.mm/yyyy
. Lowercase mm
os for minute of the hour. You need uppercase MM
for month.m
in monthYear
(also because java.time includes a MonthYear
class with uppercase M
, so to avoid confusion).java.time
.If you use System.Diagnostics.Debug.WriteLine(...)
instead of Console.WriteLine()
, then you can see the results in the Output window of Visual Studio.
If your driver is JDBC 4 compliant, there is no need for a dedicated query to test connections. Instead, there is Connection.isValid to test the connection.
JDBC 4 is part of Java 6 from 2006 and you driver should support this by now!
Famous connection pools, like HikariCP, still have a config parameter for specifying a test query but strongly discourage to use it:
connectionTestQuery
If your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" databases that do not support the JDBC4 Connection.isValid() API. This is the query that will be executed just before a connection is given to you from the pool to validate that the connection to the database is still alive. Again, try running the pool without this property, HikariCP will log an error if your driver is not JDBC4 compliant to let you know. Default: none
i have this problem many times until now ,i suggest thees approach :
1-as said check power saveing mode
2-create new project with same application id and package name and copy all source and resource from older project to new one,
Consider the easy, lightweight Java library EasyFlow. From their docs:
With EasyFlow you can:
- implement complex logic but keep your code simple and clean
- handle asynchronous calls with ease and elegance
- avoid concurrency by using event-driven programming approach
- avoid StackOverflow error by avoiding recursion
- simplify design, programming and testing of complex java applications
When you use Object.defineProperties
, by default writable
is set to false
, so _year
and edition
are actually read only properties.
Explicitly set them to writable: true
:
_year: {
value: 2004,
writable: true
},
edition: {
value: 1,
writable: true
},
Check out MDN for this method.
writable
true
if and only if the value associated with the property may be changed with an assignment operator.
Defaults tofalse
.
now you can:
using System.Configuration;
I also had problem understanding next() , but this helped
var app = require("express")();
app.get("/", function(httpRequest, httpResponse, next){
httpResponse.write("Hello");
next(); //remove this and see what happens
});
app.get("/", function(httpRequest, httpResponse, next){
httpResponse.write(" World !!!");
httpResponse.end();
});
app.listen(8080);
I have reformatted your slow sql query with www.prettysql.net
SELECT *
FROM some_table
WHERE
relevant_field in
(
SELECT relevant_field
FROM some_table
GROUP BY relevant_field
HAVING COUNT ( * ) > 1
);
When using a table in both the query and the subquery, you should always alias both, like this:
SELECT *
FROM some_table as t1
WHERE
t1.relevant_field in
(
SELECT t2.relevant_field
FROM some_table as t2
GROUP BY t2.relevant_field
HAVING COUNT ( t2.relevant_field ) > 1
);
Does that help?