As easy as
SELECT lpad(42::text, 4, '0')
References:
sqlfiddle: http://sqlfiddle.com/#!15/d41d8/3665
I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.
cmd >>file.txt 2>&1
Bash executes the redirects from left to right as follows:
>>file.txt
: Open file.txt
in append mode and redirect stdout
there.2>&1
: Redirect stderr
to "where stdout
is currently going". In this case, that is a file opened in append mode. In other words, the &1
reuses the file descriptor which stdout
currently uses.To find table dependencies you can use the sys.sql_expression_dependencies catalog view:
SELECT
referencing_object_name = o.name,
referencing_object_type_desc = o.type_desc,
referenced_object_name = referenced_entity_name,
referenced_object_type_desc =so1.type_desc
FROM sys.sql_expression_dependencies sed
INNER JOIN sys.views o ON sed.referencing_id = o.object_id
LEFT OUTER JOIN sys.views so1 ON sed.referenced_id =so1.object_id
WHERE referenced_entity_name = 'Person'
You can also try out ApexSQL Search a free SSMS and VS add-in that also has the View Dependencies feature. The View Dependencies feature has the ability to visualize all SQL database objects’ relationships, including those between encrypted and system objects, SQL server 2012 specific objects, and objects stored in databases encrypted with Transparent Data Encryption (TDE)
Disclaimer: I work for ApexSQL as a Support Engineer
@Babasaheb Gosavi Answer is perfect if you have one occurrence of the substrings (":" and ";"). but once you have multiple occurrences, it might get little bit tricky.
The best solution I have came up with to work on multiple projects is using four methods inside an object.
So enough talking, let's see the code:
var getFromBetween = {
results:[],
string:"",
getFromBetween:function (sub1,sub2) {
if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return false;
var SP = this.string.indexOf(sub1)+sub1.length;
var string1 = this.string.substr(0,SP);
var string2 = this.string.substr(SP);
var TP = string1.length + string2.indexOf(sub2);
return this.string.substring(SP,TP);
},
removeFromBetween:function (sub1,sub2) {
if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return false;
var removal = sub1+this.getFromBetween(sub1,sub2)+sub2;
this.string = this.string.replace(removal,"");
},
getAllResults:function (sub1,sub2) {
// first check to see if we do have both substrings
if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return;
// find one result
var result = this.getFromBetween(sub1,sub2);
// push it to the results array
this.results.push(result);
// remove the most recently found one from the string
this.removeFromBetween(sub1,sub2);
// if there's more substrings
if(this.string.indexOf(sub1) > -1 && this.string.indexOf(sub2) > -1) {
this.getAllResults(sub1,sub2);
}
else return;
},
get:function (string,sub1,sub2) {
this.results = [];
this.string = string;
this.getAllResults(sub1,sub2);
return this.results;
}
};
var str = 'this is the haystack {{{0}}} {{{1}}} {{{2}}} {{{3}}} {{{4}}} some text {{{5}}} end of haystack';
var result = getFromBetween.get(str,"{{{","}}}");
console.log(result);
// returns: [0,1,2,3,4,5]
All you need to do is add:
html {
overflow-y: scroll;
}
In your css file as this will have the scroller whether it is needed or not though you just won't be able to scroll
This means that the viewport will have the same width for both
One way might be;
<select name="listbox" id="listbox">
@foreach (var item in Model)
{
<option value="@item.UserRoleId">
@item.UserRole
</option>
}
</select>
(1) This just happened to me, and I thought it was interesting how it happened. Basically I had copied the folder to a new location and modified it, forgetting that it would bring along all the hidden .svn directories. Once you realize how it happens it is easier to avoid in the future.
(2) Removing the .svn directories is the solution, but you have to do it recursively all the way down the directory tree. The easiest way to do that is:
find troublesome_folder -name .svn -exec rm -rf {} \;
self
is an object reference to the object itself, therefore, they are same.
Python methods are not called in the context of the object itself.
self
in Python may be used to deal with custom object models or something.
That's the S of SOLID: Single responsibility.
A thread embodies the running context (as in execution context: stack frame, thread id, etc.) of the asynchronous execution of a piece of code. That piece of code ideally should be the same implementation, whether synchronous or asynchronous.
If you bundle them together in one implementation, you give the resulting object two unrelated causes of change:
If the language you use supports partial classes or multiple inheritance, then you can segregate each cause in its own super class, but it boils down to the same as composing the two objects, since their feature sets don't overlap. That's for the theory.
In practice, generally speaking, a programme does not need to carry more complexity than necessary. If you have one thread working on a specific task, without ever changing that task, there is probably no point in making the tasks separate classes, and your code remains simpler.
In the context of Java, since the facility is already there, it is probably easier to start directly with stand alone Runnable
classes, and pass their instances to Thread
(or Executor
) instances. Once used to that pattern, it is not harder to use (or even read) than the simple runnable thread case.
Open Android studio->Tools menu->Android-> Android Device Monitor->Emulator Tab->Location control-> Set your required latitude and longitude and check your project as per your need
select 'abcd' + ltrim(str(1)) + ltrim(str(2))
You can do something like this, without using any external libraries.
const fs = require("fs");
const https = require("https");
const file = fs.createWriteStream("data.txt");
https.get("https://www.w3.org/TR/PNG/iso_8859-1.txt", response => {
var stream = response.pipe(file);
stream.on("finish", function() {
console.log("done");
});
});
>>> class A(object): pass
>>> e = A()
>>> e
<__main__.A object at 0xb6d464ec>
>>> print type(e)
<class '__main__.A'>
>>> print type(e).__name__
A
>>>
what do you mean by convert into a string? you can define your own repr and str_ methods:
>>> class A(object):
def __repr__(self):
return 'hei, i am A or B or whatever'
>>> e = A()
>>> e
hei, i am A or B or whatever
>>> str(e)
hei, i am A or B or whatever
or i dont know..please add explainations ;)
To match either / or end of content, use (/|\z)
This only applies if you are not using multi-line matching (i.e. you're matching a single URL, not a newline-delimited list of URLs).
To put that with an updated version of what you had:
/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|\z)
Note that I've changed the start to be a non-greedy match for non-whitespace ( \S+?
) rather than matching anything and everything ( .*
)
The two top answers here suggest:
df.groupby(cols).agg(lambda x:x.value_counts().index[0])
or, preferably
df.groupby(cols).agg(pd.Series.mode)
However both of these fail in simple edge cases, as demonstrated here:
df = pd.DataFrame({
'client_id':['A', 'A', 'A', 'A', 'B', 'B', 'B', 'C'],
'date':['2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01'],
'location':['NY', 'NY', 'LA', 'LA', 'DC', 'DC', 'LA', np.NaN]
})
The first:
df.groupby(['client_id', 'date']).agg(lambda x:x.value_counts().index[0])
yields IndexError
(because of the empty Series returned by group C
). The second:
df.groupby(['client_id', 'date']).agg(pd.Series.mode)
returns ValueError: Function does not reduce
, since the first group returns a list of two (since there are two modes). (As documented here, if the first group returned a single mode this would work!)
Two possible solutions for this case are:
import scipy
x.groupby(['client_id', 'date']).agg(lambda x: scipy.stats.mode(x)[0])
And the solution given to me by cs95 in the comments here:
def foo(x):
m = pd.Series.mode(x);
return m.values[0] if not m.empty else np.nan
df.groupby(['client_id', 'date']).agg(foo)
However, all of these are slow and not suited for large datasets. A solution I ended up using which a) can deal with these cases and b) is much, much faster, is a lightly modified version of abw33's answer (which should be higher):
def get_mode_per_column(dataframe, group_cols, col):
return (dataframe.fillna(-1) # NaN placeholder to keep group
.groupby(group_cols + [col])
.size()
.to_frame('count')
.reset_index()
.sort_values('count', ascending=False)
.drop_duplicates(subset=group_cols)
.drop(columns=['count'])
.sort_values(group_cols)
.replace(-1, np.NaN)) # restore NaNs
group_cols = ['client_id', 'date']
non_grp_cols = list(set(df).difference(group_cols))
output_df = get_mode_per_column(df, group_cols, non_grp_cols[0]).set_index(group_cols)
for col in non_grp_cols[1:]:
output_df[col] = get_mode_per_column(df, group_cols, col)[col].values
Essentially, the method works on one col at a time and outputs a df, so instead of concat
, which is intensive, you treat the first as a df, and then iteratively add the output array (values.flatten()
) as a column in the df.
Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.
If you make Dict
into an object, this will work:
var dict = {};
var addPair = function (myKey, myValue) {
dict[myKey] = myValue;
};
var giveValue = function (myKey) {
return dict[myKey];
};
The myKey
variable is already a string, so you don't need more quotes.
Insead of calling sed with sed
, I do ./bin/sed
And this is the wrapper script in my ~/project/bin/sed
#!/bin/bash
if [[ "$OSTYPE" == "darwin"* ]]; then
exec "gsed" "$@"
else
exec "sed" "$@"
fi
Don't forget to chmod 755
the wrapper script.
The official package for behaviors is Microsoft.Xaml.Behaviors.Wpf
.
It used to be in the Blend SDK (deprecated).
See Jan's answer for more details if you need to migrate.
It's related about revert origin : to set origin when the object is drag : just use $(this).data("draggable").originalPosition = {top:0, left:0};
For example : i use like this
drag: function() {
var t = $(this);
left = parseInt(t.css("left")) * -1;
if(left > 0 ){
left = 0;
t.draggable( "option", "revert", true );
$(this).data("draggable").originalPosition = {top:0, left:0};
}
else t.draggable( "option", "revert", false );
$(".slider-work").css("left", left);
}
The advantage of Java 1.8 forEach method over 1.7 Enhanced for loop is that while writing code you can focus on business logic only.
forEach method takes java.util.function.Consumer object as an argument, so It helps in having our business logic at a separate location that you can reuse it anytime.
Have look at below snippet,
Here I have created new Class that will override accept class method from Consumer Class, where you can add additional functionility, More than Iteration..!!!!!!
class MyConsumer implements Consumer<Integer>{
@Override
public void accept(Integer o) {
System.out.println("Here you can also add your business logic that will work with Iteration and you can reuse it."+o);
}
}
public class ForEachConsumer {
public static void main(String[] args) {
// Creating simple ArrayList.
ArrayList<Integer> aList = new ArrayList<>();
for(int i=1;i<=10;i++) aList.add(i);
//Calling forEach with customized Iterator.
MyConsumer consumer = new MyConsumer();
aList.forEach(consumer);
// Using Lambda Expression for Consumer. (Functional Interface)
Consumer<Integer> lambda = (Integer o) ->{
System.out.println("Using Lambda Expression to iterate and do something else(BI).. "+o);
};
aList.forEach(lambda);
// Using Anonymous Inner Class.
aList.forEach(new Consumer<Integer>(){
@Override
public void accept(Integer o) {
System.out.println("Calling with Anonymous Inner Class "+o);
}
});
}
}
I prefer Python 3.x way.
cal = 123.4567
print(f"result {cal:.4E}")
4
indicates how many digits are shown shown in the floating part.
cal = 123.4567
totalDigitInFloatingPArt = 4
print(f"result {cal:.{totalDigitInFloatingPArt}E} ")
typedef void (Dog::*memfun)();
memfun doSomething = &Dog::bark;
....
(pDog->*doSomething)(); // if pDog is a pointer
// (pDog.*doSomething)(); // if pDog is a reference
I had this problem on Safari (iOS 10.3.3) - the browser was not redrawing until the touchend event fired. Fixed elements did not appear or were cut off.
The trick for me was adding transform: translate3d(0,0,0); to my fixed position element.
.fixed-position-on-mobile {
position: fixed;
transform: translate3d(0,0,0);
}
EDIT - I now know why the transform fixes the issue: hardware-acceleration. Adding the 3D transformation triggers the GPU acceleration making for a smooth transition. For more on hardware-acceleration checkout this article: http://blog.teamtreehouse.com/increase-your-sites-performance-with-hardware-accelerated-css.
I'd use recursion just in case so you can deep copy the map
and avoid bad surprises in case you were to change a map
element that is a map
itself.
Here's an example in a utils.go:
package utils
func CopyMap(m map[string]interface{}) map[string]interface{} {
cp := make(map[string]interface{})
for k, v := range m {
vm, ok := v.(map[string]interface{})
if ok {
cp[k] = CopyMap(vm)
} else {
cp[k] = v
}
}
return cp
}
And its test file (i.e. utils_test.go):
package utils
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestCopyMap(t *testing.T) {
m1 := map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
}
m2 := CopyMap(m1)
m1["a"] = "zzz"
delete(m1, "b")
require.Equal(t, map[string]interface{}{"a": "zzz"}, m1)
require.Equal(t, map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
}, m2)
}
It should easy enough to adapt if you need the map
key to be something else instead of a string
.
employees.ToList().Foreach(u=> { u.SomeProperty = null; u.OtherProperty = null; });
Notice that I used semicolons after each set statement
that is -->
u.SomeProperty = null;
u.OtherProperty = null;
I hope this will definitely solve your problem.
unset
is not actually a function, but a language construct. It is no more a function call than a return
or an include
.
Aside from performance issues, using unset
makes your code's intent much clearer.
Don't mess with the visibility flags of the container - FragmentTransaction.hide/show does that internally for you.
So the correct way to do this is:
FragmentManager fm = getFragmentManager();
fm.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.show(somefrag)
.commit();
OR if you are using android.support.v4.app.Fragment
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.show(somefrag)
.commit();
For jQuery 1.9+ as Dunstkreis mentioned .data('events') was removed. But you can use another hack (it is not recommended to use undocumented possibilities) $._data($(this).get(0), 'events') instead and solution provided by anurag will look like:
$.fn.bindFirst = function(name, fn) {
this.bind(name, fn);
var handlers = $._data($(this).get(0), 'events')[name.split('.')[0]];
var handler = handlers.pop();
handlers.splice(0, 0, handler);
};
This should work:
public static final byte[] intToByteArray(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
}
Code taken from here.
Edit An even simpler solution is given in this thread.
You can use hasOwnProperty()
as well as in
operator.
For variable argument functions like printf
and scanf
, the arguments are promoted, for example, any smaller integer types are promoted to int
, float
is promoted to double
.
scanf
takes parameters of pointers, so the promotion rule takes no effect. It must use %f
for float*
and %lf
for double*
.
printf
will never see a float
argument, float
is always promoted to double
. The format specifier is %f
. But C99 also says %lf
is the same as %f
in printf
:
C99 §7.19.6.1 The
fprintf
function
l
(ell) Specifies that a followingd
,i
,o
,u
,x
, orX
conversion specifier applies to along int
orunsigned long int
argument; that a followingn
conversion specifier applies to a pointer to along int
argument; that a followingc
conversion specifier applies to awint_t
argument; that a followings
conversion specifier applies to a pointer to awchar_t
argument; or has no effect on a followinga
,A
,e
,E
,f
,F
,g
, orG
conversion specifier.
I cannot comment on @Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.
Use it like:
var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]
Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().
You could descendingly order the tabele by id and limit the number of results to one:
SELECT id FROM tablename ORDER BY id DESC LIMIT 1
BUT: ORDER BY
rearranges the entire table for this request. So if you have a lot of data and you need to repeat this operation several times, I would not recommend this solution.
I have generated 100 different colors of different contrast, and you can increase values according to your need:
Example on Feedle: http://jsfiddle.net/zFbfE/29/ -
// CHANGE THE INITIAL SEED HERE
Math.seed = 23;
/**
* Math.seededRandom()
*
*/
Math.seededRandom = function(max, min) {
max = max || 1;
min = min || 0;
Math.seed = (Math.seed * 9301 + 49297) % 233280;
var rnd = Math.seed / 233280.0;
return min + rnd * (max - min);
}
var c, r = 0,
l = 100000,
t,
random = [],
seededRandom = [];
for(var i=0; i<100; i++)
{
random[i] = 0;
seededRandom[i] = 0;
}
// Do some loops withouth benchmarking
// to have a "fair" comparison
/*for (c = 0; c < l; ++c) {
r = 5+5;
}*/
// benchmark Math.random()
t = new Date().getTime();
s = '';
// benchmark Math.seededRandom()
t = new Date().getTime();
while(l--){
r = Math.seededRandom();
seededRandom[(r*100)|0] += 1;
}
var inc = 0;
for(c=0; c<seededRandom.length; c++) {
//var inc=15;
for(var i=0; i<seededRandom.length; i++)
{
if(i!==c) {
if(seededRandom[c] == seededRandom[i]) {
seededRandom[c] += inc;
inc = inc + 10;
// console.log(seededRandom[c]);
}
}
}
inc = inc > 255 ? 0 : inc;
}
var a=[], b=[], d=[], inc=0, dec=255;
for(c=0; c<seededRandom.length; c++) {
a[c] = (seededRandom[c] % 100) + inc;
b[c] = dec - Math.floor(seededRandom[c]/100);
if(b[c] < 0)
b[c] = b[c]* - 1;
if(a[c] > 255)
a[c] -= 255;
d[c] = Math.floor(b[c]/2);
inc += 5;
dec -= 5;
}
var app = angular.module("myAppp", []).controller('myCtrl',function($scope, $http) {
$scope.id = [];
for(var i=0; i<seededRandom.length; i++)
$scope.id.push(i);
// Generate random number
$scope.Icon = [];$scope.Icon2 = [], $scope.Icon3 = [];
var ran = 0, inc = 5, dec = 255;
for(var i=0;i<seededRandom.length;i++)
{
$scope.Icon.push(a[i]%100);
$scope.Icon2.push(b[i]%100);
$scope.Icon3.push(d[i]%100);
console.log(a[i] + "|" + b[i] + "|" + d[i]);
}
});
It works for me and I think it would be helpful for you also.
One best thing in this example is, it will generate 100 random colors and colors would be same on every page load.
If you need to convert the dictionary to binary, you need to convert it to a string (JSON) as described in the previous answer, then you can convert it to binary.
For example:
my_dict = {'key' : [1,2,3]}
import json
def dict_to_binary(the_dict):
str = json.dumps(the_dict)
binary = ' '.join(format(ord(letter), 'b') for letter in str)
return binary
def binary_to_dict(the_binary):
jsn = ''.join(chr(int(x, 2)) for x in the_binary.split())
d = json.loads(jsn)
return d
bin = dict_to_binary(my_dict)
print bin
dct = binary_to_dict(bin)
print dct
will give the output
1111011 100010 1101011 100010 111010 100000 1011011 110001 101100 100000 110010 101100 100000 110011 1011101 1111101
{u'key': [1, 2, 3]}
To get the number of votes for a specific item, you would use:
vote_count = Item.objects.filter(votes__contest=contestA).count()
If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:
contest = Contest.objects.get(pk=contest_id)
votes = contest.votes_set.select_related()
vote_counts = {}
for vote in votes:
if not vote_counts.has_key(vote.item.id):
vote_counts[vote.item.id] = {
'item': vote.item,
'count': 0
}
vote_counts[vote.item.id]['count'] += 1
This will create dictionary that maps items to number of votes. Not the only way to do this, but it's pretty light on database hits, so will run pretty quickly.
Simply - code will run fine if many threads are executing this code at the same time.
Here is a heavy tutorial that has good stuff in it to pick out:
http://mobile.tutsplus.com/tutorials/mobile-web-apps/jquery_android/
use below statement if safe_mode
is off
set_time_limit(0);
Had a good look at many of these supposed answers...
...and bupkis after scouring Stack Overflow as well as other sites for a regex that matches any string with no starting or trailing white-space and only a single space between strictly alpha character words.
^[a-zA-Z]+[(?<=\d\s]([a-zA-Z]+\s)*[a-zA-Z]+$
Thus easily modified to alphanumeric:
^[a-zA-Z0-9]+[(?<=\d\s]([a-zA-Z0-9]+\s)*[a-zA-Z0-9]+$
(This does not match single words but just use a switch/if-else with a simple ^[a-zA-Z0-9]+$
if you need to catch single words in addition.)
enjoy :D
try this it worked for me in ie 7 and ie 8
$(this).click(function (j) {
var href = ($(this).attr('href'));
window.location = href;
return true;
I'm using this:
if(count($array)==count(array_count_values($array))){
echo("all values are unique");
}else{
echo("there's dupe values");
}
I don't know if it's the fastest but works pretty good so far
As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.
There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.
Here's a Python 3 example:
class C(abc.ABC):
@abc.abstractmethod
def my_abstract_method(self, ...):
...
When instantiating C
, you'll get an error because my_abstract_method
is abstract. You need to implement it in a child class.
TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method
Subclass C
and implement my_abstract_method
.
class D(C):
def my_abstract_method(self, ...):
...
Now you can instantiate D
.
C.my_abstract_method
does not have to be empty. It can be called from D
using super()
.
An advantage of this over NotImplementedError
is that you get an explicit Exception
at instantiation time, not at method call time.
right click on the pivot table in excel choose wizard click 'back' click 'get data...' in the query window File - Table Definition
then you can create a new or choose a different connection
I created a button...
This is where you've gone wrong. You haven't created a button, you've created an anchor element. If you had used a button
element instead, you wouldn't have this problem:
<button type="button" data-toggle="modal" data-target="#myModal" data-role="disabled">
Connect
</button>
If you are going to continue using an a
element instead, at the very least you should give it a role
attribute set to "button"
and drop the href
attribute altogether:
<a role="button" ...>
Once you've done that you can introduce a piece of JavaScript which calls event.preventDefault()
- here with event
being your click event.
You either want to select an anonymous type:
var dataset2 = from recordset
in entities.processlists
where recordset.ProcessName == processname
select new
{
recordset.ServerName,
recordset.ProcessID,
recordset.Username
};
But you cannot cast that to another type, so I guess you want something like this:
var dataset2 = from recordset
in entities.processlists
where recordset.ProcessName == processname
// Select new concrete type
select new PInfo
{
ServerName = recordset.ServerName,
ProcessID = recordset.ProcessID,
Username = recordset.Username
};
There's also oct2py which can call .m files within python
https://pypi.python.org/pypi/oct2py
It requires GNU Octave, which is highly compatible with MATLAB.
I spent a lot of time and tried a lot of different solutions - in the end I did it this way :
<html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/swagger-ui.css">
<script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
<script>
function render() {
var ui = SwaggerUIBundle({
url: `path/to/my/swagger.yaml`,
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
]
});
}
</script>
</head>
<body onload="render()">
<div id="swagger-ui"></div>
</body>
</html>
You just need to have path/to/my/swagger.yaml served from the same location.
(or use CORS headers)
To keep a list of files, one can use:
rm(list=setdiff(ls(), c("df1", "df2")))
npm start --mode production
npm start --mode development
With process.env.NODE_ENV = 'production'
You are apparently using Django.
You are probably better off just using models.IntegerField()
instead of models.TextField()
. Not only will it do the check for you, but it will give you the error message translated in several langs, and it will cast the value from it's type in the database to the type in your Python code transparently.
I was having the same issue. So I went to the Java options through Control Panel. Copied the web address that I was having an issue with to the exceptions and it was fixed.
style="padding-top: 8px"
Use this to shift your div up or down in your row. Works wonders for me.
Without For loop:
Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))
newColumn.DefaultValue = "Your DropDownList value"
table.Columns.Add(newColumn)
C#:
System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);
Try BufferedReader.readLine()
instead of all this complication. It will recognize all possible line terminators.
In c++11, you can use std::regex_replace
:
#include <string>
#include <regex>
std::string test = "abc def abc def";
test = std::regex_replace(test, std::regex("def"), "klm");
The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.
import numpy as np
names = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 , 0.5678 , 0.9123 ])
ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats
np.savetxt('test.txt', ab, fmt="%10s %10.3f")
Update: This example also works properly in Python 3 by using the 'U6'
Unicode string dtype, when creating the ab
structured array, instead of the 'S6'
byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1'
in Python 3.
I've got solved my problem this way in EF on list of records from db
ListOfObjectToBeOrder.OrderBy(x => x.columnName).ToList();
Git 2.9.x/2.10 (Q3 2016) adds another debug option: GIT_TRACE_CURL
.
See commit 73e57aa, commit 74c682d (23 May 2016) by Elia Pinto (devzero2000
).
Helped-by: Torsten Bögershausen (tboegi
), Ramsay Jones , Junio C Hamano (gitster
), Eric Sunshine (sunshineco
), and Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 2f84df2, 06 Jul 2016)
http.c
: implement theGIT_TRACE_CURL
environment variableImplement the
GIT_TRACE_CURL
environment variable to allow a greater degree of detail ofGIT_CURL_VERBOSE
, in particular the complete transport header and all the data payload exchanged.
It might be useful if a particular situation could require a more thorough debugging analysis.
The documentation will state:
GIT_TRACE_CURL
Enables a curl full trace dump of all incoming and outgoing data, including descriptive information, of the git transport protocol.
This is similar to doingcurl --trace-ascii
on the command line.This option overrides setting the
GIT_CURL_VERBOSE
environment variable.
You can see that new option used in this answer, but also in the Git 2.11 (Q4 2016) tests:
See commit 14e2411, commit 81590bf, commit 4527aa1, commit 4eee6c6 (07 Sep 2016) by Elia Pinto (devzero2000
).
(Merged by Junio C Hamano -- gitster
-- in commit 930b67e, 12 Sep 2016)
Use the new
GIT_TRACE_CURL
environment variable instead of the deprecatedGIT_CURL_VERBOSE
.
GIT_TRACE_CURL=true git clone --quiet $HTTPD_URL/smart/repo.git
The problem is that you are using SingleOrDefault
. This method will only succeed when the collections contains exactly 0 or 1 element. I believe you are looking for FirstOrDefault
which will succeed no matter how many elements are in the collection.
You cannot calculate the differences separately ... what difference would that yield for 7:59 and 8:00 o'clock? Try
import time
time.time()
which gives you the seconds since the start of the epoch.
You can then get the intermediate time with something like
timestamp1 = time.time()
# Your code here
timestamp2 = time.time()
print "This took %.2f seconds" % (timestamp2 - timestamp1)
If it's just for passing values between pages and you only require it for the one request. Use Context.
Context
The Context object holds data for a single user, for a single request, and it is only persisted for the duration of the request. The Context container can hold large amounts of data, but typically it is used to hold small pieces of data because it is often implemented for every request through a handler in the global.asax. The Context container (accessible from the Page object or using System.Web.HttpContext.Current) is provided to hold values that need to be passed between different HttpModules and HttpHandlers. It can also be used to hold information that is relevant for an entire request. For example, the IBuySpy portal stuffs some configuration information into this container during the Application_BeginRequest event handler in the global.asax. Note that this only applies during the current request; if you need something that will still be around for the next request, consider using ViewState. Setting and getting data from the Context collection uses syntax identical to what you have already seen with other collection objects, like the Application, Session, and Cache. Two simple examples are shown here:
// Add item to
Context Context.Items["myKey"] = myValue;
// Read an item from the
Context Response.Write(Context["myKey"]);
http://msdn.microsoft.com/en-us/magazine/cc300437.aspx#S6
Using the above. If you then do a Server.Transfer
the data you've saved in the context will now be available to the next page. You don't have to concern yourself with removing/tidying up this data as it is only scoped to the current request.
!members.find()
I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:
def lst1 = []
assert !lst1.find()
def lst2 = [null]
assert !lst2.find()
def lst3 = [null,2,null]
assert lst3.find()
def lst4 = [null,null,null]
assert !lst4.find()
def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42
def lst6 = null;
assert !lst6.find()
Not to repeat what everyone already have said but keep the following cheat sheet handly for File manipulations:
System.IO.File.ReadAllBytes(filename);
File.Exists(filename)
Path.Combine(folderName, resOfThePath);
Path.GetFullPath(path); // converts a relative path to absolute one
Path.GetExtension(path);
When you say 2^8
you get 256
, but the numbers in computers terms begins from the number 0
. So, then you got the 255
, you can probe it in a internet mask for the IP or in the IP itself.
255
is the maximum value of a 8 bit integer : 11111111 = 255
Does that help?
@bku_drytt's solution didn't do it for me.
I solved it by additionally changing every occurence of 14.0
to 12.0
and v140
to v120
manually in the .vcxproj files.
Then it compiled!
Following @patrick-desjardins answer, I implemented abstract and it's implementation class along with @Test
as follows:
Abstract class - ABC.java
import java.util.ArrayList;
import java.util.List;
public abstract class ABC {
abstract String sayHello();
public List<String> getList() {
final List<String> defaultList = new ArrayList<>();
defaultList.add("abstract class");
return defaultList;
}
}
As Abstract classes cannot be instantiated, but they can be subclassed, concrete class DEF.java, is as follows:
public class DEF extends ABC {
@Override
public String sayHello() {
return "Hello!";
}
}
@Test class to test both abstract as well as non-abstract method:
import org.junit.Before;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.contains;
import java.util.Collection;
import java.util.List;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Test;
public class DEFTest {
private DEF def;
@Before
public void setup() {
def = new DEF();
}
@Test
public void add(){
String result = def.sayHello();
assertThat(result, is(equalTo("Hello!")));
}
@Test
public void getList(){
List<String> result = def.getList();
assertThat((Collection<String>) result, is(not(empty())));
assertThat(result, contains("abstract class"));
}
}
See Android arsenal (category Graphics) for more libraries.
Here's a slightly updated version of Chris Herring's solution, taking into account that you can use innerHTML
as well instead of a creating a new text node:
function insertCss( code ) {
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
// IE
style.styleSheet.cssText = code;
} else {
// Other browsers
style.innerHTML = code;
}
document.getElementsByTagName("head")[0].appendChild( style );
}
You might also consider adding "
.
For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus"
is very good idea.
<div style="display: inline">Is this what you meant?</div>
You can try also using below script
<html>
<head>
<script>
function load()
{
document.frm1.submit()
}
</script>
</head>
<body onload="load()">
<form action="http://www.google.com" id="frm1" name="frm1">
<input type="text" value="" />
</form>
</body>
</html>
*{font-family:Algerian;}
better solution below Applying a single font to an entire website with CSS
para resolver o meu problema, eu apenas adicionei na minha MainActivity ("Theme = To solve my problem, I just added it in my MainActivity ("Theme =" @ style / MyTheme "") where MyTheme is the name of my theme
[Activity(Label = "Name Label", MainLauncher = true, Icon = "@drawable/icon", LaunchMode = LaunchMode.SingleTop, Theme = "@style/MyTheme")]
In the first case you are simply starting a new thread while in the second case you are entering in the thread pool.
The thread pool job is to share and recycle threads. It allows to avoid losing a few millisecond every time we need to create a new thread.
There are a several ways to enter the thread pool:
I have wrote this function to check both methods using old window.performance.navigation
and new performance.getEntriesByType("navigation")
in same time:
function navigationType(){
var result;
var p;
if (window.performance.navigation) {
result=window.performance.navigation;
if (result==255){result=4} // 4 is my invention!
}
if (window.performance.getEntriesByType("navigation")){
p=window.performance.getEntriesByType("navigation")[0].type;
if (p=='navigate'){result=0}
if (p=='reload'){result=1}
if (p=='back_forward'){result=2}
if (p=='prerender'){result=3} //3 is my invention!
}
return result;
}
Result description:
0: clicking a link, Entering the URL in the browser's address bar, form submission, Clicking bookmark, initializing through a script operation.
1: Clicking the Reload button or using Location.reload()
2: Working with browswer history (Bakc and Forward).
3: prerendering activity like <link rel="prerender" href="//example.com/next-page.html">
4: any other method.
In C#, float
is an alias for System.Single
(a bit like int
is an alias for System.Int32
).
wget
wget
is a linux command, not a PHP command, so to run this you woud need to use exec
, which is a PHP command for executing shell commands.
exec("wget --http-user=[user] --http-password=[pass] http://www.example.com/file.xml");
This can be useful if you are downloading a large file - and would like to monitor the progress, however when working with pages in which you are just interested in the content, there are simple functions for doing just that.
The exec
function is enabled by default, but may be disabled in some situations. The configuration options for this reside in your php.ini
, to enable, remove exec
from the disabled_functions
config string.
alternative
Using file_get_contents
we can retrieve the contents of the specified URL/URI. When you just need to read the file into a variable, this would be the perfect function to use as a replacement for curl - follow the URI syntax when building your URL.
// standard url
$content = file_get_contents("http://www.example.com/file.xml");
// or with basic auth
$content = file_get_contents("http://user:[email protected]/file.xml");
As noted by Sean the Bean
- you may also need to change allow_url_fopen
to true
in your php.ini to allow the use of a URL in this method, however, this should be true by default.
If you want to then store that file locally, there is a function file_put_contents
to write that into a file, combined with the previous, this could emulate a file download:
file_put_contents("local_file.xml", $content);
While writing a monitoring tool, i took a slightly different approach.
It felt a bit wasteful to spin up an extra thread just to use WaitForSingleObject or even the RegisterWaitForSingleObject (which does that for you). Since in my case i don't need to know the exact instant a process has closed, just that it indeed HAS closed.
I'm using the GetProcessTimes() instead:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx
GetProcessTimes() will return a FILETIME struct for the process's ExitTime only if the process has actually exited. So is just a matter of checking if the ExitTime struct is populated and if the time isn't 0;
This solution SHOULD account the case where a process has been killed but it's PID was reused by another process. GetProcessTimes needs a handle to the process, not the PID. So the OS should know that the handle is to a process that was running at some point, but not any more, and give you the exit time.
Relying on the ExitCode felt dirty :/
Here's an example of how to solve the same problem without having to map the fields manually:
from sqlalchemy import Column, ForeignKey, Integer, String, Date, DateTime, text, create_engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.attributes import InstrumentedAttribute
engine = create_engine('postgres://postgres@localhost:5432/database')
session = sessionmaker()
session.configure(bind=engine)
Base = declarative_base()
class Media(Base):
__tablename__ = 'media'
id = Column(Integer, primary_key=True)
title = Column(String, nullable=False)
slug = Column(String, nullable=False)
type = Column(String, nullable=False)
def update(self):
s = session()
mapped_values = {}
for item in Media.__dict__.iteritems():
field_name = item[0]
field_type = item[1]
is_column = isinstance(field_type, InstrumentedAttribute)
if is_column:
mapped_values[field_name] = getattr(self, field_name)
s.query(Media).filter(Media.id == self.id).update(mapped_values)
s.commit()
So to update a Media instance, you can do something like this:
media = Media(id=123, title="Titular Line", slug="titular-line", type="movie")
media.update()
Check if you are using any sort of jquery/javascript validation on the page and try disabling it and see what happens. You can use your browser's developer tools to see if any javascript file with validate or validation is being loaded. You can also look for hidden form elements (ie. style set to display:none; or something like that) and make sure there isn't a hidden validation error on those that's not being rendered.
The "ojdbc.jar" is not in the CLASSPATH
of your application server.
Just tell us which application server it is and we will tell you where the driver should be placed.
Edit: I saw the tag jboss so it has to be placed in folder "$JBOSS_HOME/server/default/lib/"
The answers by cval and Priyank Patel work great. However, be aware that some values could be unicode strings and therefore may cause the str
to throw a UnicodeEncodeError
error. In that case, replace the function str
by the function unicode
.
For example, assume the string Libië (Dutch for Libya), represented in Python as the unicode string u'Libi\xeb'
:
print str(u'Libi\xeb')
throws the following error:
Traceback (most recent call last):
File "/Users/tomasz/Python/MA-CIW-Scriptie/RecreateTweets.py", line 21, in <module>
print str(u'Libi\xeb')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in position 4: ordinal not in range(128)
The following line, however, will not throw an error:
print unicode(u'Libi\xeb') # prints Libië
So, replace:
values = ','.join([str(i) for i in value_list])
by
values = ','.join([unicode(i) for i in value_list])
to be safe.
Download the jar file from here
now put it into your libs folder, right click it and select 'Add as library'
now in main.xml put this code
<com.devsmart.android.ui.HorizontalListView
android:id="@+id/hlistview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
now in Activity class if you want Horizontal Listview with images then put this code
HorizontalListView hListView = (HorizontalListView) findViewById(R.id.hlistview);
hListView.setAdapter(new HAdapter(this));
private class HAdapter extends BaseAdapter {
LayoutInflater inflater;
public HAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return Const.template.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listinflate, null);
holder = new HViewHolder();
convertView.setTag(holder);
} else {
holder = (HViewHolder) convertView.getTag();
}
holder.img = (ImageView) convertView.findViewById(R.id.image);
holder.img.setImageResource(Const.template[position]);
return convertView;
}
}
class HViewHolder {
ImageView img;
}
Take a form-control
, and add is-valid
to its class. Notice how the control turns green, but more importantly, notice the checkmark icon on the right of the control? This is what we want!
Example:
.my-icon {_x000D_
padding-right: calc(1.5em + .75rem);_x000D_
background-image: url('https://use.fontawesome.com/releases/v5.8.2/svgs/regular/calendar-alt.svg');_x000D_
background-repeat: no-repeat;_x000D_
background-position: center right calc(.375em + .1875rem);_x000D_
background-size: calc(.75em + .375rem) calc(.75em + .375rem);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
<div class="container">_x000D_
<div class="col-md-5">_x000D_
<input type="text" id="date" class="form-control my-icon" placeholder="Select...">_x000D_
</div>_x000D_
</div>
_x000D_
You should set the android:exported attribute of the service to "true", in order to allow other components to invoke it. In the AndroidManifest.xml file, add the following attribute:
<service android:exported="true" ></service>
Then, you should be able to start the service via adb:
adb shell am startservice com.package.name/.YourServiceName
For more info about the android:exported attribute see this page.
Use this, modified from https://stephenhaunts.com/2014/09/25/remove-the-close-button-from-a-wpf-window :
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
namespace Whatever
{
public partial class MainMenu : Window
{
private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x00080000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLongPtr(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
public MainMenu()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Window_Loaded);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLongPtr(hwnd, GWL_STYLE, GetWindowLongPtr(hwnd, GWL_STYLE) & ~WS_SYSMENU);
}
}
}
Jquery Datepicker defaultDate ONLY set the default date that you chose on the calendar that pops up when you click on your field. If you want the default date to APPEAR on your input before the user clicks on the field you should give a val() to your field. Something like this:
$("#searchDateFrom").datepicker({ defaultDate: "-1y -1m -6d" });
$("#searchDateFrom").val((date.getMonth()) + '/' + (date.getDate() - 6) + '/' + (date.getFullYear() - 1));
These answers are right, but old and works for Depoloyement Package Model
.
What I Actually needed is to change the server name, database name of a connection manager and i found this very helpful:
https://www.youtube.com/watch?v=_yLAwTHH_GA
Better for people using SQL Server 2012-2014-2016 ... with Deployment Project Model
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(function() {
//here you have the control over the body of the iframe document
var iBody = $("#iView").contents().find("body");
//here you have the control over any element (#myContent)
var myContent = iBody.find("#myContent");
});
</script>
</head>
<body>
<iframe src="mifile.html" id="iView" style="width:200px;height:70px;border:dotted 1px red" frameborder="0"></iframe>
</body>
</html>
For a simple use of slice
, use my extension to Array Class:
Array.prototype.subarray = function(start, end) {
if (!end) { end = -1; }
return this.slice(start, this.length + 1 - (end * -1));
};
Then:
var bigArr = ["a", "b", "c", "fd", "ze"];
Test1:
bigArr.subarray(1, -1);
< ["b", "c", "fd", "ze"]
Test2:
bigArr.subarray(2, -2);
< ["c", "fd"]
Test3:
bigArr.subarray(2);
< ["c", "fd","ze"]
Might be easier for developers coming from another language (i.e. Groovy).
You don't need external library:
Integer[] input = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(input, (a, b) -> b - a); // reverse order
return Arrays.stream(input).mapToInt(Integer::intValue).toArray();
Allows getting any URL on your system, not just a current one.
import org.springframework.hateoas.mvc.ControllerLinkBuilder
...
ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId))
URI methodUri = linkBuilder.Uri()
String methodUrl = methodUri.getPath()
You can add empty line ;
Paragraph p = new Paragraph();
// add one empty line
addEmptyLine(p, 1);
// add 3 empty line
addEmptyLine(p, 3);
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
I had a new VirtualHost configuration file that was not showing when using the apachectl -S
command. After much head scratching I realised that my file did not have suffix ".conf". Once I renamed the file with that suffix my Vhost started showing and working!
Lone time lurker, first time poster...
Expanding on @Devart and @ildanny solutions...
I had the need to run this for ALL tables in a db and also to execute the code against Linked Servers.
All tables...
/*
Ex.
EXEC etl.GetTableDefinitions '{friendlyname}', '{DatabaseName}', 'All', 0, NULL;
EXEC etl.GetTableDefinitions '{friendlyname}', '{DatabaseName}', 'dbo', 0, NULL;
EXEC etl.GetTableDefinitions '{friendlyname}', '{DatabaseName}', 'All', 1, '{linkedservername}';
*/
CREATE PROCEDURE etl.GetTableDefinitions
(
@SystemName NVARCHAR(128)
, @DatabaseName NVARCHAR(128)
, @SchemaName NVARCHAR(128)
, @linkedserver BIT
, @linkedservername NVARCHAR(128)
)
AS
DECLARE @sql NVARCHAR(MAX) = N'';
DECLARE @sql1 NVARCHAR(MAX) = N'';
DECLARE @inSchemaName NVARCHAR(MAX) = N'';
SELECT @inSchemaName = CASE WHEN @SchemaName = N'All' THEN N's.[name]' ELSE '''' + @SchemaName + '''' END;
IF @linkedserver = 0
BEGIN
SELECT @sql = N'
SET NOCOUNT ON;
--- options ---
DECLARE @UseTransaction BIT = 0;
DECLARE @GenerateUseDatabase BIT = 0;
DECLARE @GenerateFKs BIT = 0;
DECLARE @GenerateIdentity BIT = 1;
DECLARE @GenerateCollation BIT = 0;
DECLARE @GenerateCreateTable BIT = 1;
DECLARE @GenerateIndexes BIT = 0;
DECLARE @GenerateConstraints BIT = 1;
DECLARE @GenerateKeyConstraints BIT = 1;
DECLARE @GenerateConstraintNameOfDefaults BIT = 1;
DECLARE @GenerateDropIfItExists BIT = 0;
DECLARE @GenerateDropFKIfItExists BIT = 0;
DECLARE @GenerateDelete BIT = 0;
DECLARE @GenerateInsertInto BIT = 0;
DECLARE @GenerateIdentityInsert INT = 0; --0 ignore set,but add column; 1 generate; 2 ignore set AND column
DECLARE @GenerateSetNoCount INT = 0; --0 ignore set,1=set on, 2=set off
DECLARE @GenerateMessages BIT = 0; --print with no wait
DECLARE @GenerateDataCompressionOptions BIT = 0; --TODO: generates the compression option only of the TABLE, not the indexes
--NB: the compression options reflects the design VALUE.
--The actual compression of a the page is saved here
--- variables ---
DECLARE @DataTypeSpacer INT = 1; --this is just to improve the formatting of the script ...
DECLARE @name SYSNAME;
DECLARE @sql NVARCHAR(MAX) = N'''';
DECLARE @int INT = 1;
DECLARE @maxint INT;
DECLARE @SourceDatabase NVARCHAR(MAX) = N''' + @DatabaseName + '''; --this is used by the INSERT
DECLARE @TargetDatabase NVARCHAR(MAX) = N''' + @DatabaseName + '''; --this is used by the INSERT AND USE <DBName>
DECLARE @cr NVARCHAR(20) = NCHAR(13);
DECLARE @tab NVARCHAR(20) = NCHAR(9);
DECLARE @Tables TABLE
(
id INT IDENTITY(1,1)
, [name] SYSNAME
, [object_id] INT
, [database_id] SMALLINT
);
BEGIN
INSERT INTO @Tables([name], [object_id], [database_id])
SELECT s.[name] + N''.'' + t.[name] AS [name]
, t.[object_id]
, DB_ID(''' + @DatabaseName + ''') AS [database_id]
FROM [' + @DatabaseName + '].sys.tables t
JOIN [' + @DatabaseName + '].sys.schemas s ON t.[schema_id] = s.[schema_id]
WHERE t.[name] NOT IN (''Tally'',''LOC_AND_SEG_CAP1'',''LOC_AND_SEG_CAP2'',''LOC_AND_SEG_CAP3'',''LOC_AND_SEG_CAP4'',''TableNames'')
AND s.[name] = ' + @inSchemaName + '
ORDER BY s.[name], t.[name];
SELECT @maxint = COUNT(0)
FROM @Tables;
WHILE @int <= @maxint
BEGIN
;WITH
index_column AS
(
SELECT ic.[object_id]
, OBJECT_NAME(ic.[object_id], DB_ID(N''' + @DatabaseName + ''')) AS ObjectName
, ic.index_id
, ic.is_descending_key
, ic.is_included_column
, c.[name]
FROM [' + @DatabaseName + '].sys.index_columns ic WITH (NOLOCK)
JOIN [' + @DatabaseName + '].sys.columns c WITH (NOLOCK) ON ic.[object_id] = c.[object_id]
AND ic.column_id = c.column_id
JOIN [' + @DatabaseName + '].sys.tables t ON c.[object_id] = t.[object_id]
)
, fk_columns AS
(
SELECT k.constraint_object_id
, cname = c.[name]
, rcname = rc.[name]
FROM [' + @DatabaseName + '].sys.foreign_key_columns k WITH (NOWAIT)
JOIN [' + @DatabaseName + '].sys.columns rc WITH (NOWAIT) ON rc.[object_id] = k.referenced_object_id
AND rc.column_id = k.referenced_column_id
JOIN [' + @DatabaseName + '].sys.columns c WITH (NOWAIT) ON c.[object_id] = k.parent_object_id
AND c.column_id = k.parent_column_id
JOIN [' + @DatabaseName + '].sys.tables t ON c.[object_id] = t.[object_id]
WHERE @GenerateFKs = 1
)
SELECT @sql = @sql +
-------------------- USE DATABASE --------------------------------------------------------------------------------------------------
CAST(
CASE WHEN @GenerateUseDatabase = 1
THEN N''USE '' + @TargetDatabase + N'';'' + @cr
ELSE N'''' END
AS NVARCHAR(200))
+
-------------------- SET NOCOUNT --------------------------------------------------------------------------------------------------
CAST(
CASE @GenerateSetNoCount
WHEN 1 THEN N''SET NOCOUNT ON;'' + @cr
WHEN 2 THEN N''SET NOCOUNT OFF;'' + @cr
ELSE N'''' END
AS NVARCHAR(MAX))
+
-------------------- USE TRANSACTION --------------------------------------------------------------------------------------------------
CAST(
CASE WHEN @UseTransaction = 1
THEN
N''SET XACT_ABORT ON'' + @cr
+ N''BEGIN TRY'' + @cr
+ N''BEGIN TRAN'' + @cr
ELSE N'''' END
AS NVARCHAR(MAX))
+
-------------------- DROP SYNONYM --------------------------------------------------------------------------------------------------
CASE WHEN @GenerateDropIfItExists = 1
THEN CAST(N''IF OBJECT_ID('''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''',''''SN'''') IS NOT NULL DROP SYNONYM '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'';'' + @cr AS NVARCHAR(MAX))
ELSE CAST(N'''' AS NVARCHAR(MAX)) END
+
-------------------- DROP TABLE IF EXISTS --------------------------------------------------------------------------------------------------
CASE WHEN @GenerateDropIfItExists = 1
THEN
--Drop TABLE if EXISTS
CAST(N''IF OBJECT_ID('''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''',''''U'''') IS NOT NULL DROP TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'';'' + @cr AS NVARCHAR(MAX))
+ @cr
ELSE N'''' END
+
-------------------- DROP CONSTRAINT IF EXISTS --------------------------------------------------------------------------------------------------
CAST((CASE WHEN @GenerateMessages = 1 AND @GenerateDropFKIfItExists = 1 THEN
N''RAISERROR(''''DROP CONSTRAINTS OF %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + @cr
ELSE N'''' END) AS NVARCHAR(MAX))
+
CASE WHEN @GenerateDropFKIfItExists = 1
THEN
--Drop foreign keys
ISNULL(((
SELECT
CAST(
N''ALTER TABLE '' + QUOTENAME(s.[name]) + N''.'' + QUOTENAME(t.[name]) + N'' DROP CONSTRAINT '' + RTRIM(f.[name]) + N'';'' + @cr
AS NVARCHAR(MAX))
FROM [' + @DatabaseName + '].sys.tables t
INNER JOIN [' + @DatabaseName + '].sys.foreign_keys f ON f.parent_object_id = t.[object_id]
INNER JOIN [' + @DatabaseName + '].sys.schemas s ON s.[schema_id] = f.[schema_id]
WHERE f.referenced_object_id = t.[object_id]
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''))
, N'''') + @cr
ELSE N'''' END
+
--------------------- CREATE TABLE -----------------------------------------------------------------------------------------------------------------
CAST((CASE WHEN @GenerateMessages = 1 THEN
N''RAISERROR(''''CREATE TABLE %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + @cr
ELSE CAST(N'''' AS NVARCHAR(MAX)) END) AS NVARCHAR(MAX))
+
CASE WHEN @GenerateCreateTable = 1 THEN
CAST(
N''CREATE TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + @cr + N''('' + @cr + STUFF((
SELECT
CAST(
@tab + N'','' + QUOTENAME(c.[name]) + N'' '' + ISNULL(REPLICATE('' '',@DataTypeSpacer - LEN(QUOTENAME(c.[name]))),'''')
+
CASE WHEN c.is_computed = 1
THEN N'' AS '' + cc.[definition]
ELSE UPPER(tp.[name]) +
CASE WHEN tp.[name] IN (N''varchar'', N''char'', N''varbinary'', N''binary'', N''text'')
THEN N''('' + CASE WHEN c.max_length = -1 THEN N''MAX'' ELSE CAST(c.max_length AS NVARCHAR(5)) END + N'')''
WHEN tp.[name] IN (N''NVARCHAR'', N''nchar'', N''ntext'')
THEN N''('' + CASE WHEN c.max_length = -1 THEN N''MAX'' ELSE CAST(c.max_length / 2 AS NVARCHAR(5)) END + N'')''
WHEN tp.[name] IN (N''datetime2'', N''time2'', N''datetimeoffset'')
THEN N''('' + CAST(c.scale AS NVARCHAR(5)) + N'')''
WHEN tp.[name] = N''decimal''
THEN N''('' + CAST(c.[precision] AS NVARCHAR(5)) + N'','' + CAST(c.scale AS NVARCHAR(5)) + N'')''
ELSE N''''
END +
CASE WHEN c.collation_name IS NOT NULL AND @GenerateCollation = 1 THEN N'' COLLATE '' + c.collation_name ELSE N'''' END +
CASE WHEN c.is_nullable = 1 THEN N'' NULL'' ELSE N'' NOT NULL'' END +
CASE WHEN dc.[definition] IS NOT NULL THEN CASE WHEN @GenerateConstraintNameOfDefaults = 1 THEN N'' CONSTRAINT '' + QUOTENAME(dc.[name]) ELSE N'''' END + N'' DEFAULT'' + dc.[definition] ELSE N'''' END +
CASE WHEN ic.is_identity = 1 AND @GenerateIdentity = 1 THEN N'' IDENTITY('' + CAST(ISNULL(ic.seed_value, N''0'') AS NCHAR(1)) + N'','' + CAST(ISNULL(ic.increment_value, N''1'') AS NCHAR(1)) + N'')'' ELSE N'''' END
END + @cr
AS NVARCHAR(MAX))
FROM [' + @DatabaseName + '].sys.columns c WITH (NOWAIT)
INNER JOIN [' + @DatabaseName + '].sys.types tp WITH (NOWAIT) ON c.user_type_id = tp.user_type_id
LEFT JOIN [' + @DatabaseName + '].sys.computed_columns cc WITH (NOWAIT) ON c.[object_id] = cc.[object_id]
AND c.column_id = cc.column_id
LEFT JOIN [' + @DatabaseName + '].sys.default_constraints dc WITH (NOWAIT) ON c.default_object_id != 0
AND c.[object_id] = dc.parent_object_id
AND c.column_id = dc.parent_column_id
LEFT JOIN [' + @DatabaseName + '].sys.identity_columns ic WITH (NOWAIT) ON c.is_identity = 1
AND c.[object_id] = ic.[object_id]
AND c.column_id = ic.column_id
WHERE c.[object_id] = t.[object_id]
ORDER BY c.column_id
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, @tab + N'' '') AS NVARCHAR(MAX))
ELSE CAST(N'''' AS NVARCHAR(MAX)) END
+
---------------------- Key Constraints ----------------------------------------------------------------
CAST(
CASE WHEN @GenerateKeyConstraints <> 1 THEN N''''
ELSE
ISNULL((SELECT @tab + N'', CONSTRAINT '' + QUOTENAME(k.[name]) + N'' PRIMARY KEY '' + ISNULL(kidx.[type_desc], N'''') + N''('' +
(SELECT STUFF((
SELECT N'', '' + QUOTENAME(c.[name]) + N'' '' + CASE WHEN ic.is_descending_key = 1 THEN N''DESC'' ELSE N''ASC'' END
FROM [' + @DatabaseName + '].sys.index_columns ic WITH (NOWAIT)
JOIN [' + @DatabaseName + '].sys.columns c WITH (NOWAIT) ON c.[object_id] = ic.[object_id]
AND c.column_id = ic.column_id
WHERE ic.is_included_column = 0
AND ic.[object_id] = k.parent_object_id
AND ic.index_id = k.unique_index_id
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N''''))
+ N'')'' + @cr
FROM [' + @DatabaseName + '].sys.key_constraints k WITH (NOWAIT)
LEFT JOIN [' + @DatabaseName + '].sys.indexes kidx ON k.parent_object_id = kidx.[object_id]
AND k.unique_index_id = kidx.index_id
WHERE k.parent_object_id = t.[object_id]
AND k.[type] = N''PK''), N'''') + N'')'' + @cr
END
AS NVARCHAR(MAX))
+
CAST(
CASE
WHEN @GenerateDataCompressionOptions = 1 AND (SELECT TOP 1 data_compression_desc FROM [' + @DatabaseName + '].sys.partitions WHERE OBJECT_ID = t.[object_id] AND index_id = 1) <> N''NONE''
THEN N''WITH (DATA_COMPRESSION='' + (SELECT TOP 1 data_compression_desc FROM [' + @DatabaseName + '].sys.partitions WHERE OBJECT_ID = t.[object_id] AND index_id = 1) + N'')'' + @cr
ELSE N'''' + @cr
END AS NVARCHAR(MAX))
+
--------------------- FOREIGN KEYS -----------------------------------------------------------------------------------------------------------------
CAST((CASE WHEN @GenerateMessages = 1 AND @GenerateDropFKIfItExists = 1 THEN
N''RAISERROR(''''CREATING FK OF %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + @cr
ELSE N'''' END) AS NVARCHAR(MAX))
+
CAST(
ISNULL((SELECT (
SELECT @cr +
N''ALTER TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' WITH''
+ CASE WHEN fk.is_not_trusted = 1
THEN N'' NOCHECK''
ELSE N'' CHECK''
END +
N'' ADD CONSTRAINT '' + QUOTENAME(fk.[name]) + N'' FOREIGN KEY(''
+ STUFF((
SELECT N'', '' + QUOTENAME(k.cname) + N''''
FROM fk_columns k
WHERE k.constraint_object_id = fk.[object_id]
AND fk.[object_id] = t.[object_id]
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N'''')
+ N'')'' +
N'' REFERENCES '' + QUOTENAME(SCHEMA_NAME(ro.[schema_id])) + N''.'' + QUOTENAME(ro.[name]) + N'' (''
+ STUFF((
SELECT N'', '' + QUOTENAME(k.rcname) + N''''
FROM fk_columns k
WHERE k.constraint_object_id = fk.[object_id]
AND fk.[object_id] = t.[object_id]
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N'''')
+ N'')''
+ CASE
WHEN fk.delete_referential_action = 1 THEN N'' ON DELETE CASCADE''
WHEN fk.delete_referential_action = 2 THEN N'' ON DELETE SET NULL''
WHEN fk.delete_referential_action = 3 THEN N'' ON DELETE SET DEFAULT''
ELSE N''''
END
+ CASE
WHEN fk.update_referential_action = 1 THEN N'' ON UPDATE CASCADE''
WHEN fk.update_referential_action = 2 THEN N'' ON UPDATE SET NULL''
WHEN fk.update_referential_action = 3 THEN N'' ON UPDATE SET DEFAULT''
ELSE N''''
END
+ @cr + N''ALTER TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' CHECK CONSTRAINT '' + QUOTENAME(fk.[name]) + N'''' + @cr
FROM [' + @DatabaseName + '].sys.foreign_keys fk WITH (NOWAIT)
JOIN [' + @DatabaseName + '].sys.objects ro WITH (NOWAIT) ON ro.[object_id] = fk.referenced_object_id
WHERE fk.parent_object_id = t.[object_id]
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)'')), N'''')
AS NVARCHAR(MAX))
+
--------------------- INDEXES ----------------------------------------------------------------------------------------------------------
CAST((CASE WHEN @GenerateMessages = 1 AND @GenerateIndexes = 1 THEN
N''RAISERROR(''''CREATING INDEXES OF %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + @cr
ELSE N'''' END) AS NVARCHAR(MAX))
+
CASE WHEN @GenerateIndexes = 1 THEN
CAST(
ISNULL(((SELECT
@cr + N''CREATE'' + CASE WHEN i.is_unique = 1 THEN N'' UNIQUE '' ELSE N'' '' END
+ i.[type_desc] + N'' INDEX '' + QUOTENAME(i.[name]) + N'' ON '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' ('' +
STUFF((
SELECT N'', '' + QUOTENAME(c.[name]) + N'''' + CASE WHEN c.is_descending_key = 1 THEN N'' DESC'' ELSE N'' ASC'' END
FROM index_column c
WHERE c.is_included_column = 0
AND c.[object_id] = t.[object_id]
AND c.index_id = i.index_id
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N'''') + N'')''
+ ISNULL(@cr + N''INCLUDE ('' +
STUFF((
SELECT N'', '' + QUOTENAME(c.[name]) + N''''
FROM index_column c
WHERE c.is_included_column = 1
AND c.[object_id] = t.[object_id]
AND c.index_id = i.index_id
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N'''') + N'')'', N'''') + @cr
FROM [' + @DatabaseName + '].sys.indexes i WITH (NOWAIT)
WHERE i.[object_id] = t.[object_id]
AND i.is_primary_key = 0
AND i.[type] in (1,2)
AND @GenerateIndexes = 1
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)'')
), N'''')
AS NVARCHAR(MAX))
ELSE N'''' END
+
------------------------ @GenerateDelete ----------------------------------------------------------
CAST((CASE WHEN @GenerateMessages = 1 AND @GenerateDelete = 1 THEN
N''RAISERROR(''''TRUNCATING %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + @cr
ELSE N'''' END) AS NVARCHAR(MAX))
+
CASE WHEN @GenerateDelete = 1 THEN
CAST(
(CASE WHEN EXISTS (SELECT TOP 1 [name] FROM [' + @DatabaseName + '].sys.foreign_keys WHERE referenced_object_id = t.[object_id]) THEN
N''DELETE FROM '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'';'' + @cr
ELSE
N''TRUNCATE TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'';'' + @cr
END)
AS NVARCHAR(MAX))
ELSE N'''' END
+
------------------------- @GenerateInsertInto ----------------------------------------------------------
CAST((CASE WHEN @GenerateMessages = 1 AND @GenerateDropFKIfItExists = 1 THEN
N''RAISERROR(''''INSERTING INTO %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + @cr
ELSE N'''' END) AS NVARCHAR(MAX))
+
CASE WHEN @GenerateInsertInto = 1
THEN
CAST(
CASE WHEN EXISTS (SELECT TOP 1 c.[name] FROM [' + @DatabaseName + '].sys.columns c WHERE c.[object_id] = t.[object_id] AND c.is_identity = 1) AND @GenerateIdentityInsert = 1 THEN
N''SET IDENTITY_INSERT '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' ON;'' + @cr
ELSE N'''' END
+
N''INSERT INTO '' + QUOTENAME(@TargetDatabase) + N''.'' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N''(''
+ @cr
+
(
@tab + N'' '' + SUBSTRING(
(
SELECT @tab + '',''+ QUOTENAME(c.[name]) + @cr
FROM [' + @DatabaseName + '].sys.columns c
WHERE c.[object_id] = t.[object_id]
AND c.system_type_ID <> 189 /*timestamp*/
AND c.is_computed = 0
AND (c.is_identity = 0 or @GenerateIdentityInsert in (0,1))
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)'')
,3,99999)
)
+ N'')'' + @cr + N''SELECT ''
+ @cr
+
(
@tab + N'' '' + SUBSTRING(
(
SELECT @tab + '',''+ QUOTENAME(c.[name]) + @cr
FROM [' + @DatabaseName + '].sys.columns c
WHERE c.[object_id] = t.[object_id]
AND c.system_type_ID <> 189 /*timestamp*/
AND c.is_computed = 0
AND (c.is_identity = 0 or @GenerateIdentityInsert in (0,1))
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)'')
,3,99999)
)
+ N''FROM '' + @SourceDatabase + N''.'' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id]))
+ N'';'' + @cr
+ CASE WHEN EXISTS (SELECT TOP 1 c.[name] FROM [' + @DatabaseName + '].sys.columns c WHERE c.[object_id] = t.[object_id] AND c.is_identity = 1) AND @GenerateIdentityInsert = 1 THEN
N''SET IDENTITY_INSERT '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' OFF;''+ @cr
ELSE N'''' END
AS NVARCHAR(MAX))
ELSE N'''' END
+
-------------------- USE TRANSACTION --------------------------------------------------------------------------------------------------
CAST(
CASE WHEN @UseTransaction = 1
THEN
@cr + N''COMMIT TRAN; ''
+ @cr + N''END TRY''
+ @cr + N''BEGIN CATCH''
+ @cr + N'' IF XACT_STATE() IN (-1,1)''
+ @cr + N'' ROLLBACK TRAN;''
+ @cr + N''''
+ @cr + N'' SELECT ERROR_NUMBER() AS ErrorNumber ''
+ @cr + N'' ,ERROR_SEVERITY() AS ErrorSeverity ''
+ @cr + N'' ,ERROR_STATE() AS ErrorState ''
+ @cr + N'' ,ERROR_PROCEDURE() AS ErrorProcedure ''
+ @cr + N'' ,ERROR_LINE() AS ErrorLine ''
+ @cr + N'' ,ERROR_MESSAGE() AS ErrorMessage; ''
+ @cr + N''END CATCH''
ELSE N'''' END
AS NVARCHAR(700))
FROM @Tables t
WHERE ID = @int
ORDER BY [name];
SET @int = @int + 1;
END
EXEC [master].dbo.PrintMax @sql;
/* see below for PrintMax code*/
END'
EXEC (@sql);
END
ELSE
And the Linked Server bit...
BEGIN
SELECT @sql = N'EXECUTE (''
SET NOCOUNT ON;
BEGIN
... Same code but be sure to double up on your single quotes
END
... code for the printmax proc (not mine, @Ben B) because it may not exist at destination server
DECLARE @CurrentEnd BIGINT; /* track the length of the next substring */
DECLARE @offset TINYINT; /*tracks the amount of offset needed */
DECLARE @String NVARCHAR(MAX);
SET @String = REPLACE(REPLACE(@sql, CHAR(13) + CHAR(10), CHAR(10)), CHAR(13), CHAR(10))
WHILE LEN(@String) > 1
BEGIN
IF CHARINDEX(CHAR(10), @String) BETWEEN 1 AND 4000
BEGIN
SET @CurrentEnd = CHARINDEX(CHAR(10), @String) -1
SET @offset = 2
END
ELSE
BEGIN
SET @CurrentEnd = 4000
SET @offset = 1
END
PRINT SUBSTRING(@String, 1, @CurrentEnd)
SET @String = SUBSTRING(@String, @CurrentEnd + @offset, LEN(@String))
END
END'') AT [' + @linkedservername + ']';
EXEC (@sql);
END
This query should identify columns that are potential problems...
SELECT *
FROM [source].INFORMATION_SCHEMA.COLUMNS src
INNER JOIN [dest].INFORMATION_SCHEMA.COLUMNS dst
ON dst.COLUMN_NAME = src.COLUMN_NAME
WHERE dst.CHARACTER_MAXIMUM_LENGTH < src.CHARACTER_MAXIMUM_LENGTH
Just to clarify PHP uses copy on write, so basically everything is a reference until you modify it, but for objects you need to use clone and the __clone() magic method like in the accepted answer.
Best answer of that question I've seen is:
list(, $caller) = debug_backtrace(false);
Short and clean
Old question but nowadays CSS3 makes vertical alignment really simple!
Just add to the <div>
this css:
display:flex;
align-items:center;
justify-content:center;
Live Example:
.img_thumb {_x000D_
float: left;_x000D_
height: 120px;_x000D_
margin-bottom: 5px;_x000D_
margin-left: 9px;_x000D_
position: relative;_x000D_
width: 147px;_x000D_
background-color: rgba(0, 0, 0, 0.5);_x000D_
border-radius: 3px;_x000D_
display:flex;_x000D_
align-items:center;_x000D_
justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
<a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
<img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
</a>_x000D_
</div>
_x000D_
For Ubuntu 14.04 and Android try:
hcitool scan #get hardware address
sudo bluetooth-agent PIN HARDWARE-ADDRESS
PIN dialog pops up on Android device. Enter same PIN.
Note: sudo apt-get install bluez-utils
might be necessary.
Note2: If PIN dialog does not appear, try pairing from Android first (will fail because of wrong PIN). Then try again as described above.
This is because of the proxy settings.
I also had the same problem, under which I could not use any of the modules which were fetching data from the internet.
There are simple steps to follow:
1. open the control panel
2. open internet options
3. under connection tab open LAN settings
4. go to advance settings and unmark everything, delete every proxy in there. Or u can just unmark the checkbox in proxy server this will also do the same
5. save all the settings by clicking ok.
you are done.
try to run the programme again, it must work
it worked for me at least
Try this code
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Salary";
//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").VerticalAlignment =
Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Create an array to multiple values at once.
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[4, 1] = "Johnson";
//Fill A2:B6 with an array of values (First and Last Names).
oSheet.get_Range("A2", "B6").Value2 = saNames;
//Fill C2:C6 with a relative formula (=A2 & " " & B2).
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
//Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.get_Range("D2", "D6");
oRng.Formula = "=RAND()*100000";
oRng.NumberFormat = "$0.00";
//AutoFit columns A:D.
oRng = oSheet.get_Range("A1", "D1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
oWB.Close();
oXL.Quit();
//...
In case you would like to use timeout middleware and exclude a specific route:
var timeout = require('connect-timeout');
app.use(timeout('5s')); //set 5s timeout for all requests
app.use('/my_route', function(req, res, next) {
req.clearTimeout(); // clear request timeout
req.setTimeout(20000); //set a 20s timeout for this request
next();
}).get('/my_route', function(req, res) {
//do something that takes a long time
});
upstream
in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add
. Depending on what you select for this name, your git pull
usage will change. For example, if you use:
git remote add upstream git://github.com/somename/original-project.git
then you would use this to pull changes:
git pull upstream master
But, if you choose origin for the name of the remote repo, your commands would be:
To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git
And to pull: git pull origin master
I think you need this ..
Dim n as Integer
For n = 5 to 17
msgbox cells(n,3) '--> sched waste
msgbox cells(n,4) '--> type of treatm
msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
msgbox cells(n,6) '--> email col
Next
I had such problem. In my case problem was in data - my column 'information' contained 1 unique value and it caused error
UPDATE: to correct work 'pivot' pairs (id_user,information) cannot have duplicates
It works:
df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5],
'information':['phon','phon','phone','phone1','phone','phone1','phone'],
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')
it doesn't work:
df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5],
'information':['phone','phone','phone','phone','phone','phone','phone'],
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')
Another way that this can be done using gmtime and format function;
from time import gmtime
print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))
Output: 2018-10-4 11:57:44
In addition, if you want to refer to the root directory, you can use:
/
Which will refer to the root. So, let's say we're in a file that's nested within a few levels of folders and you want to go back to the main index.html:
<a href="/index.html">My Index Page</a>
Robert is spot-on with further relative path explanations.
Another simple solution:
public class MyPagerAdapter extends FragmentPagerAdapter {
private Fragment mCurrentFragment;
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
//...
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (getCurrentFragment() != object) {
mCurrentFragment = ((Fragment) object);
}
super.setPrimaryItem(container, position, object);
}
}
While Jon's answer is correct, he is rewriting code that already exists in CopyTo
. So for .Net 4 use Sandip's solution, but for previous version of .Net use Jon's answer. Sandip's code would be improved by use of "using" as exceptions in CopyTo
are, in many situations, quite likely and would leave the MemoryStream
not disposed.
public static byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
Ok here is what I do
sys.argv is always what you type into the terminal or use as the file path when executing it with python.exe or pythonw.exe
For example you can run the file text.py several ways, they each give you a different answer they always give you the path that python was typed.
C:\Documents and Settings\Admin>python test.py
sys.argv[0]: test.py
C:\Documents and Settings\Admin>python "C:\Documents and Settings\Admin\test.py"
sys.argv[0]: C:\Documents and Settings\Admin\test.py
Ok so know you can get the file name, great big deal, now to get the application directory you can know use os.path, specifically abspath and dirname
import sys, os
print os.path.dirname(os.path.abspath(sys.argv[0]))
That will output this:
C:\Documents and Settings\Admin\
it will always output this no matter if you type python test.py or python "C:\Documents and Settings\Admin\test.py"
The problem with using __file__ Consider these two files test.py
import sys
import os
def paths():
print "__file__: %s" % __file__
print "sys.argv: %s" % sys.argv[0]
a_f = os.path.abspath(__file__)
a_s = os.path.abspath(sys.argv[0])
print "abs __file__: %s" % a_f
print "abs sys.argv: %s" % a_s
if __name__ == "__main__":
paths()
import_test.py
import test
import sys
test.paths()
print "--------"
print __file__
print sys.argv[0]
Output of "python test.py"
C:\Documents and Settings\Admin>python test.py
__file__: test.py
sys.argv: test.py
abs __file__: C:\Documents and Settings\Admin\test.py
abs sys.argv: C:\Documents and Settings\Admin\test.py
Output of "python test_import.py"
C:\Documents and Settings\Admin>python test_import.py
__file__: C:\Documents and Settings\Admin\test.pyc
sys.argv: test_import.py
abs __file__: C:\Documents and Settings\Admin\test.pyc
abs sys.argv: C:\Documents and Settings\Admin\test_import.py
--------
test_import.py
test_import.py
So as you can see file gives you always the python file it is being run from, where as sys.argv[0] gives you the file that you ran from the interpreter always. Depending on your needs you will need to choose which one best fits your needs.
For PAC based urls
Proxy proxy = new Proxy();
proxy.setProxyType(Proxy.ProxyType.PAC);
proxy.setProxyAutoconfigUrl("http://some-server/staging.pac");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, proxy);
return new FirefoxDriver(capabilities);
I hope this could help.
Now there is a problem, if you have package-lock.json with npm 5+. You have to remove it before use of npm install --production
.
It is standard matplotlib.pyplot:
...
import matplotlib.pyplot as plt
plt.ylim(10, 40)
Or simpler, as mwaskom comments below:
ax.set(ylim=(10, 40))
You can use below code for multiple select:
<select asp-for="EmployeeId" multiple="multiple" asp-items="@ViewBag.Employees">
<option>Please select</option>
</select>
You can also use:
<select id="EmployeeId" name="EmployeeId" multiple="multiple" asp-items="@ViewBag.Employees">
<option>Please select</option>
</select>
yes you need to call repaint(); revalidate(); when you call removeAll() then you have to call repaint() and revalidate()
The InterruptedException
is usually thrown when a sleep is interrupted.
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";
If Controls.Find is not found "textBox1" => error. You must add code.
If(tbx != null)
Edit:
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
If(tbx != null)
tbx.Text = "found!";
datetime.datetime.fromtimestamp()
is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp()
expects Unix timestamp, in seconds.
Do it like that:
>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
and the result is:
>>> date
datetime.datetime(2012, 3, 16, 1, 0)
Does it answer your question?
EDIT: J.F. Sebastian correctly suggested to use true division by 1e3
(float 1000
). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int
when dividing (using /
operator) int
by int
(this is called floor division). By replacing the divisor 1000
(being an int
) with the 1e3
divisor (being representation of 1000
as float) or with float(1000)
(or 1000.
etc.), the division becomes true division. Python 2.x returns float
when dividing int
by float
, float
by int
, float
by float
etc. And when there is some fractional part in the timestamp passed to fromtimestamp()
method, this method's result also contains information about that fractional part (as the number of microseconds).
Simply add the below to your maven project pom.xml flie:
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
They are both data formats for hierarchical data, so while the syntax is quite different, the structure is similar. Example:
JSON:
{
"persons": [
{
"name": "Ford Prefect",
"gender": "male"
},
{
"name": "Arthur Dent",
"gender": "male"
},
{
"name": "Tricia McMillan",
"gender": "female"
}
]
}
XML:
<persons>
<person>
<name>Ford Prefect</name>
<gender>male</gender>
</person>
<person>
<name>Arthur Dent</name>
<gender>male</gender>
</person>
<person>
<name>Tricia McMillan</name>
<gender>female</gender>
</person>
</persons>
The XML format is more advanced than shown by the example, though. You can for example add attributes to each element, and you can use namespaces to partition elements. There are also standards for defining the format of an XML file, the XPATH language to query XML data, and XSLT for transforming XML into presentation data.
The XML format has been around for some time, so there is a lot of software developed for it. The JSON format is quite new, so there is a lot less support for it.
While XML was developed as an independent data format, JSON was developed specifically for use with Javascript and AJAX, so the format is exactly the same as a Javascript literal object (that is, it's a subset of the Javascript code, as it for example can't contain expressions to determine values).
This works fine for me:
`%nin%` <- Negate(`%in%`)
I use GWTDesigner http://www.instantiations.com/gwtdesigner/ which is not free but works well. Best of all, their customer support is top notch - very responsive.
The same issue i was facing couple of months back and that is because end of free google map usage effective from i think June 11, 2018. Google does not provide free google maps now. You need to have a valid API key and valid billing used, which may give you 200$ of free usage.
Refer link for more details: Google map pricing
Follow the process here to get your api key.
If you are upto using only maps with specific user, you can try other map tools.
Updated for ES6 Arrow Functions (Supported in almost all modern browsers, see CanIUse)
const formatNumber = n => ("0" + n).slice(-2);
I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.
public static void RemoveEverythingButUserInfo()
{
foreach (String o in HttpContext.Current.Session.Keys)
{
if (o != "UserInfoIDontWantToAskForAgain")
keys.Add(o);
}
}
more generally, this could also look like this:
import multiprocessing
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
numberOfThreads = 4
if __name__ == '__main__':
jobs = []
for i, param in enumerate(params):
p = multiprocessing.Process(target=f, args=(i,param))
jobs.append(p)
for i in chunks(jobs,numberOfThreads):
for j in i:
j.start()
for j in i:
j.join()
Of course, that way is quite cruel (since it waits for every process in a junk until it continues with the next chunk). Still it works well for approx equal run times of the function calls.
You need to put an actual tab character after the -t\ and to do that in a shell you hit ctrl-v and then the tab character. Most shells I've used support this mode of literal tab entry.
Beware, though, because copying and pasting from another place generally does not preserve tabs.
in first.java
Intent i = new Intent(this, second.class);
i.putExtra("uri",uri);
startActivity(i);
in second.java
Bundle bd = getIntent().getExtras();
Uri uri = bd.getParcelable("uri");
Log.e("URI", uri.toString());
try {
Bitmap bitmap = Media.getBitmap(this.getContentResolver(), uri);
imageView.setImageBitmap(bitmap);
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Have a look at this
for outputing from mongo shell to file. There is no support for outputing csv from mongos shell. You would have to write the javascript yourself or use one of the many converters available. Google "convert json to csv" for example.
You can render your icon using the SVG Path notation.
See Google documentation for more information.
Here is a basic example:
var icon = {
path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
fillColor: '#FF0000',
fillOpacity: .6,
anchor: new google.maps.Point(0,0),
strokeWeight: 0,
scale: 1
}
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: false,
icon: icon
});
Here is a working example on how to display and scale a marker SVG icon:
Edit:
Another example here with a complex icon:
Edit 2:
And here is how you can have a SVG file as an icon:
Make sure this is not code smell. Is it possible to reverse the logic and be 'inclusive' rather than 'exclusive'?
List<String> names = ....
List<String> reducedNames = ....
for (String name : names) {
// Do something
if (conditionToIncludeMet)
reducedNames.add(name);
}
return reducedNames;
The situation that led me to this page involved old code that looped through a List using indecies to remove elements from the List. I wanted to refactor it to use the foreach style.
It looped through an entire list of elements to verify which ones the user had permission to access, and removed the ones that didn't have permission from the list.
List<Service> services = ...
for (int i=0; i<services.size(); i++) {
if (!isServicePermitted(user, services.get(i)))
services.remove(i);
}
To reverse this and not use the remove:
List<Service> services = ...
List<Service> permittedServices = ...
for (Service service:services) {
if (isServicePermitted(user, service))
permittedServices.add(service);
}
return permittedServices;
When would "remove" be preferred? One consideration is if gien a large list or expensive "add", combined with only a few removed compared to the list size. It might be more efficient to only do a few removes rather than a great many adds. But in my case the situation did not merit such an optimization.
Running a command through /usr/bin/env
has the benefit of looking for whatever the default version of the program is in your current environment.
This way, you don't have to look for it in a specific place on the system, as those paths may be in different locations on different systems. As long as it's in your path, it will find it.
One downside is that you will be unable to pass more than one argument (e.g. you will be unable to write /usr/bin/env awk -f
) if you wish to support Linux, as POSIX is vague on how the line is to be interpreted, and Linux interprets everything after the first space to denote a single argument. You can use /usr/bin/env -S
on some versions of env
to get around this, but then the script will become even less portable and break on fairly recent systems (e.g. even Ubuntu 16.04 if not later).
Another downside is that since you aren't calling an explicit executable, it's got the potential for mistakes, and on multiuser systems security problems (if someone managed to get their executable called bash
in your path, for example).
#!/usr/bin/env bash #lends you some flexibility on different systems
#!/usr/bin/bash #gives you explicit control on a given system of what executable is called
In some situations, the first may be preferred (like running python scripts with multiple versions of python, without having to rework the executable line). But in situations where security is the focus, the latter would be preferred, as it limits code injection possibilities.
It was a limitation of the technology at the time it was created. My answer copied over from Programmers.SE:
From one of the original HTML drafts:
NOTE: In the initial design for forms, multi-line text fields were supported by the Input element with TYPE=TEXT. Unfortunately, this causes problems for fields with long text values. SGML's default (Reference Quantity Set) limits the length of attribute literals to only 240 characters. The HTML 2.0 SGML declaration increases the limit to 1024 characters.
package com.ofs;
public class ReverseWordsInString{
public static void main(String[] args) {
String str = "welcome to the new world and how are you feeling ?";
// Get the Java runtime
Runtime runtime = Runtime.getRuntime();
// Run the garbage collector
runtime.gc();
// Calculate the used memory
long firstUsageMemory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used memory in bytes: " + firstUsageMemory);
System.out.println(str);
str = new StringBuffer(str).reverse().toString();
int count = 0;
int preValue = 0;
int lastspaceIndexVal = str.lastIndexOf(" ");
int strLen = str.length();
for (int i = 0; i < strLen - 1; i++) {
if (Character.isWhitespace(str.charAt(i))) {
if (i - preValue == 1 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 2 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 3 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 4 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 5 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.substring(i - 2, i - 1) + str.charAt(i - 3)
+ str.charAt(i - 3) + str.charAt(i - 5)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 6 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 7 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.charAt(i - 7)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 8 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.charAt(i - 7)
+ str.charAt(i - 8) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 2 && count != 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.substring(i, strLen);
preValue = i;
} else if (i - preValue == 3 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.substring(i, strLen);
preValue = i;
} else if (i - preValue == 4 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.substring(i, strLen);
preValue = i;
} else if (i - preValue == 5 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 6 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 7 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 8 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.charAt(i - 7)
+ str.substring(i, strLen);
preValue = i;
count++;
}
if (lastspaceIndexVal == preValue) {
if (strLen - lastspaceIndexVal == 2 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1);
preValue = i;
} else if (strLen - lastspaceIndexVal == 3 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2);
preValue = i;
} else if (strLen - lastspaceIndexVal == 4 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3);
preValue = i;
count++;
} else if (strLen - lastspaceIndexVal == 5 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3)
+ str.charAt(strLen - 4);
preValue = i;
} else if (strLen - lastspaceIndexVal == 6 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3)
+ str.charAt(strLen - 4)
+ str.charAt(strLen - 5);
preValue = i;
count++;
} else if (strLen - lastspaceIndexVal == 7 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3)
+ str.charAt(strLen - 4)
+ str.charAt(strLen - 5)
+ str.charAt(strLen - 6);
preValue = i;
} else if (strLen - lastspaceIndexVal == 8 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3)
+ str.charAt(strLen - 4)
+ str.charAt(strLen - 5)
+ str.charAt(strLen - 6)
+ str.charAt(strLen - 7);
preValue = i;
}
}
}
}
runtime.gc();
// Calculate the used memory
long SecondaryUsageMemory = runtime.totalMemory()
- runtime.freeMemory();
System.out.println("Used memory in bytes: " + SecondaryUsageMemory);
System.out.println(str);
}
}
Output buffering is used by PHP to improve performance and to perform a few tricks.
You can have PHP store all output into a buffer and output all of it at once improving network performance.
You can access the buffer content without sending it back to browser in certain situations.
Consider this example:
<?php
ob_start( );
phpinfo( );
$output = ob_get_clean( );
?>
The above example captures the output into a variable instead of sending it to the browser. output_buffering is turned off by default.
Consider this example:
<?php
ob_start( );
echo "Hello World";
if ( $some_error )
{
header( "Location: error.php" );
exit( 0 );
}
?>
First check if you have configured JDK correctly:
Secondly check if you have provided in path in Library's section
This should fix the problem
There are several useful answers, but none seem to cover all the latest options. To that end all my examples also cater for the presence of matching label
elements and also allow you to dynamically add checkboxes and see the results in a side-panel (by redirecting console.log
).
Listening for click
events on checkboxes
is not a good idea as that will not allow for keyboard toggling or for changes made where a matching label
element was clicked. Always listen for the change
event.
Use the jQuery :checkbox
pseudo-selector, rather than input[type=checkbox]
. :checkbox
is shorter and more readable.
Use is()
with the jQuery :checked
pseudo-selector to test for whether a checkbox is checked. This is guaranteed to work across all browsers.
$('#myform :checkbox').change(function () {
if ($(this).is(':checked')) {
console.log($(this).val() + ' is now checked');
} else {
console.log($(this).val() + ' is now unchecked');
}
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/2/
:checkbox
selector, which is preferable to using input[type=checkbox]
Delegated event handlers are designed for situations where the elements may not yet exist (dynamically loaded or created) and is very useful. They delegate responsibility to an ancestor element (hence the term).
$('#myform').on('change', ':checkbox', function () {
if ($(this).is(':checked')) {
console.log($(this).val() + ' is now checked');
} else {
console.log($(this).val() + ' is now unchecked');
}
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/4/
change
) to bubble up to a non-changing ancestor element (in this case #myform
). ':checkbox'
in this case) to only the elements in the bubble chain.document
as the default to connect the delegated event handler, if nothing else is closer/convenient. body
to attach delegated events as it has a bug (to do with styling) that can stop it getting mouse events.The upshot of delegated handlers is that the matching elements only need to exist at event time and not when the event handler was registered. This allows for dynamically added content to generate the events.
Q: Is it slower?
A: So long as the events are at user-interaction speeds, you do not need to worry about the negligible difference in speed between a delegated event handler and a directly connected handler. The benefits of delegation far outweigh any minor downside. Delegated event handlers are actually faster to register as they typically connect to a single matching element.
prop('checked', true)
fire the change
event?This is actually by design. If it did fire the event you would easily get into a situation of endless updates. Instead, after changing the checked property, send a change event to the same element using trigger
(not triggerHandler
):
e.g. without trigger
no event occurs
$cb.prop('checked', !$cb.prop('checked'));
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/5/
e.g. with trigger
the normal change event is caught
$cb.prop('checked', !$cb.prop('checked')).trigger('change');
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/6/
Notes:
triggerHandler
as was suggested by one user, as it will not bubble events to a delegated event handler.JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/8/
although it will work for an event handler directly connected to the element:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/9/
Events triggered with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.
Reference: http://api.jquery.com/triggerhandler/
If anyone has additional features they feel are not covered by this, please do suggest additions.
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
You could do like this too. It worked out for me.
<form action="ResultsDulith.php" id="intermediate" name="inputMachine[]" multiple="multiple" method="post">
<select id="selectDuration" name="selectDuration[]" multiple="multiple">
<option value="1 WEEK" >Last 1 Week</option>
<option value="2 WEEK" >Last 2 Week </option>
<option value="3 WEEK" >Last 3 Week</option>
<option value="4 WEEK" >Last 4 Week</option>
<option value="5 WEEK" >Last 5 Week</option>
<option value="6 WEEK" >Last 6 Week</option>
</select>
<input type="submit"/>
</form>
Then take the multiple selection from following PHP code below. It print the selected multiple values accordingly.
$shift=$_POST['selectDuration'];
print_r($shift);
More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:
Delete this folder after every few days interval. Most of the time, it occupy huge space!
~/Library/Developer/Xcode/DerivedData
All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.
~/Library/Developer/Xcode/Archives
iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.
~/Library/Developer/Xcode/iOS DeviceSupport
Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.
~/Library/Developer/CoreSimulator
(Here's a handy shell command for step 5: xcrun simctl delete unavailable
)
Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!
~/Library/Caches/com.apple.dt.Xcode
Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.
~/Library/Application Support/MobileSync/Backup
Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac
I got back about 40GB!
Part One - Polyfill
For browsers that haven't implemented it, a polyfill for array.find
. Courtesy of MDN.
if (!Array.prototype.find) {
Array.prototype.find = function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}
Part Two - Interface
You need to extend the open Array interface to include the find
method.
interface Array<T> {
find(predicate: (search: T) => boolean) : T;
}
When this arrives in TypeScript, you'll get a warning from the compiler that will remind you to delete this.
Part Three - Use it
The variable x
will have the expected type... { id: number }
var x = [{ "id": 1 }, { "id": -2 }, { "id": 3 }].find(myObj => myObj.id < 0);
Use the hex code for a non-breaking space. Something like this:
.breadcrumbs a:before {
content: '>\00a0';
}
I combined all of the above answers and created a shell function that would suit my needs. This is from a cygwin terminal of my 2 Windows10 machines where I had a shared folder between them. I need to be able to handle the following:
cat file.cpp | tx
tx < file.cpp
tx file.cpp
Where a specific filename is specified, I need to used the same filename during copy. Where input data stream has been piped thru, then i need to generate a temporary filename having the hour minute and seconds. The shared mainfolder has subfolders of the days of the week. This is for organizational purposes.
Behold, the ultimate script for my needs:
tx ()
{
if [ $# -eq 0 ]; then
local TMP=/tmp/tx.$(date +'%H%M%S')
while IFS= read -r line; do
echo "$line"
done < /dev/stdin > $TMP
cp $TMP //$OTHER/stargate/$(date +'%a')/
rm -f $TMP
else
[ -r $1 ] && cp $1 //$OTHER/stargate/$(date +'%a')/ || echo "cannot read file"
fi
}
If there is any way that you can see to further optimize this, I would like to know.
If you want to get any element that has part of a URL in their href attribute you could use:
$( 'a[href*="google.com"]' );
This will select all elements with a href that contains google.com, for example:
As stated by @BalusC in the comments below, it will also match elements that have google.com
at any position in the href, like blahgoogle.com
.
The documentation for WAITFOR()
doesn't explicitly lay out the required string format.
This will wait for 2 seconds:
WAITFOR DELAY '00:00:02';
The format is hh:mi:ss.mmm
.
From Python 2.5 onwards you can do:
value = b if a > 10 else c
Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:
value = [c, b][a > 10]
There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.
This is my solution using only CSS (Jsfiddle: http://jsfiddle.net/xykPT/).
div.options > label > input {_x000D_
visibility: hidden;_x000D_
}_x000D_
_x000D_
div.options > label {_x000D_
display: block;_x000D_
margin: 0 0 0 -10px;_x000D_
padding: 0 0 20px 0; _x000D_
height: 20px;_x000D_
width: 150px;_x000D_
}_x000D_
_x000D_
div.options > label > img {_x000D_
display: inline-block;_x000D_
padding: 0px;_x000D_
height:30px;_x000D_
width:30px;_x000D_
background: none;_x000D_
}_x000D_
_x000D_
div.options > label > input:checked +img { _x000D_
background: url(http://cdn1.iconfinder.com/data/icons/onebit/PNG/onebit_34.png);_x000D_
background-repeat: no-repeat;_x000D_
background-position:center center;_x000D_
background-size:30px 30px;_x000D_
}
_x000D_
<div class="options">_x000D_
<label title="item1">_x000D_
<input type="radio" name="foo" value="0" /> _x000D_
Item 1_x000D_
<img />_x000D_
</label>_x000D_
<label title="item2">_x000D_
<input type="radio" name="foo" value="1" />_x000D_
Item 2_x000D_
<img />_x000D_
</label> _x000D_
<label title="item3">_x000D_
<input type="radio" name="foo" value="2" />_x000D_
Item 3_x000D_
<img />_x000D_
</label>_x000D_
</div>
_x000D_
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) {
)
SELECT @variable1 = col1, @variable2 = col2
FROM table1
You need to download log4j and add in your classpath.
Subtract the past most one from the future most one and divide by 60.
Times are done in Unix format so they're just a big number showing the number of seconds from January 1, 1970, 00:00:00 GMT
For template, you can use
{% firstof request.user.get_full_name request.user.username %}
firstof will return the first one if not null else the second one
If you are using Windows.Data.Xml.Dom.XmlDocument
version of XmlDocument
(used in UWP apps for example), you can use yourXmlDocument.GetXml()
to get the XML as a string.
From my experience, Selenium Webdriver doesn't auto scroll to an element on click when there are more than one scrollable section on the page (which is quite common).
I am using Ruby, and for my AUT, I had to monkey patch the click method as follows;
class Element
#
# Alias the original click method to use later on
#
alias_method :base_click, :click
# Override the base click method to scroll into view if the element is not visible
# and then retry click
#
def click
begin
base_click
rescue Selenium::WebDriver::Error::ElementNotVisibleError
location_once_scrolled_into_view
base_click
end
end
The 'location_once_scrolled_into_view' method is an existing method on WebElement class.
I apreciate you may not be using Ruby but it should give you some ideas.
If you have local array with options (received by ajax call), i think you should use data
parameter as function returning results for select box:
var pills = [{id:0, text: "red"}, {id:1, text: "blue"}];
$('#selectpill').select2({
placeholder: "Select a pill",
data: function() { return {results: pills}; }
});
$('#uppercase').click(function() {
$.each(pills, function(idx, val) {
pills[idx].text = val.text.toUpperCase();
});
});
$('#newresults').click(function() {
pills = [{id:0, text: "white"}, {id:1, text: "black"}];
});
FIDDLE: http://jsfiddle.net/RVnfn/576/
In case if you customize select2 interface with buttons, just call updateResults
(this method not allowed to call from outsite of select2 object but you can add it to allowedMethods
array in select2 if you need to) method after updateting data array(pills in example).
Custom data adapter with additional updateOptions
(its unclear why original ArrayAdapter
lacks this functionality) method can be used to dynamically update options list (all options in this example):
$.fn.select2.amd.define('select2/data/customAdapter',
['select2/data/array', 'select2/utils'],
function (ArrayAdapter, Utils) {
function CustomDataAdapter ($element, options) {
CustomDataAdapter.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomDataAdapter, ArrayAdapter);
CustomDataAdapter.prototype.updateOptions = function (data) {
this.$element.find('option').remove(); // remove all options
this.addOptions(this.convertToOptions(data));
}
return CustomDataAdapter;
}
);
var customAdapter = $.fn.select2.amd.require('select2/data/customAdapter');
var sel = $('select').select2({
dataAdapter: customAdapter,
data: pills
});
$('#uppercase').click(function() {
$.each(pills, function(idx, val) {
pills[idx].text = val.text.toUpperCase();
});
sel.data('select2').dataAdapter.updateOptions(pills);
});
FIDDLE: https://jsfiddle.net/xu48n36c/1/
in v4 you can define custom transport method that can work with local data array (thx @Caleb_Kiage for example, i've played with it without succes)
docs: https://select2.github.io/options.html#can-an-ajax-plugin-other-than-jqueryajax-be-used
Select2 uses the transport method defined in ajax.transport to send requests to your API. By default, this transport method is jQuery.ajax but this can be changed.
$('select').select2({
ajax: {
transport: function(params, success, failure) {
var items = pills;
// fitering if params.data.q available
if (params.data && params.data.q) {
items = items.filter(function(item) {
return new RegExp(params.data.q).test(item.text);
});
}
var promise = new Promise(function(resolve, reject) {
resolve({results: items});
});
promise.then(success);
promise.catch(failure);
}
}
});
BUT with this method you need to change ids of options if text of option in array changes - internal select2 dom option element list did not modified. If id of option in array stay same - previous saved option will be displayed instead of updated from array! That is not problem if array modified only by adding new items to it - ok for most common cases.
FIDDLE: https://jsfiddle.net/xu48n36c/3/
@Entity(name = "someThing") => this name will be used to name the Entity @Table(name = "someThing") => this name will be used to name a table in DB
So, in the first case your table and entity will have the same name, that will allow you to access your table with the same name as the entity while writing HQL or JPQL.
And in second case while writing queries you have to use the name given in @Entity and the name given in @Table will be used to name the table in the DB.
So in HQL your someThing will refer to otherThing in the DB.
Since you are interested in catching network related errors and HTTP errors, the following provides a better approach:
function curl_error_test($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$responseBody = curl_exec($ch);
/*
* if curl_exec failed then
* $responseBody is false
* curl_errno() returns non-zero number
* curl_error() returns non-empty string
* which one to use is up too you
*/
if ($responseBody === false) {
return "CURL Error: " . curl_error($ch);
}
$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
/*
* 4xx status codes are client errors
* 5xx status codes are server errors
*/
if ($responseCode >= 400) {
return "HTTP Error: " . $responseCode;
}
return "No CURL or HTTP Error";
}
Tests:
curl_error_test("http://expamle.com"); // CURL Error: Could not resolve host: expamle.com
curl_error_test("http://example.com/whatever"); // HTTP Error: 404
curl_error_test("http://example.com"); // No CURL or HTTP Error
After a function is invoked, it goes out of scope. If that function contains something like a callback function, then that callback function is still in scope. If the callback function references some local variable in the immediate environment of the parent function, then naturally you'd expect that variable to be inaccessible to the callback function and return undefined.
Closures ensure that any property that is referenced by the callback function is available for use by that function, even when its parent function may have gone out of scope.
This method seems ok in all browsers, if you set the onclick with a jQuery event:
<a href="javascript:;">Click me!</a>
As said before, href="#" with change the url hash and can trigger data re/load if you use a History (or ba-bbq) JS plugin.
I tried to do the same as you, but apparently the backgroundImage doesn't work with encoded data. As an alternative, I suggest to use CSS classes and the change between those classes.
If you are generating the data "on the fly" you can load the CSS files dynamically.
CSS:
.backgroundA {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RDUxRjY0ODgyQTkxMTFFMjk0RkU5NjI5MEVDQTI2QzUiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RDUxRjY0ODkyQTkxMTFFMjk0RkU5NjI5MEVDQTI2QzUiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpENTFGNjQ4NjJBOTExMUUyOTRGRTk2MjkwRUNBMjZDNSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpENTFGNjQ4NzJBOTExMUUyOTRGRTk2MjkwRUNBMjZDNSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PuT868wAAABESURBVHja7M4xEQAwDAOxuPw5uwi6ZeigB/CntJ2lkmytznwZFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYW1qsrwABYuwNkimqm3gAAAABJRU5ErkJggg==");
}
.backgroundB {
background-image:url("data:image/gif;base64,R0lGODlhUAAPAKIAAAsLav///88PD9WqsYmApmZmZtZfYmdakyH5BAQUAP8ALAAAAABQAA8AAAPbWLrc/jDKSVe4OOvNu/9gqARDSRBHegyGMahqO4R0bQcjIQ8E4BMCQc930JluyGRmdAAcdiigMLVrApTYWy5FKM1IQe+Mp+L4rphz+qIOBAUYeCY4p2tGrJZeH9y79mZsawFoaIRxF3JyiYxuHiMGb5KTkpFvZj4ZbYeCiXaOiKBwnxh4fnt9e3ktgZyHhrChinONs3cFAShFF2JhvCZlG5uchYNun5eedRxMAF15XEFRXgZWWdciuM8GCmdSQ84lLQfY5R14wDB5Lyon4ubwS7jx9NcV9/j5+g4JADs=");
}
HTML:
<div id="test" height="20px" class="backgroundA">
div test 1
</div>
<div id="test2" name="test2" height="20px" class="backgroundB">
div test2
</div>
<input type="button" id="btn" />
Javascript:
function change() {
if (document.getElementById("test").className =="backgroundA") {
document.getElementById("test").className="backgroundB";
document.getElementById("test2").className="backgroundA";
} else {
document.getElementById("test").className="backgroundA";
document.getElementById("test2").className="backgroundB";
}
}
btn.onclick= change;
I fiddled it here, press the button and it will switch the divs' backgrounds: http://jsfiddle.net/egorbatik/fFQC6/
You have to loop through the list and fill your String[]
.
String[] array = new String[lst.size()];
int index = 0;
for (Object value : lst) {
array[index] = (String) value;
index++;
}
If the list would be of String
values, List then this would be as simple as calling lst.toArray(new String[0])
;
I was having trouble getting redirection to HTTPS to work on a Windows server which runs version 6 of MS Internet Information Services (IIS). I’m more used to working with Apache on a Linux host so I turned to the Internet for help and this was the highest ranking Stack Overflow question when I searched for “php redirect http to https”. However, the selected answer didn’t work for me.
After some trial and error, I discovered that with IIS, $_SERVER['HTTPS']
is
set to off
for non-TLS connections. I thought the following code should
help any other IIS users who come to this question via search engine.
<?php
if (! isset($_SERVER['HTTPS']) or $_SERVER['HTTPS'] == 'off' ) {
$redirect_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: $redirect_url");
exit();
}
?>
Edit: From another Stack Overflow answer,
a simpler solution is to check if($_SERVER["HTTPS"] != "on")
.
private Map<String, String> convertAttributes(final Map<String, Object> attributes) {
final Map<String, String> result = new HashMap<String, String>();
for (final Map.Entry<String, Object> entry : attributes.entrySet()) {
result.put(entry.getKey(), String.valueOf(entry.getValue()));
}
return result;
}
pip3 install --trusted-host pypi.org --trusted-host files.pythonhosted.org <app>
There is a pandas function that can be applied to DateTime index in pandas data frame.
date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list
the element inside the list:
u'1910-11-02'
You might need to replace the 'u'.
There might be some additional arguments that I should put into the previous functions.
Don't forget, union all is a way to add records to a record set without sorting or merging (as opposed to union).
So for example:
select * from (
select col1, col2
from table a
<....>
order by col3
limit by 200
) a
union all
select * from (
select cola, colb
from table b
<....>
order by colb
limit by 300
) b
It keeps the individual queries clearer and allows you to sort by different parameters in each query. However by using the selected answer's way it might become clearer depending on complexity and how related the data is because you are conceptualizing the sort. It also allows you to return the artificial column to the querying program so it has a context it can sort by or organize.
But this way has the advantage of being fast, not introducing extra variables, and making it easy to separate out each query including the sort. The ability to add a limit is simply an extra bonus.
And of course feel free to turn the union all into a union and add a sort for the whole query. Or add an artificial id, in which case this way makes it easy to sort by different parameters in each query, but it otherwise is the same as the accepted answer.
Using the constraints
features UniqueConstraint
is preferred over unique_together.
From the Django documentation for unique_together
:
Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together.
unique_together may be deprecated in the future.
For example:
class Volume(models.Model):
id = models.AutoField(primary_key=True)
journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
volume_number = models.CharField('Volume Number', max_length=100)
comments = models.TextField('Comments', max_length=4000, blank=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
]
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
Old question, but a slightly cleaner approach using LINQ's .Cast<>()
var values = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();
foreach(var val in values)
{
Console.WriteLine("Member: {0}",val.ToString());
}
You can use Paros to sniff the network traffic from your iPhone. See this excellent step by step post for more information: http://blog.jerodsanto.net/2009/06/sniff-your-iphones-network-traffic/. Also, look in the comments for some advice for using other proxies to get the same job done.
One caveat is that Paras only sniffs HTTP GET/POST requests using the method above, so to sniff all network traffic, try the following:
- Just turn on network sharing over WiFi and run a packet sniffer like Cocoa Packet Analyzer (in OSX).
- Then connect to the new network from iPhone over WiFi. (SystemPreferences->Sharing->InternetSharing)
If you're after sniffing these packets on Windows, connect to the internet using Ethernet, share your internet connection, and use the Windows computer as your access point. Then, just run Wireshark as normal and intercept the packets flowing through, filtering by their startpoints. Alternatively, try using a network hub as Wireshark can trace all packets flowing through a network if they are using the same router endpoint address (as in a hub).
You cannot make Maven re-download dependencies, but what you can do instead is to purge dependencies that were incorrectly downloaded using mvn dependency:purge-local-repository
See: http://maven.apache.org/plugins/maven-dependency-plugin/purge-local-repository-mojo.html
I have the same setup that you do, and this works fine for me. I think that maybe the problem lies somewhere on your moss configuration or on your network.
You said that moss resides on the same domain as your application. If you have access to the site with your user (that is logged into your machine)... have you tried:
client.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
An easy way to do:
function toggleButton(ref,bttnID){
document.getElementById(bttnID).disabled= ((ref.value !== ref.defaultValue) ? false : true);
}
<input ... onkeyup="toggleButton(this,'bttnsubmit');">
<input ... disabled='disabled' id='bttnsubmit' ... >
Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. [-a-z]
or [0-9-]
), OR escape it (e.g. [a-z\-0-9]
) in order to add "hyphen" to your class.
It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.
(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. [a-z\%\$\#\@\!\-\_]
) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)
Great question!
<input type="text" style="font-size:xxpt;height:xxpx">
Just replace "xx" with whatever values you wish.
app:cardBackgroundColor="#488747"
use this in your card view and you can change a color of your card view
With React Hook, form is made super easy (React Hook Form: https://github.com/bluebill1049/react-hook-form)
i have reused your html markup.
import React from "react";
import useForm from 'react-hook-form';
function Test() {
const { useForm, register } = useForm();
const contactSubmit = data => {
console.log(data);
};
return (
<form name="contactform" onSubmit={contactSubmit}>
<div className="col-md-6">
<fieldset>
<input name="name" type="text" size="30" placeholder="Name" ref={register} />
<br />
<input name="email" type="text" size="30" placeholder="Email" ref={register} />
<br />
<input name="phone" type="text" size="30" placeholder="Phone" ref={register} />
<br />
<input name="address" type="text" size="30" placeholder="Address" ref={register} />
<br />
</fieldset>
</div>
<div className="col-md-6">
<fieldset>
<textarea name="message" cols="40" rows="20" className="comments" placeholder="Message" ref={register} />
</fieldset>
</div>
<div className="col-md-12">
<fieldset>
<button className="btn btn-lg pro" id="submit" value="Submit">
Send Message
</button>
</fieldset>
</div>
</form>
);
}
parent()
method returns the direct parent element of the selected one. This method only traverse a single level up the DOM tree.
parents()
method allows us to search through the ancestors of these elements in the DOM tree. Begin from given selector and move up.
The **.parents()** and **.parent()** methods are almost similar, except that the latter only travels a single level up the DOM tree. Also, **$( "html" ).parent()** method returns a set containing document whereas **$( "html" ).parents()** returns an empty set.
[closest()][3]method returns the first ancestor of the selected element.An ancestor is a parent, grandparent, great-grandparent, and so on.
This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.
According to docs:
**closest()** method is similar to **parents()**, in that they both traverse up the DOM tree. The differences are as follows:
**closest()**
Begins with the current element
Travels up the DOM tree and returns the first (single) ancestor that matches the passed expression
The returned jQuery object contains zero or one element
**parents()**
Begins with the parent element
Travels up the DOM tree and returns all ancestors that matches the passed expression
The returned jQuery object contains zero or more than one element
Good question. These two operators work the same in PHP and C#.
|
is a bitwise OR. It will compare two values by their bits. E.g. 1101 | 0010 = 1111. This is extremely useful when using bit options. E.g. Read = 01 (0X01) Write = 10 (0X02) Read-Write = 11 (0X03). One useful example would be opening files. A simple example would be:
File.Open(FileAccess.Read | FileAccess.Write); //Gives read/write access to the file
||
is a logical OR. This is the way most people think of OR and compares two values based on their truth. E.g. I am going to the store or I will go to the mall. This is the one used most often in code. For example:
if(Name == "Admin" || Name == "Developer") { //allow access } //checks if name equals Admin OR Name equals Developer
PHP Resource: http://us3.php.net/language.operators.bitwise
C# Resources: http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.71).aspx
http://msdn.microsoft.com/en-us/library/6373h346(VS.71).aspx
.compare()
returns an integer, which is a measure of the difference between the two strings.
0
indicates that the two strings compare as equal. operator==
simply returns a boolean, indicating whether the strings are equal or not.
If you don't need the extra detail, you may as well just use ==
.
You can run but you can't hide... At the end you will be using NVM anyways.
Although some answers here maybe great, none helped my case (which is very similar to OP's error message).
This error needed fixing because even though my components rendered with their data (pulled from API), when deployed to firebase hosting, it did not render some of my components (the components that rely on data).
To fix it (and given you followed the suggestions in the accepted answer), in the Parent component (the ones pulling data and passing to child component), I did:
// pulled data in this life cycle hook, saving it to my store
created() {
FetchData.getProfile()
.then(myProfile => {
const mp = myProfile.data;
console.log(mp)
this.$store.dispatch('dispatchMyProfile', mp)
this.propsToPass = mp;
})
.catch(error => {
console.log('There was an error:', error.response)
})
}
// called my store here
computed: {
menu() {
return this.$store.state['myProfile'].profile
}
},
// then in my template, I pass this "menu" method in child component
<LeftPanel :data="menu" />
_x000D_
This cleared that error away. I deployed it again to firebase hosting, and viola!
Hope this bit helps you.
Try this:
Update users
Set username = 'Jack', password='123'
Where ID = '1'
Or if you're actually trying to insert:
Insert Into users (id, username, password) VALUES ('1', 'Jack','123');
You are initializing datatables twice, why?
// Take this off
/*
$(document).ready(function() {
$( '#example' ).dataTable();
} );
*/
$(document).ready( function() {
$( '#example' ).dataTable( {
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
// Bold the grade for all 'A' grade browsers
if ( aData[4] == "A" )
{
$('td:eq(4)', nRow).html( '<b>A</b>' );
}
}
} );
} );
You can use zjsonpatch library, which presents the diff information in accordance with RFC 6902 (JSON Patch). Its very easy to use. Please visit its description page for its usage
file_put_contents('file.txt', 'bar');
echo file_get_contents('file.txt'); // bar
file_put_contents('file.txt', 'foo');
echo file_get_contents('file.txt'); // foo
Alternatively, if you're stuck with fopen()
you can use the w
or w+
modes:
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
You could also do:
public static IWebElement FindElementByJs(this IWebDriver driver, string jsCommand)
{
return (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(jsCommand);
}
public static IWebElement FindElementByJsWithWait(this IWebDriver driver, string jsCommand, int timeoutInSeconds)
{
if (timeoutInSeconds > 0)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
wait.Until(d => d.FindElementByJs(jsCommand));
}
return driver.FindElementByJs(jsCommand);
}
public static IWebElement FindElementByJsWithWait(this IWebDriver driver, string jsCommand)
{
return FindElementByJsWithWait(driver, jsCommand, s_PageWaitSeconds);
}
Few years later, I've built this library to do drop files into any HTML element.
You can use it like
const Droppable = require('droppable');
const droppable = new Droppable({
element: document.querySelector('#my-droppable-element')
})
droppable.onFilesDropped((files) => {
console.log('Files were dropped:', files);
});
// Clean up when you're done!
droppable.destroy();
The following javascript will fade in an element from opacity 0 to whatever the opacity value was at the time of calling fade in. You can also set the duration of the animation which is nice:
function fadeIn(element) {
var duration = 0.5;
var interval = 10;//ms
var op = 0.0;
var iop = element.style.opacity;
var timer = setInterval(function () {
if (op >= iop) {
op = iop;
clearInterval(timer);
}
element.style.opacity = op;
op += iop/((1000/interval)*duration);
}, interval);
}
*Based on IBUs answer but modified to account for previous opacity value and ability to set duration, also removed irrelevant CSS changes it was making
With Java 8+, you can use the new Java time API:
to parse the time:
LocalTime time = LocalTime.parse("11:22")
to do date comparisons, you have LocalTime::isBefore
and LocalTime::isAfter
- note that these methods are strict
So you problem would be as simple as:
public static void main(String[] args) {
LocalTime time = LocalTime.parse("11:22");
System.out.println(isBetween(time, LocalTime.of(10, 0), LocalTime.of(18, 0)));
}
public static boolean isBetween(LocalTime candidate, LocalTime start, LocalTime end) {
return !candidate.isBefore(start) && !candidate.isAfter(end); // Inclusive.
}
For inclusive beginning but exclusive ending (half-open), use this line.
return !candidate.isBefore(start) && candidate.isBefore(end); // Exclusive of end.
You can use a link to invoke history.go(-1)
in Javascript, which is essentially equivalent to clicking the Back button. Ideally, however, it'd be better to just create a link back to the URL from whence the user was posted to the form - that way the proper "flow" of history is preserved and the user doesn't wonder why they have something to click "Forward" to which is actually just submitting the form again.