When every given bool
is True
, or when every given bool
is False
...
they all are equal to each other!
So, we just need to find two elements which evaluates to different bool
s
to know that there is at least one True
and at least one False
.
not bool(a)==bool(b)==bool(c)
I belive it short-circuits, cause AFAIK a==b==c
equals a==b and b==c
.
def _any_but_not_all(first, iterable): #doing dirty work
bool_first=bool(first)
for x in iterable:
if bool(x) is not bool_first:
return True
return False
def any_but_not_all(arg, *args): #takes any amount of args convertable to bool
return _any_but_not_all(arg, args)
def v_any_but_not_all(iterable): #takes iterable or iterator
iterator=iter(iterable)
return _any_but_not_all(next(iterator), iterator)
I wrote also some code dealing with multiple iterables, but I deleted it from here because I think it's pointless. It's however still available here.
Traditional relational databases were designed as client/server database systems. They can be scaled horizontally but the process to do so tends to be complex and error prone. NewSQL databases like NuoDB are memory-centric distributed database systems designed to scale out horizontally while maintaining the SQL/ACID properties of traditional RDBMS.
For more information on NuoDB, read their technical white paper.
Although already over a year old, I stumbled across this question a couple of times on other Google search and I believe I can improve on the previous answer for the benefit of others.
Short answer is you cannot combine both action in one line, but you can create a chain that does what you want and then call it in a one liner.
Let's create a chain to log and accept:
iptables -N LOG_ACCEPT
And let's populate its rules:
iptables -A LOG_ACCEPT -j LOG --log-prefix "INPUT:ACCEPT:" --log-level 6
iptables -A LOG_ACCEPT -j ACCEPT
Now let's create a chain to log and drop:
iptables -N LOG_DROP
And let's populate its rules:
iptables -A LOG_DROP -j LOG --log-prefix "INPUT:DROP: " --log-level 6
iptables -A LOG_DROP -j DROP
Now you can do all actions in one go by jumping (-j) to you custom chains instead of the default LOG / ACCEPT / REJECT / DROP:
iptables -A <your_chain_here> <your_conditions_here> -j LOG_ACCEPT
iptables -A <your_chain_here> <your_conditions_here> -j LOG_DROP
I can't say I know the best practice, but here's my perspective.
Are you using these variables for anything?
Personally, I haven't needed to change neither, on Linux nor Windows, in environments varying from development to production. Unless you are doing something particular that relies on them, chances are you could leave them alone.
catalina.sh
sets the variables that Tomcat needs to work out of the box. It also says that CATALINA_BASE
is optional:
# CATALINA_HOME May point at your Catalina "build" directory.
#
# CATALINA_BASE (Optional) Base directory for resolving dynamic portions
# of a Catalina installation. If not present, resolves to
# the same directory that CATALINA_HOME points to.
I'm pretty sure you'll find out whether or not your setup works when you start your server.
I needed to do this for files created with dynamic names in a particular folder and served by IIS.
This worked for me:
Add a new header with the following info:
Name: content-disposition
Value: attachment
(from: http://forums.iis.net/t/1175103.aspx?add+CustomHeaders+only+for+certain+file+types+)
SELECT RIGHT(column, 3)
That's all you need.
You can also do LEFT()
in the same way.
Bear in mind if you are using this in a WHERE
clause that the RIGHT()
can't use any indexes.
The below code worked for me.
I've created a method for seekbar
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mp.start();
getDurationTimer();
getSeekBarStatus();
}
//Creating duration time method
public void getDurationTimer(){
final long minutes=(mSongDuration/1000)/60;
final int seconds= (int) ((mSongDuration/1000)%60);
SongMaxLength.setText(minutes+ ":"+seconds);
}
//creating a method for seekBar progress
public void getSeekBarStatus(){
new Thread(new Runnable() {
@Override
public void run() {
// mp is your MediaPlayer
// progress is your ProgressBar
int currentPosition = 0;
int total = mp.getDuration();
seekBar.setMax(total);
while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
}).start();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress=0;
@Override
public void onProgressChanged(final SeekBar seekBar, int ProgressValue, boolean fromUser) {
if (fromUser) {
mp.seekTo(ProgressValue);//if user drags the seekbar, it gets the position and updates in textView.
}
final long mMinutes=(ProgressValue/1000)/60;//converting into minutes
final int mSeconds=((ProgressValue/1000)%60);//converting into seconds
SongProgress.setText(mMinutes+":"+mSeconds);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
SongProgress and SongMaxLength are the TextView to show song duration and song length.
First we should know the order of execution of Clauses i.e FROM > WHERE > GROUP BY > HAVING > DISTINCT > SELECT > ORDER BY. Since WHERE Clause gets executed before GROUP BY Clause the records cannot be filtered by applying WHERE to a GROUP BY applied records.
"HAVING is same as the WHERE clause but is applied on grouped records".
first the WHERE clause fetches the records based on the condition then the GROUP BY clause groups them accordingly and then the HAVING clause fetches the group records based on the having condition.
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
Whether or not you install opencv3 manually or from Gohlke's whl package, I found the need to create/edit the file cv.py in site_packages as follows to make compatable with old code:
import cv2 as cv
Add the following line to the beginning script1.py
#!/usr/bin/env python
and then make the script executable:
$ chmod +x script1.py
If the script resides in a directory that appears in your PATH
variable, you can simply type
$ script1.py
Otherwise, you'll need to provide the full path (either absolute or relative). This includes the current working directory, which should not be in your PATH
.
$ ./script1.py
You can achieve this without loops by using the following.
It looks very elegant and it does not require any dependencies such as jQuery of Underscore.js.
function transpose(matrix) {
return zeroFill(getMatrixWidth(matrix)).map(function(r, i) {
return zeroFill(matrix.length).map(function(c, j) {
return matrix[j][i];
});
});
}
function getMatrixWidth(matrix) {
return matrix.reduce(function (result, row) {
return Math.max(result, row.length);
}, 0);
}
function zeroFill(n) {
return new Array(n+1).join('0').split('').map(Number);
}
Minified
function transpose(m){return zeroFill(m.reduce(function(m,r){return Math.max(m,r.length)},0)).map(function(r,i){return zeroFill(m.length).map(function(c,j){return m[j][i]})})}function zeroFill(n){return new Array(n+1).join("0").split("").map(Number)}
Here is a demo I threw together. Notice the lack of loops :-)
// Create a 5 row, by 9 column matrix._x000D_
var m = CoordinateMatrix(5, 9);_x000D_
_x000D_
// Make the matrix an irregular shape._x000D_
m[2] = m[2].slice(0, 5);_x000D_
m[4].pop();_x000D_
_x000D_
// Transpose and print the matrix._x000D_
println(formatMatrix(transpose(m)));_x000D_
_x000D_
function Matrix(rows, cols, defaultVal) {_x000D_
return AbstractMatrix(rows, cols, function(r, i) {_x000D_
return arrayFill(cols, defaultVal);_x000D_
});_x000D_
}_x000D_
function ZeroMatrix(rows, cols) {_x000D_
return AbstractMatrix(rows, cols, function(r, i) {_x000D_
return zeroFill(cols);_x000D_
});_x000D_
}_x000D_
function CoordinateMatrix(rows, cols) {_x000D_
return AbstractMatrix(rows, cols, function(r, i) {_x000D_
return zeroFill(cols).map(function(c, j) {_x000D_
return [i, j];_x000D_
});_x000D_
});_x000D_
}_x000D_
function AbstractMatrix(rows, cols, rowFn) {_x000D_
return zeroFill(rows).map(function(r, i) {_x000D_
return rowFn(r, i);_x000D_
});_x000D_
}_x000D_
/** Matrix functions. */_x000D_
function formatMatrix(matrix) {_x000D_
return matrix.reduce(function (result, row) {_x000D_
return result + row.join('\t') + '\n';_x000D_
}, '');_x000D_
}_x000D_
function copy(matrix) { _x000D_
return zeroFill(matrix.length).map(function(r, i) {_x000D_
return zeroFill(getMatrixWidth(matrix)).map(function(c, j) {_x000D_
return matrix[i][j];_x000D_
});_x000D_
});_x000D_
}_x000D_
function transpose(matrix) { _x000D_
return zeroFill(getMatrixWidth(matrix)).map(function(r, i) {_x000D_
return zeroFill(matrix.length).map(function(c, j) {_x000D_
return matrix[j][i];_x000D_
});_x000D_
});_x000D_
}_x000D_
function getMatrixWidth(matrix) {_x000D_
return matrix.reduce(function (result, row) {_x000D_
return Math.max(result, row.length);_x000D_
}, 0);_x000D_
}_x000D_
/** Array fill functions. */_x000D_
function zeroFill(n) {_x000D_
return new Array(n+1).join('0').split('').map(Number);_x000D_
}_x000D_
function arrayFill(n, defaultValue) {_x000D_
return zeroFill(n).map(function(value) {_x000D_
return defaultValue || value;_x000D_
});_x000D_
}_x000D_
/** Print functions. */_x000D_
function print(str) {_x000D_
str = Array.isArray(str) ? str.join(' ') : str;_x000D_
return document.getElementById('out').innerHTML += str || '';_x000D_
}_x000D_
function println(str) {_x000D_
print.call(null, [].slice.call(arguments, 0).concat(['<br />']));_x000D_
}
_x000D_
#out {_x000D_
white-space: pre;_x000D_
}
_x000D_
<div id="out"></div>
_x000D_
You can't directly control this, because it's an option controlled by Internet Explorer users.
Opening pages using Window.open with a different window name will open in a new browser window like a popup, OR open in a new tab, if the user configured the browser to do so.
It's the only solution to map a ManyToMany association : you need a join table between the two entities tables to map the association.
It's also used for OneToMany (usually unidirectional) associations when you don't want to add a foreign key in the table of the many side and thus keep it independent of the one side.
Search for @JoinTable in the hibernate documentation for explanations and examples.
use...
# chmod 400 ec2-keypair.pem
don't use the 600 permission otherwise you might overwrite your key accidently.
A good alternative to PuTTY is the Mintty terminal emulator. It has more configurable options than PuTTY.
You can also put the item with the default value selected out of the ng-repeat like follow :
<div ng-app="app" ng-controller="myCtrl">
<select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
<option value="yourDefaultValue">Default one</option>
<option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
</select>
</div>
and don't forget the value atribute if you leave it blank you will have the same issue.
This is exactly what you want. Try this:
{{ wpis.entry.lastChangeDate|date:'Y-m-d H:i' }}
If you make both dates NSDate
s you can use NSDate
's compare:
method:
NSComparisonResult result = [Date2 compare:Date1];
if(result==NSOrderedAscending)
NSLog(@"Date1 is in the future");
else if(result==NSOrderedDescending)
NSLog(@"Date1 is in the past");
else
NSLog(@"Both dates are the same");
You can take a look at the docs here.
All the answers above are correct, What I prefer is to use tui mode (ctrl+X A or 'tui enable') which shows your location and the function in a separate window which is very helpful for the users. Hope that helps too.
I'm using something like this:
$.when(
$.each(yourArray, function (key, value) {
// Do Something in loop here
})
).then(function () {
// After loop ends.
});
Just as a suggestion:
<?php echo date("W", strtotime("2012-10-18")); ?>
Might be a little simpler than all that lot.
Other things you could do:
<?php echo date("Weeknumber: W", strtotime("2012-10-18 01:00:00")); ?>
<?php echo date("Weeknumber: W", strtotime($MY_DATE)); ?>
This works:
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
It will produce:
'abcdgxre'
You can also use a delimiter like a comma to produce:
'a,b,c,d,g,x,r,e'
By using:
','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
You should use datetime
object, not str
.
>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'
To get the datetime object from the string, use datetime.datetime.strptime
:
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'
This example reads 6 bytes into a byte array and writes it to another byte array. It does an XOR operation with the bytes so that the result written to the file is the same as the original starting values. The file is always 6 bytes in size, since it writes at position 0.
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
byte[] b1 = { 1, 2, 4, 8, 16, 32 };
byte[] b2 = new byte[6];
byte[] b3 = new byte[6];
byte[] b4 = new byte[6];
FileStream f1;
f1 = new FileStream("test.txt", FileMode.Create, FileAccess.Write);
// write the byte array into a new file
f1.Write(b1, 0, 6);
f1.Close();
// read the byte array
f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);
f1.Read(b2, 0, 6);
f1.Close();
// make changes to the byte array
for (int i = 1; i < b2.Length; i++)
{
b2[i] = (byte)(b2[i] ^ (byte)10); //xor 10
}
f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);
// write the new byte array into the file
f1.Write(b2, 0, 6);
f1.Close();
f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);
// read the byte array
f1.Read(b3, 0, 6);
f1.Close();
// make changes to the byte array
for (int i = 1; i < b3.Length; i++)
{
b4[i] = (byte)(b3[i] ^ (byte)10); //xor 10
}
f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);
// b4 will have the same values as b1
f1.Write(b4, 0, 6);
f1.Close();
}
}
}
I had to drop and recreate the general log at one point. During the recreation, character sets got messed up and I ended up having this error in the logs:
[ERROR] Incorrect definition of table mysql.general_log: expected the type of column 'user_host' at position 1 to have character set 'utf8' but found character set 'latin1'
So if the standard answer of "check to make sure logging is on" doesn't work for you, check to make sure your fields have the right character set.
Check out the request module.
It's more full featured than node's built-in http client.
var request = require('request');
var propertiesObject = { field1:'test1', field2:'test2' };
request({url:url, qs:propertiesObject}, function(err, response, body) {
if(err) { console.log(err); return; }
console.log("Get response: " + response.statusCode);
});
In pgAdmin you can also use
SET search_path TO your_db_name;
Go back to Windows, tell Eclipse to change the encoding to UTF-8, then back to Unix and run d2u
on the files.
The method I use is to import the ch.qos.logback modules and then type-cast the slf4j Logger instance to a ch.qos.logback.classic.Logger. This instance includes a setLevel() method.
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
Logger levelSet = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
// Now you can set the desired logging-level
levelSet.setLevel( Level.OFF );
To find out the possible Logging-levels, you can explode the ch.qos.logback class to see all the possible values for Level:
prompt$ javap -cp logback-classic-1.2.3.jar ch.qos.logback.classic.Level
The results are the following:
{
// ...skipping
public static final ch.qos.logback.classic.Level OFF;
public static final ch.qos.logback.classic.Level ERROR;
public static final ch.qos.logback.classic.Level WARN;
public static final ch.qos.logback.classic.Level INFO;
public static final ch.qos.logback.classic.Level DEBUG;
public static final ch.qos.logback.classic.Level TRACE;
public static final ch.qos.logback.classic.Level ALL;
}
Take a look at anchor tags. You can create an anchor with
<div id="anchor-name">Heading Text</div>
and refer to it later with
<a href="http://server/page.html#anchor-name">Link text</a>
Tried list[:][0]
to show all first member of each list inside list is not working. Result is unknowingly will same as list[0][:]
So i use list comprehension like this:
[i[0] for i in list]
which return first element value for each list inside list.
Right click on your database and select Tasks -> Generate Scripts
Select things you want to restore or just let the complete database be selected by default.
Now click Next -> Click Advanced and Choose 'Script for Server Version' to the 'ssms version' you want to restore like 2008 or 2008 R2 or other.
also, select 'type of data to script' to 'Schema and Data'
Finally execute this .sql file on destination ssms and Change Database Name in first Line Use Database
if database is not there then create one and if you get error with executing the script execute the script from alter keyword to complete bottom.
<div id="placeholder" style="position:absolute; top:0; right:0; bottom:0; left:0;"></div>
It is also possible to split the string into a character array using fold
and then iterate over this array:
for char in `echo "??????" | fold -w1`; do
echo $char
done
var result = replaceSpace.replace(/ /g, ";");
Here, / /g
is a regex (regular expression). The flag g
means global. It causes all matches to be replaced.
Create extension for an Array
:
extension Array {
var string: String? {
do {
let data = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
return String(data: data, encoding: .utf8)
} catch {
return nil
}
}
}
If you need to just do something in background without the PHP page waiting for it to complete, you could use another (background) PHP script that is "invoked" with wget command. This background PHP script will be executed with privileges, of course, as any other PHP script on your system.
Here is an example on Windows using wget from gnuwin32 packages.
The background code (file test-proc-bg.php) as an exmple ...
sleep(5); // some delay
file_put_contents('test.txt', date('Y-m-d/H:i:s.u')); // writes time in a file
The foreground script, the one invoking ...
$proc_command = "wget.exe http://localhost/test-proc-bg.php -q -O - -b";
$proc = popen($proc_command, "r");
pclose($proc);
You must use the popen/pclose for this to work properly.
The wget options:
-q keeps wget quiet.
-O - outputs to stdout.
-b works on background
You can use window.close()
to close browser tab.
I've made an example without jQuery here : http://codepen.io/sorinnn/pen/ovzdq
/**
by Nemes Ioan Sorin - not an jQuery big fan
therefore this script is for those who love the old clean coding style
@id = the id of the element who need to bring into view
Note : this demo scrolls about 12.700 pixels from Link1 to Link3
*/
(function()
{
window.setTimeout = window.setTimeout; //
})();
var smoothScr = {
iterr : 30, // set timeout miliseconds ..decreased with 1ms for each iteration
tm : null, //timeout local variable
stopShow: function()
{
clearTimeout(this.tm); // stopp the timeout
this.iterr = 30; // reset milisec iterator to original value
},
getRealTop : function (el) // helper function instead of jQuery
{
var elm = el;
var realTop = 0;
do
{
realTop += elm.offsetTop;
elm = elm.offsetParent;
}
while(elm);
return realTop;
},
getPageScroll : function() // helper function instead of jQuery
{
var pgYoff = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
return pgYoff;
},
anim : function (id) // the main func
{
this.stopShow(); // for click on another button or link
var eOff, pOff, tOff, scrVal, pos, dir, step;
eOff = document.getElementById(id).offsetTop; // element offsetTop
tOff = this.getRealTop(document.getElementById(id).parentNode); // terminus point
pOff = this.getPageScroll(); // page offsetTop
if (pOff === null || isNaN(pOff) || pOff === 'undefined') pOff = 0;
scrVal = eOff - pOff; // actual scroll value;
if (scrVal > tOff)
{
pos = (eOff - tOff - pOff);
dir = 1;
}
if (scrVal < tOff)
{
pos = (pOff + tOff) - eOff;
dir = -1;
}
if(scrVal !== tOff)
{
step = ~~((pos / 4) +1) * dir;
if(this.iterr > 1) this.iterr -= 1;
else this.itter = 0; // decrease the timeout timer value but not below 0
window.scrollBy(0, step);
this.tm = window.setTimeout(function()
{
smoothScr.anim(id);
}, this.iterr);
}
if(scrVal === tOff)
{
this.stopShow(); // reset function values
return;
}
}
}
use
pattern.compile("\"");
String s= p.toString()+"yourcontent"+p.toString();
will give result as yourcontent
as is
This is the trick I use. Good for responsive designs. Works perfectly when user tries to mess with browser resizing.
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
#container {
position: absolute;
width: 100%;
min-height: 100%;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="container">some content</div>
</body>
Time complexity is O(E+V)
instead of O(2E+V)
because if the time complexity is n^2+2n+7 then it is written as O(n^2).
Hence, O(2E+V) is written as O(E+V)
because difference between n^2 and n matters but not between n and 2n.
Manish, Eden after your suggestion: here is the code. But still showing the red(Default) icon.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var markers = [
{
"title": 'This is title',
"lat": '-37.801578',
"lng": '145.060508',
"icon": 'http://maps.gstatic.com/mapfiles/ridefinder-images/mm_20_green.png',
"description": 'Vikash Rathee. <br/><a href="http://www.pricingindia.in/pincode.aspx">Pin Code by City</a>'
}
];
</script>
<script type="text/javascript">
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
flat: true,
styles: [ { "stylers": [ { "hue": "#4bd6bf" }, { "gamma": "1.58" } ] } ],
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: markers[i][3],
title: data.title
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
</script>
<div id="dvMap" style="width: 100%; height: 100%">
</div>
Once gdb
starts, you can run the program using "r args".
So if you are running your code by:
$ executablefile arg1 arg2 arg3
Debug it on gdb
by:
$ gdb executablefile
(gdb) r arg1 arg2 arg3
Instead of this :
for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){
It should be
for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++){
^ ^ ^
| | |
| | |
-------------------------------------------Note the changes
|
v |
if(rank==cards.substring(a,b){ |
-------------------------------------------------------------
|
v
System.out.println(c); //capital S in system
Try to get using:
var count = $("ul > li").size();
alert(count);
I recommend adding the following line after the export to PDF:
ThisWorkbook.Sheets("Sheet1").Select
(where eg. Sheet1
is the single sheet you want to be active afterwards)
Leaving multiple sheets in a selected state may cause problems executing some code. (eg. unprotect doesn't function properly when multiple sheets are actively selected.)
To control the precision of floating point arithmetic, you should use java.math.BigDecimal. Read The need for BigDecimal by John Zukowski for more information.
Given your example, the last line would be as following using BigDecimal.
import java.math.BigDecimal;
BigDecimal premium = BigDecimal.valueOf("1586.6");
BigDecimal netToCompany = BigDecimal.valueOf("708.75");
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);
This results in the following output.
877.85 = 1586.6 - 708.75
Parameter int defStyleAttr
does not specifies the style. From the Android documentation:
defStyleAttr - An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.
To setup the style in View constructor we have 2 possible solutions:
With use of ContextThemeWrapper:
ContextThemeWrapper wrappedContext = new ContextThemeWrapper(yourContext, R.style.your_style);
TextView textView = new TextView(wrappedContext, null, 0);
With four-argument constructor (available starting from LOLLIPOP):
TextView textView = new TextView(yourContext, null, 0, R.style.your_style);
Key thing for both solutions - defStyleAttr
parameter should be 0 to apply our style to the view.
The Hibernate configuration file must define the entity classes:
<mapping class="annotations.Users"/>
Or you must explicitly add the class to the configuration using
configuration.addClass(annotations.Users.class)
// Read mappings as a application resourceName
// addResource is for add hbml.xml files in case of declarative approach
configuration.addResource("myFile.hbm.xml"); // not hibernateAnnotations.cfg.xml
If you want to see the list of all available snippets:
Press Ctrl + K and then X.
Here is the code that will not download courpt files
$filename = "myfile.jpg";
$file = "/uploads/images/".$filename;
header('Content-type: application/octet-stream');
header("Content-Type: ".mime_content_type($file));
header("Content-Disposition: attachment; filename=".$filename);
while (ob_get_level()) {
ob_end_clean();
}
readfile($file);
I have included mime_content_type which will return content type of file .
To prevent from corrupt file download i have added ob_get_level() and ob_end_clean();
I had the same problem. Android Emulator worked perfectly on Android < 6.0. When I used emulator Nexus 5 (Android 6.0), the app worked very slow with I/Choreographer: Skipped frames
in the logs.
So, I solved this problem by changing in Manifest file hardwareAccelerated
option to true
like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<application android:hardwareAccelerated="true">
...
</application>
</manifest>
I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"
in my .html
<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">
then in my component.ts
reSearch(newValue: string) {
//this.searchText would equal the new value
//handle my filtering with the new value
}
I did not find any of the above code worked. Maybe that's because my app is running .NET 3.5. I don't know. The following code worked perfectly for me. I got this from a senior level .NET app developer on my team.
Write(Microsoft.Win32.Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\", "WordWatcher", "\"" + Application.ExecutablePath.ToString() + "\"");
public bool Write(RegistryKey baseKey, string keyPath, string KeyName, object Value)
{
try
{
// Setting
RegistryKey rk = baseKey;
// I have to use CreateSubKey
// (create or open it if already exits),
// 'cause OpenSubKey open a subKey as read-only
RegistryKey sk1 = rk.CreateSubKey(keyPath);
// Save the value
sk1.SetValue(KeyName.ToUpper(), Value);
return true;
}
catch (Exception e)
{
// an error!
MessageBox.Show(e.Message, "Writing registry " + KeyName.ToUpper());
return false;
}
}
You can simply use
pip install numpy
Or for python3, use
pip3 install numpy
I have created an illustration that explains better than words, in my opinion:
First order your object based on key using this function
function sortObject(o) {
return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}
Then, compare the stringified version of your object, using this funtion
function isEqualObject(a,b){
return JSON.stringify(sortObject(a)) == JSON.stringify(sortObject(b));
}
Here is an example
Assuming objects keys are ordered differently and are of the same values
var obj1 = {"hello":"hi","world":"earth"}
var obj2 = {"world":"earth","hello":"hi"}
isEqualObject(obj1,obj2);//returns true
Try AddDate:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("now:", now)
then := now.AddDate(0, -1, 0)
fmt.Println("then:", then)
}
Produces:
now: 2009-11-10 23:00:00 +0000 UTC
then: 2009-10-10 23:00:00 +0000 UTC
Playground: http://play.golang.org/p/QChq02kisT
I was getting the same error in chrome (and different one in Firefox, IE).
Also in error.log i was getting [error] [client cli.ent.ip.add] Invalid method in request \x16\x03
Following the instructions form this site I changed my configuration FROM:
<VirtualHost subdomain.domain.com:443>
ServerAdmin [email protected]
ServerName subdomain.domain.com
SSLEngine On
SSLCertificateFile conf/ssl/ssl.crt
SSLCertificateKeyFile conf/ssl/ssl.key
</VirtualHost>
TO:
<VirtualHost _default_:443>
ServerAdmin [email protected]
ServerName subdomain.domain.com
SSLEngine On
SSLCertificateFile conf/ssl/ssl.crt
SSLCertificateKeyFile conf/ssl/ssl.key
</VirtualHost>
Now it's working fine :)
You shouldn't use the keypress
event, but the keyup
or keydown
event because the keypress
event is intended for real (printable) characters. keydown
is handled at a lower level so it will capture all nonprinting keys like delete and enter.
The multiline flag tells regex to match the pattern to each line as opposed to the entire string for your purposes a wild card will suffice.
I got this error because my AdonisJS server was not running before I ran the test. Running the server first fixed it.
I have the same error and it fixed it including in the file the following
#include <stdint.h>
at the beginning of your file.
A clear way without any need of regExp and any external libraries.
public static String trimLeadingZeros(String source) {
for (int i = 0; i < source.length(); ++i) {
char c = source.charAt(i);
if (c != '0') {
return source.substring(i);
}
}
return ""; // or return "0";
}
Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction()
function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!
You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.
Create Proc[usp_mquestions]
(
@title nvarchar(500), --0
@tags nvarchar(max), --1
@category nvarchar(200), --2
@ispoll char(1), --3
@descriptions nvarchar(max), --4
)
AS
BEGIN TRY
BEGIN
DECLARE @message varchar(1000);
DECLARE @tempid bigint;
IF((SELECT count(id) from [xyz] WHERE title=@title)>0)
BEGIN
SELECT 'record already existed.';
END
ELSE
BEGIN
if @id=0
begin
select @tempid =id from [xyz] where id=@id;
if @tempid is null
BEGIN
INSERT INTO xyz
(entrydate,updatedate)
VALUES
(GETDATE(),GETDATE())
SET @tempid=@@IDENTITY;
END
END
ELSE
BEGIN
set @tempid=@id
END
if @tempid>0
BEGIN
-- Updation of table begin--
UPDATE tab_questions
set title=@title, --0
tags=@tags, --1
category=@category, --2
ispoll=@ispoll, --3
descriptions=@descriptions, --4
status=@status, --5
WHERE id=@tempid ; --9 ;
IF @id=0
BEGIN
SET @message= 'success:Record added successfully:'+ convert(varchar(10), @tempid)
END
ELSE
BEGIN
SET @message= 'success:Record updated successfully.:'+ convert(varchar(10), @tempid)
END
END
ELSE
BEGIN
SET @message= 'failed:invalid request:'+convert(varchar(10), @tempid)
END
END
END
END TRY
BEGIN CATCH
SET @message='failed:'+ ERROR_MESSAGE();
END CATCH
SELECT @message;
This will remove spaces only, matches the SQL functionality of rtrim(ltrim(myString))
Dim charstotrim() As Char = {" "c}
myString = myString .Trim(charstotrim)
To diagnose this problem, run the service under the Visual Studio debugger. Use the menu: Debug|Exceptions and indicate that you want to break when an Exception is thrown.
The original exception thrown will have a much better error message than "..it is in the Faulted state."
For example I was getting this exception from ServiceHost.Open(), but when I caught the original exception at the time it was thrown, the error message was:
Service 'MyServiceName' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.
Fixing the spelling error in App.config solved the problem.
HTML--
<div class="col-sm-12" id="my_styles">
<button type="submit" class="btn btn-warning" id="1">Button1</button>
<button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>
css--
.active{
background:red;
}
button.btn:active{
background:red;
}
jQuery--
jQuery("#my_styles .btn").click(function(){
jQuery("#my_styles .btn").removeClass('active');
jQuery(this).toggleClass('active');
});
view the live demo on jsfiddle
If you want to quit without saving in Vim and have Vim return a non-zero exit code, you can use :cq
.
I use this all the time because I can't be bothered to pinky shift for !
. I often pipe things to Vim which don't need to be saved in a file. We also have an odd SVN wrapper at work which must be exited with a non-zero value in order to abort a checkin.
Code bellow may help if you want to exclude boolean type from serialization either:
@JsonInclude(JsonInclude.Include.NON_ABSENT)
Flask-JsonTools package has an implementation of JsonSerializableBase Base class for your models.
Usage:
from sqlalchemy.ext.declarative import declarative_base
from flask.ext.jsontools import JsonSerializableBase
Base = declarative_base(cls=(JsonSerializableBase,))
class User(Base):
#...
Now the User
model is magically serializable.
If your framework is not Flask, you can just grab the code
Pipe it to awk
:
awk '{if(NR>1)print}'
or sed
sed -n '1!p'
Also it may cause some warnigs in logs like a Cglib2AopProxy Unable to proxy method. And many other reasons for this are described here Why always have single implementaion interfaces in service and dao layers?
Okay, the .NET 2.0 answers:
If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.)
If you do need to clone the values, you can use something like this:
public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue>
(Dictionary<TKey, TValue> original) where TValue : ICloneable
{
Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count,
original.Comparer);
foreach (KeyValuePair<TKey, TValue> entry in original)
{
ret.Add(entry.Key, (TValue) entry.Value.Clone());
}
return ret;
}
That relies on TValue.Clone()
being a suitably deep clone as well, of course.
#!/bin/bash
req=$(curl -s -X GET http://host:8080/some/resource -H "Accept: application/json") 2>&1
echo "${req}"
Thanks, for your function I Used IT........................ This is my EXAMPLE
**UPDATE [RD].[PurchaseOrderHeader]
SET [DispatchCycleNumber] ='10'
WHERE OrderNumber in(select * FROM XA.fn_SplitOrderIDs(@InvoiceNumberList))**
CREATE FUNCTION [XA].[fn_SplitOrderIDs]
(
@OrderList varchar(500)
)
RETURNS
@ParsedList table
(
OrderID int
)
AS
BEGIN
DECLARE @OrderID varchar(10), @Pos int
SET @OrderList = LTRIM(RTRIM(@OrderList))+ ','
SET @Pos = CHARINDEX(',', @OrderList, 1)
IF REPLACE(@OrderList, ',', '') <> ''
BEGIN
WHILE @Pos > 0
BEGIN
SET @OrderID = LTRIM(RTRIM(LEFT(@OrderList, @Pos - 1)))
IF @OrderID <> ''
BEGIN
INSERT INTO @ParsedList (OrderID)
VALUES (CAST(@OrderID AS int)) --Use Appropriate conversion
END
SET @OrderList = RIGHT(@OrderList, LEN(@OrderList) - @Pos)
SET @Pos = CHARINDEX(',', @OrderList, 1)
END
END
RETURN
END
The MVC framework supports this natively. The System.Web.MVC.Controller.File controller provides methods to return a file by name/stream/array.
For example using a virtual path to the file you could do the following.
return File(virtualFilePath, System.Net.Mime.MediaTypeNames.Application.Octet, Path.GetFileName(virtualFilePath));
<style type="text/css">
td { word-wrap: break-word;max-width:50px; }
</style>
I think you have created your test classes outside the src folder. You can solve above problem by two way:
Add your package name in java build path->source
Move your package/class
in src
folder
I have the same problem and solved in this way both solutions working fine.
I think the best way to use django is with virtualenv it's safe and you can install many apps in virtualenv which does not affect any outer space of the system vitualenv uses the default version of python which is same as in your system to install virtualenv
sudo pip install virtualenv
or for python3
sudo pip3 install virtualenv
and then in your dir
mkdir ~/newproject
cd ~/newproject
Now, create a virtual environment within the project directory by typing
virtualenv newenv
To install packages into the isolated environment, you must activate it by typing:
source newenv/bin/activate
now install here with
pip install django
You can verify the installation by typing:
django-admin --version
To leave your virtual environment, you need to issue the deactivate command from anywhere on the system:
deactivate
Note that the word boundaries also depend on the Locale. I think the best way to do it using standard java.text.BreakIterator. Here is an example from the java.sun.com tutorial.
import java.text.BreakIterator;
import java.util.Locale;
public static void main(String[] args) {
String text = "\n" +
"\n" +
"For example I'm extracting a text String from a text file and I need those words to form an array. However, when I do all that some words end with comma (,) or a full stop (.) or even have brackets attached to them (which is all perfectly normal).\n" +
"\n" +
"What I want to do is to get rid of those characters. I've been trying to do that using those predefined String methods in Java but I just can't get around it.\n" +
"\n" +
"Every help appreciated. Thanx";
BreakIterator wordIterator = BreakIterator.getWordInstance(Locale.getDefault());
extractWords(text, wordIterator);
}
static void extractWords(String target, BreakIterator wordIterator) {
wordIterator.setText(target);
int start = wordIterator.first();
int end = wordIterator.next();
while (end != BreakIterator.DONE) {
String word = target.substring(start, end);
if (Character.isLetterOrDigit(word.charAt(0))) {
System.out.println(word);
}
start = end;
end = wordIterator.next();
}
}
Source: http://java.sun.com/docs/books/tutorial/i18n/text/word.html
If I may answer this.
The fundamentals behind converting series to data frame is to understand that
1. At conceptual level, every column in data frame is a series.
2. And, every column name is a key name that maps to a series.
If you keep above two concepts in mind, you can think of many ways to convert series to data frame. One easy solution will be like this:
Create two series here
import pandas as pd
series_1 = pd.Series(list(range(10)))
series_2 = pd.Series(list(range(20,30)))
Create an empty data frame with just desired column names
df = pd.DataFrame(columns = ['Column_name#1', 'Column_name#1'])
Put series value inside data frame using mapping concept
df['Column_name#1'] = series_1
df['Column_name#2'] = series_2
Check results now
df.head(5)
I managed to render the following SELECT with SQLAlchemy on both layers.
SELECT count(*) AS count_1
FROM "table"
from sqlalchemy import select, func, Integer, Table, Column, MetaData
metadata = MetaData()
table = Table("table", metadata,
Column('primary_key', Integer),
Column('other_column', Integer) # just to illustrate
)
print select([func.count()]).select_from(table)
You just subclass Query
(you have probably anyway) and provide a specialized count()
method, like this one.
from sqlalchemy.sql.expression import func
class BaseQuery(Query):
def count_star(self):
count_query = (self.statement.with_only_columns([func.count()])
.order_by(None))
return self.session.execute(count_query).scalar()
Please note that order_by(None)
resets the ordering of the query, which is irrelevant to the counting.
Using this method you can have a count(*)
on any ORM Query, that will honor all the filter
andjoin
conditions already specified.
Try this regular expression:
^(.{0,2}|([^A]..|A[^B].|AB[^C])|.{4,})$
It describes three cases:
A
, orA
but the second is not B
, orA
, the second B
but the third is not C
You could wrapping the transaction over try..catch or even reverse them,
here my example code I used to in laravel 5,, if you look deep inside DB:transaction()
in Illuminate\Database\Connection
that the same like you write manual transaction.
Laravel Transaction
public function transaction(Closure $callback)
{
$this->beginTransaction();
try {
$result = $callback($this);
$this->commit();
}
catch (Exception $e) {
$this->rollBack();
throw $e;
} catch (Throwable $e) {
$this->rollBack();
throw $e;
}
return $result;
}
so you could write your code like this, and handle your exception like throw message back into your form via flash or redirect to another page. REMEMBER return inside closure is returned in transaction() so if you return redirect()->back()
it won't redirect immediately, because the it returned at variable which handle the transaction.
Wrap Transaction
$result = DB::transaction(function () use ($request, $message) {
try{
// execute query 1
// execute query 2
// ..
return redirect(route('account.article'));
} catch (\Exception $e) {
return redirect()->back()->withErrors(['error' => $e->getMessage()]);
}
});
// redirect the page
return $result;
then the alternative is throw boolean variable and handle redirect outside transaction function or if your need to retrieve why transaction failed you can get it from $e->getMessage()
inside catch(Exception $e){...}
Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.
The newest versions of pandas now include a built-in function for iterating over rows.
for index, row in df.iterrows():
# do some logic here
Or, if you want it faster use itertuples()
But, unutbu's suggestion to use numpy functions to avoid iterating over rows will produce the fastest code.
You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)
usually the log file is in
/var/log/apache2/error.log
or
/var/log/httpd/error.log
I found the solution to a similar problem. I am using Gradle 1.11 (as April, 2014). The project name can be changed directly in settings.gradle
file as following:
rootProject.name='YourNewName'
This takes care of uploading to repository (Artifactory w/ its plugin for me) with the correct artifactId.
This really isn't too hard to implement with ModelForms. So lets say you have Forms A, B, and C. You print out each of the forms and the page and now you need to handle the POST.
if request.POST():
a_valid = formA.is_valid()
b_valid = formB.is_valid()
c_valid = formC.is_valid()
# we do this since 'and' short circuits and we want to check to whole page for form errors
if a_valid and b_valid and c_valid:
a = formA.save()
b = formB.save(commit=False)
c = formC.save(commit=False)
b.foreignkeytoA = a
b.save()
c.foreignkeytoB = b
c.save()
Here are the docs for custom validation.
import os
os.remove("/tmp/<file_name>.txt")
Or
import os
os.unlink("/tmp/<file_name>.txt")
Or
pathlib Library for Python version >= 3.4
file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()
Unlink method used to remove the file or the symbolik link.
If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.
os.path.isfile("/path/to/file")
exception handling.
EXAMPLE for os.path.isfile
#!/usr/bin/python
import os
myfile="/tmp/foo.txt"
## If file exists, delete it ##
if os.path.isfile(myfile):
os.remove(myfile)
else: ## Show an error ##
print("Error: %s file not found" % myfile)
#!/usr/bin/python
import os
## Get input ##
myfile= raw_input("Enter file name to delete: ")
## Try to delete the file ##
try:
os.remove(myfile)
except OSError as e: ## if failed, report it back to the user ##
print ("Error: %s - %s." % (e.filename, e.strerror))
Enter file name to delete : demo.txt Error: demo.txt - No such file or directory. Enter file name to delete : rrr.txt Error: rrr.txt - Operation not permitted. Enter file name to delete : foo.txt
shutil.rmtree()
Example for shutil.rmtree()
#!/usr/bin/python
import os
import sys
import shutil
# Get directory name
mydir= raw_input("Enter directory name: ")
## Try to remove tree; if failed show an error using try...except on screen
try:
shutil.rmtree(mydir)
except OSError as e:
print ("Error: %s - %s." % (e.filename, e.strerror))
You want either auto-fit
or auto-fill
inside the repeat()
function:
grid-template-columns: repeat(auto-fit, 186px);
The difference between the two becomes apparent if you also use a minmax()
to allow for flexible column sizes:
grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
This allows your columns to flex in size, ranging from 186 pixels to equal-width columns stretching across the full width of the container. auto-fill
will create as many columns as will fit in the width. If, say, five columns fit, even though you have only four grid items, there will be a fifth empty column:
Using auto-fit
instead will prevent empty columns, stretching yours further if necessary:
Big thanks to the contributors to the answers here, it pointed me in the right direction.
For the Bootstrap4 users out there, this worked for me. Sets the a link (tap target) to correct size to pass the Lighthouse Site Audit on mobiles.
<span class="small">
<a class="d-inline position-relative p-3 m-n3" style="z-index: 1;" href="/AdvancedSearch" title="Advanced Site Search using extra optional filters">Advanced Site Search</a>
</span>
If you put position:relative;
on the outer element, the inner element will place itself according to this one. Then a width:auto;
on the inner element will be the same as the width of the outer.
you could use redis with the lightning fast node_redis client. It even has built-in pubsub semantics.
For others who land here in the future (including myself), add a -name option to find specific file types, for instance: find /var -name "*.php" -mtime -1 -ls
I have developed a double Splitter (Takes two split characters) as requested Here. Could be of some value in this thread seeing its the most referenced for queries relating to string splitting.
CREATE FUNCTION uft_DoubleSplitter
(
-- Add the parameters for the function here
@String VARCHAR(4000),
@Splitter1 CHAR,
@Splitter2 CHAR
)
RETURNS @Result TABLE (Id INT,MId INT,SValue VARCHAR(4000))
AS
BEGIN
DECLARE @FResult TABLE(Id INT IDENTITY(1, 1),
SValue VARCHAR(4000))
DECLARE @SResult TABLE(Id INT IDENTITY(1, 1),
MId INT,
SValue VARCHAR(4000))
SET @String = @String+@Splitter1
WHILE CHARINDEX(@Splitter1, @String) > 0
BEGIN
DECLARE @WorkingString VARCHAR(4000) = NULL
SET @WorkingString = SUBSTRING(@String, 1, CHARINDEX(@Splitter1, @String) - 1)
--Print @workingString
INSERT INTO @FResult
SELECT CASE
WHEN @WorkingString = '' THEN NULL
ELSE @WorkingString
END
SET @String = SUBSTRING(@String, LEN(@WorkingString) + 2, LEN(@String))
END
IF ISNULL(@Splitter2, '') != ''
BEGIN
DECLARE @OStartLoop INT
DECLARE @OEndLoop INT
SELECT @OStartLoop = MIN(Id),
@OEndLoop = MAX(Id)
FROM @FResult
WHILE @OStartLoop <= @OEndLoop
BEGIN
DECLARE @iString VARCHAR(4000)
DECLARE @iMId INT
SELECT @iString = SValue+@Splitter2,
@iMId = Id
FROM @FResult
WHERE Id = @OStartLoop
WHILE CHARINDEX(@Splitter2, @iString) > 0
BEGIN
DECLARE @iWorkingString VARCHAR(4000) = NULL
SET @IWorkingString = SUBSTRING(@iString, 1, CHARINDEX(@Splitter2, @iString) - 1)
INSERT INTO @SResult
SELECT @iMId,
CASE
WHEN @iWorkingString = '' THEN NULL
ELSE @iWorkingString
END
SET @iString = SUBSTRING(@iString, LEN(@iWorkingString) + 2, LEN(@iString))
END
SET @OStartLoop = @OStartLoop + 1
END
INSERT INTO @Result
SELECT MId AS PrimarySplitID,
ROW_NUMBER() OVER (PARTITION BY MId ORDER BY Mid, Id) AS SecondarySplitID ,
SValue
FROM @SResult
END
ELSE
BEGIN
INSERT INTO @Result
SELECT Id AS PrimarySplitID,
NULL AS SecondarySplitID,
SValue
FROM @FResult
END
RETURN
Usage:
--FirstSplit
SELECT * FROM uft_DoubleSplitter('ValueA=ValueB=ValueC=ValueD==ValueE&ValueA=ValueB=ValueC===ValueE&ValueA=ValueB==ValueD===','&',NULL)
--Second Split
SELECT * FROM uft_DoubleSplitter('ValueA=ValueB=ValueC=ValueD==ValueE&ValueA=ValueB=ValueC===ValueE&ValueA=ValueB==ValueD===','&','=')
Possible Usage (Get second value of each split):
SELECT fn.SValue
FROM uft_DoubleSplitter('ValueA=ValueB=ValueC=ValueD==ValueE&ValueA=ValueB=ValueC===ValueE&ValueA=ValueB==ValueD===', '&', '=')AS fn
WHERE fn.mid = 2
For those looking for the Firebase Firestore equivalent. It's
firebase.firestore.FieldValue.serverTimestamp()
e.g.
firebase.firestore().collection("cities").add({
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
name: "Tokyo",
country: "Japan"
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
You need to git push -f
assuming that nobody has pulled the other commit before. Beware, you're changing history.
This should work:
select * from mytable where 'Journal'=ANY(pub_types);
i.e. the syntax is <value> = ANY ( <array> )
. Also notice that string literals in postresql are written with single quotes.
If you are using NumPy arrays, shape can be used. For example
>>> a = numpy.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
>>> a
array([[[ 1, 2, 3],
[ 1, 2, 3]],
[[12, 3, 4],
[ 2, 1, 3]]])
>>> a.shape
(2, 2, 3)
This can happen if you e.g. generate a new certificate request after having your old certificate request approved. The new request will cause IIS to delete the private key associated with your first certificate request, and hence when you import the (now signed) certificate associated with your first request, it will not have a private key associated with it. Since it doesn't have a private key, it can't be used for SSL binding and will not appear in the IIS manager.
You may be able to restore the private key, since it is stored more than one place on your computer:
If the certutil command returns with "-repairstore command completed successfully", the private key of your certificate was most likely recovered. You can verify this by going to the MMC certificate list and hitting F5 -- if successful, your certificate will now have a small key in its icon. You will then be able to select your certificate from IIS.
If this fails, your private key is no longer available and you need to send a new certificate signing request to the signing authority.
These one-line commands have been tested on Windows XP, Server 2012, 7 and 10 (thank you Mad Tom Vane).
x.y
in a cmd
consolefor /f "tokens=4-7 delims=[.] " %i in ('ver') do @(if %i==Version (echo %j.%k) else (echo %i.%j))
x.y.z
for /f "tokens=4-7 delims=[.] " %i in ('ver') do @(if %i==Version (echo %j.%k.%l) else (echo %i.%j.%k))
%%
instead of single %
@echo off
for /f "tokens=4-7 delims=[.] " %%i in ('ver') do (if %%i==Version (set v=%%j.%%k) else (set v=%%i.%%j))
echo %v%
Be aware that the extracted version number does not always corresponds to the Windows name release. See below an extract from the full list of Microsoft Windows versions.
10.0
Windows 10
6.3
Windows Server 2012
6.3
Windows 8.1/!\
6.2
Windows 8/!\
6.1
Windows 7/!\
6.0
Windows Vista
5.2
Windows XP x64
5.1
Windows XP
5.0
Windows 2000
4.10
Windows 98
Please also up-vote answers from Agent Gibbs and peterbh as my answer is inspired from their ideas.
In C, \0
denotes a character with value zero. The following are identical:
char a = 0;
char b = '\0';
The utility of this escape sequence is greater inside string literals, which are arrays of characters:
char arr[] = "abc\0def\0ghi\0";
(Note that this array has two zero characters at the end, since string literals include a hidden, implicit terminal zero.)
$number = sprintf('%0.2f', $numbers); // 520.89898989 -> 520.89
This will give you 2 number after decimal.
In case you have ufw enabled, remember add ftp:
> sudo ufw allow ftp
It took me 2 days to realise that I enabled ufw.
You can do
curl -sS https://getcomposer.org/installer | php
The -sS flag meaning don't show progress, do show errors
and then
php composer.phar install
Try this.
SELECT * FROM la_schedule WHERE `start_date` > '2012-11-18';
For adding margins to specified cells, you can use this custom flow layout. https://github.com/voyages-sncf-technologies/VSCollectionViewCellInsetFlowLayout/
extension ViewController : VSCollectionViewDelegateCellInsetFlowLayout
{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForItemAt indexPath: IndexPath) -> UIEdgeInsets {
if indexPath.item == 0 {
return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
}
return UIEdgeInsets.zero
}
}
This works for me
dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;
Yes -- parseFloat
.
parseFloat(document.getElementById(amtid4).innerHTML);
For formatting numbers, use toFixed
:
var num = parseFloat(document.getElementById(amtid4).innerHTML).toFixed(2);
num
is now a string with the number formatted with two decimal places.
In addition to the solution with 'aaaaaaaa' LIKE '%' || tag_name || '%'
there
are position
(reversed order of args) and strpos
.
SELECT id FROM TAG_TABLE WHERE strpos('aaaaaaaa', tag_name) > 0
Besides what is more efficient (LIKE looks less efficient, but an index might change things), there is a very minor issue with LIKE: tag_name of course should not contain %
and especially _
(single char wildcard), to give no false positives.
If you are using the fluent API, you need to set it up via the Executor
:
Executor.unregisterScheme("https");
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext,
SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Executor.registerScheme(new Scheme("https", 443, sslSocketFactory));
... where sslContext
is the SSLContext created as shown in the ZZ Coder's answer.
After that, you can do your http requests as:
String responseAsString = Request.Get("https://192.168.1.0/whatever.json")
.execute().getContent().asString();
Note: tested with HttpClient 4.2
From Twitter Bootstrap documentation:
.col-sm-*
,.col-md-*
,.col-lg-*
.This is an old, but still relevant question, and while the answers here are helpful no one answer fully addressed both of the OP's questions.
1. Do I have to install ODP.NET and Oracle client on the computer that I want to run my application?
YES - if you are using ODP.NET, Unmanaged. This is the version that you typically install when you choose "Oracle Data Provider for .NET" in the Oracle Client installer (for example). You Download this from Oracle (just google it: Oracle URLs change often).
But If you are using ODP.NET, Managed (and you probably want to use this one this instead) then No, you only need to install (or deploy) ODP.NET, Managed with the app, not the full Oracle Client. See below for details.
2. If yes, is there other way that I don't have to install them but still can run my application?
Yes, there is at least one way. And it is the Managed port of ODP.NET.
Unfortunately the usual workarounds, including ODBC, Microsoft's Oracle Provider for .NET (yes, that old, deprecated one), and the ODP.NET, Unmanaged DLL all require the Oracle client to be installed. It wasn't until our friends at Oracle gave us a nice little (~5MB) DLL that is also Managed. This means no more having to depoy 32-bit and 64-bit versions to go with 32-bit and 64-bit Oracle clients! And no more issues with assembly binding where you build against 10.0.2.1 (or whatever) but your customers install a range of clients from 9i all the way to 12c, including the 'g' ones in the middle) because you can just ship it with your app, and manage it via nuget.
But if you use ODP.NET, Managed which is available as a nuget package, then you do not need to install the Oracle Client. You only need the ODP.NET, Managed DLL. And if you were previously using the ODP.NET, Unmanaged DLL, it is very easy to switch: simply change all your references to the Managed ODP.NET (.csproj files in csharp, etc.), and then change any using
statements, for example: using Oracle.DataAccess.Client
becomes using Oracle.ManagedDataAccess.Client
and that's it! (Unless you were supposedly using some of the more advanced DB management features in the full client that are exposed in the ODP.NET, Unmanaged, which I have not done myself, so good luck with that..). And also nuke all of those annoying assemblyBindingRedirect
nodes from your app.config
/web.config
files and never sweat that junk again!
References:
Troubleshooting:
That error typically means ODP.NET was found OK, but Oracle client was not found or not installed. This could also occur when the architecture doesn't match (32-bit Oracle client is installed, but trying to use 64-bit Unmanaged ODP.NET, or vice versa). This can also happen due to permissions issues and path issues and other problems with the app domain (your web app or your EXE or whatever) not being able to find the Oracle DLLs to actually communicate with Oracle over the network (the ODP.NET Unmanaged DLLs are basically just wrappers for this that hook into ADO and stuff).
Common solutions I have found to this problem:
App is 64-bit?
App is 32-bit?
Oracle Client is already installed for the correct architecture?
ORACLE_HOME
variables, make sure Oracle can be found (newer versions may use Registry instead)ORACLE_HOME
folder. If you don't know where this is, check the Registry. I have seen cases where ASP.NET app worker process was using Network Service user and for some reason installing 32-bit and 64-bit clients side by side resulted in the permissions being removed from the first client for the Authorized Users
group.. fixing perms on the home folder fixed this.Type Cast to List
job_reports = JobReport.objects.filter(job_id=job_id, status=1).values('id', 'name')
json.dumps(list(job_reports))
The execmgr.log
will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log
and some clients will have outdated appenforce
or no ppenforce.log
files.
execmgr.log
also shows required hidden uninstall actions as well.
You may want to save the blog link. I still reference it from time to time.
An example of how to implement it:
public bool ValidateSocialSecNumber(string socialSecNumber)
{
//Accepts only 10 digits, no more no less. (Like Mike's answer)
Regex pattern = new Regex(@"(?<!\d)\d{10}(?!\d)");
if(pattern.isMatch(socialSecNumber))
{
//Do something
return true;
}
else
{
return false;
}
}
You could've also done it in another way by e.g. using Match
and then wrapping a try-catch block around the pattern matching. However, if a wrong input is given quite often, it's quite expensive to throw an exception. Thus, I prefer the above way, in simple cases at least.
The error is here:
hasLetter("a",words[]);
You are passing the first item of words
, instead of the array.
Instead, pass the array to the function:
hasLetter("a",words);
Problem solved!
Here's a breakdown of what the problem was:
I'm guessing in your browser (chrome throws a different error), words[] == words[0]
, so when you call hasLetter("a",words[]);
, you are actually calling hasLetter("a",words[0]);
. So, in essence, you are passing the first item of words to your function, not the array as a whole.
Of course, because words
is just an empty array, words[0]
is undefined
. Therefore, your function call is actually:
hasLetter("a", undefined);
which means that, when you try to access d[ascii]
, you are actually trying to access undefined[0]
, hence the error.
It might also be an OpenJDK bug... (not in this case but it is the same error)
If somebody like me stumbles upon this answer regarding the
java.lang.IllegalArgumentException: Comparison method violates its general contract!
then it might also be a bug in the Java-Version. I have a compareTo running since several years now in some applications. But suddenly it stopped working and throws the error after all compares were done (i compare 6 Attributes before returning "0").
Now I just found this Bugreport of OpenJDK:
<select id="ddlViewBy">
<option value="value">text</option>
</select>
JQuery
var txt = $("#ddlViewBy option:selected").text();
var val = $("#ddlViewBy option:selected").val();
In Java 8 you can simply do
ZonedDateTime.now().toInstant().toEpochMilli()
returns : the number of milliseconds since the epoch of 1970-01-01T00:00:00Z
The accepted answer is not complete without the remainder of instructions (paraphrased below) from the forum thread linked to:
cd /etc/php5/conf.d
cat > sqlite3.ini
# configuration for php SQLite3 module
extension=sqlite3.so
^D
sudo /etc/init.d/apache2 restart
As stated in one other answer Docker doesn't play nice with a VPN. If you're using Nordvpn you have to disable "Invisibility on LAN" and probably "Internet Kill Switch".
If you've done so it should work even with the VPN active.
This because the input that the user inserts into the JOptionPane
is a String
and it is stored and returned as a String
.
Java cannot convert between strings and number by itself, you have to use specific functions, just use:
int ans = Integer.parseInt(JOptionPane.showInputDialog(...))
For a single boxplot:
import seaborn as sb
sb.boxplot(data=Array).set_title('Title')
For more boxplot in the same plot:
import seaborn as sb
sb.boxplot(data=ArrayofArray).set_title('Title')
e.g.
import seaborn as sb
myarray=[78.195229, 59.104538, 19.884109, 25.941648, 72.234825, 82.313911]
sb.boxplot(data=myarray).set_title('myTitle')
No, IIRC there is no getopt() on Windows.
Boost, however, has the program_options library... which works okay. It will seem like overkill at first, but it isn't terrible, especially considering it can handle setting program options in configuration files and environment variables in addition to command line options.
You should specify formGroupName
for nested controls
<div class="panel panel-default" formGroupName="address"> <== add this
<div class="panel-heading">Contact Info</div>
There are 3 ways to that, i mention them in order of being the better way...
1-HTML way:
<input type="text" autocomplete="false" />
2-Javascript way:
document.getElementById("input-id").getAttribute("autocomplete") = "off";
3-jQuery way:
$('input').attr('autocomplete','off');
You need to use setTimeout and pass it a callback function. The reason you can't use sleep in javascript is because you'd block the entire page from doing anything in the meantime. Not a good plan. Use Javascript's event model and stay happy. Don't fight it!
I have tried several solutions today, the one working best for me is Jo-Geek/jQuery-ResizableColumns. Is is very simple, yet it handles tables placed in flex containers, which many of the other ones fail with.
<table class="resizable">
</table>
$('table.resizable').resizableColumns();
$(function() {_x000D_
$('table.resizable').resizableColumns();_x000D_
})
_x000D_
body {_x000D_
margin: 0px;_x000D_
}_x000D_
_x000D_
table {_x000D_
width: 100%;_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://jo-geek.github.io/jQuery-ResizableColumns/demo/resizableColumns.min.js"></script>_x000D_
<table class="resizable" border="true">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>col 1</th><th>col 2</th><th>col 3</th><th>col 4</th>_x000D_
</tr>_x000D_
</thead>_x000D_
_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
there are 600 million ticks per minute. ticksperminute
Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}
In case anyone else is looking to simply overwrite everything from one branch (say master) with the contents of another, there's an easier way:
git merge origin/master --strategy=ours
Thanks to https://stackoverflow.com/a/1295232/560114
Or for the other way around, see Is there a "theirs" version of "git merge -s ours"?
By default a span
is an inline
element... so that's not the default behavior.
You can make the span
behave that way by adding display: block;
to your CSS.
span {
display: block;
width: 100px;
}
A simple way to find this out in Windows is to run SQLPlus from your Oracle homes's bin directory and then check Task Manager. If it is a 32-bit version of SQLPlus, you'll see a process on the Processes tab that looks like this:
sqlplus.exe *32
If it is 64-bit, the process will look like this:
sqlplus.exe
From Go 1.5 there's the "vendor experiment" that helps you manage dependencies. As of Go 1.6 this is no longer an experiment. Theres also some other options on the Go wiki..
Edit: as mentioned in this answer gopkg.in is a good option for pinning github-depdencies pre-1.5.
In order to set the value of integer variable we simply assign the value to it.
eg g1val = 0
where as set keyword is used to assign value to object.
Sub test()
Dim g1val, g2val As Integer
g1val = 0
g2val = 0
For i = 3 To 18
If g1val > Cells(33, i).Value Then
g1val = g1val
Else
g1val = Cells(33, i).Value
End If
Next i
For j = 32 To 57
If g2val > Cells(31, j).Value Then
g2val = g2val
Else
g2val = Cells(31, j).Value
End If
Next j
End Sub
tl;dr for folks looking here for an ISO formatted date:
instead of using something like '%Y-%m-%d %H:%M:%S.%03d%z', create your own class as @unutbu indicated. Here's one for iso date format:
import logging
from time import gmtime, strftime
class ISOFormatter(logging.Formatter):
def formatTime(self, record, datefmt=None):
t = strftime("%Y-%m-%dT%H:%M:%S", gmtime(record.created))
z = strftime("%z",gmtime(record.created))
s = "%s.%03d%s" % (t, record.msecs,z)
return s
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
logger.addHandler(console)
formatter = ISOFormatter(fmt='%(asctime)s - %(module)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)
logger.debug('Jackdaws love my big sphinx of quartz.')
#2020-10-23T17:25:48.310-0800 - <stdin> - DEBUG - Jackdaws love my big sphinx of quartz.
Hmm... actually i dont know how this solved it? But the following steps solved it for me:
find / -name 'config.m4'
Now look if the config.m4 is anywhere in a folder of that stuff you want to phpize. Go to that folder and run phpize directly in there.
In chrome it is possible to use location.ancestorOrigins It will return all parent urls
The simplest way is to use the following pattern:
http://[server]/[site]/[ListName]/[Folder]/[SubFolder]
To place a shortcut to a document library:
$scope.changePass = function(data){_x000D_
_x000D_
if(data.txtNewConfirmPassword !== data.txtNewPassword){_x000D_
$scope.confirmStatus = true;_x000D_
}else{_x000D_
$scope.confirmStatus = false;_x000D_
}_x000D_
};
_x000D_
<form class="list" name="myForm">_x000D_
<label class="item item-input"> _x000D_
<input type="password" placeholder="???????????????????" ng-model="data.txtCurrentPassword" maxlength="5" required>_x000D_
</label>_x000D_
<label class="item item-input">_x000D_
<input type="password" placeholder="???????????????" ng-model="data.txtNewPassword" maxlength="5" ng-minlength="5" name="checknawPassword" ng-change="changePass(data)" required>_x000D_
</label>_x000D_
<label class="item item-input">_x000D_
<input type="password" placeholder="????????????????????????" ng-model="data.txtNewConfirmPassword" maxlength="5" ng-minlength="5" name="checkConfirmPassword" ng-change="changePass(data)" required>_x000D_
</label> _x000D_
<div class="spacer" style="width: 300px; height: 5px;"></div> _x000D_
<span style="color:red" ng-show="myForm.checknawPassword.$error.minlength || myForm.checkConfirmPassword.$error.minlength">??????????????????? 5 ????</span><br>_x000D_
<span ng-show="confirmStatus" style="color:red">?????????????????????</span>_x000D_
<br>_x000D_
<button class="button button-positive button-block" ng-click="saveChangePass(data)" ng-disabled="myForm.$invalid || confirmStatus">???????</button>_x000D_
</form>
_x000D_
Add something like this to lib/__init__.py
from .helperclass import Helper
now you can import it directly:
from lib import Helper
You can save a page using php, like this:
$_SESSION['current_page'] = $_SERVER['REQUEST_URI']
And return to the page with:
header("Location: ". $_SESSION['current_page'])
for (i>0; i--;)
is probably wrong and should be
for (; i>0; i--)
instead. Note where I put the semicolons. The condition goes in the middle, not at the start.
A rather nice addition to @MartijnPieters answer is to get back a dictionary sorted by occurrence since Collections.most_common
only returns a tuple. I often couple this with a json output for handy log files:
from collections import Counter, OrderedDict
x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())
With the output:
OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
"c": 7,
"a": 5,
"b": 3
}
@Table's name attribute is the actual table name. @Entitiy's name is useful if you have two @Entity classes with the same name and you need a way to differentiate them when running queries.
This is supposed to print the ASCII value of the character, as %d
is the escape sequence for an integer. So the value given as argument of printf
is taken as integer when printed.
char ch = 'a';
printf("%d", ch);
Same holds for printf("%d", '\0');
, where the NULL character is interpreted as the 0 integer.
Finally, sizeof('\n')
is 4 because in C, this notation for characters stands for the corresponding ASCII integer. So '\n' is the same as 10 as an integer.
It all depends on the interpretation you give to the bytes.
Better Solution compared to trimming the value of the textarea.
$('textarea[maxlength]').live('keypress', function(e) {
var maxlength = $(this).attr('maxlength');
var val = $(this).val();
if (val.length > maxlength) {
return false;
}
});
A lot depends on what kind of project it is. WTP's JSP support either expects the JSP files to be under the same folder that's the parent of the WEB-INF folder (src/web, which it will then treat as "/" to find TLDs), or to have project metadata set up to help it know where that root is (done for you in a Dynamic Web Project through Deployment Assembly). How are you referring to the TLD file, and where is the JSP file located?
And maybe I missed the original post to the Eclipse forums; the one I saw was posted a full day after this one.
You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:
[NSString stringWithFormat:@"my dictionary is %@", aDictionary];
or
NSLog(@"My dictionary is %@", aDictionary);
Check out Apache commons-net, which contains FTP utilities. Off the top of my head I'm not sure if it meets all of your requirements, but it's certainly free!
Dim FindRow as Range
Set FindRow = Range("A:A").Find(What:="ProjTemp", _' This is what you are searching for
After:=.Cells(.Cells.Count), _ ' This is saying after the last cell in the_
' column i.e. the first
LookIn:=xlValues, _ ' this says look in the values of the cell not the formula
LookAt:=xlWhole, _ ' This look s for EXACT ENTIRE MATCH
SearchOrder:=xlByRows, _ 'This look down the column row by row
'Larger Ranges with multiple columns can be set to
' look column by column then down
MatchCase:=False) ' this says that the search is not case sensitive
If Not FindRow Is Nothing Then ' if findrow is something (Prevents Errors)
FirstRow = FindRow.Row ' set FirstRow to the first time a match is found
End If
If you would like to get addition ones you can use:
Do Until FindRow Is Nothing
Set FindRow = Range("A:A").FindNext(after:=FindRow)
If FindRow.row = FirstRow Then
Exit Do
Else ' Do what you'd like with the additional rows here.
End If
Loop
Referring to the Microsoft example: [https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.enableraisingevents?view=netframework-4.8]
Best would be to set:
myProcess.EnableRaisingEvents = true;
otherwiese the Code will be blocked. Also no additional properties needed.
// Start a process and raise an event when done.
myProcess.StartInfo.FileName = fileName;
// Allows to raise event when the process is finished
myProcess.EnableRaisingEvents = true;
// Eventhandler wich fires when exited
myProcess.Exited += new EventHandler(myProcess_Exited);
// Starts the process
myProcess.Start();
// Handle Exited event and display process information.
private void myProcess_Exited(object sender, System.EventArgs e)
{
Console.WriteLine(
$"Exit time : {myProcess.ExitTime}\n" +
$"Exit code : {myProcess.ExitCode}\n" +
$"Elapsed time : {elapsedTime}");
}
This exact error happened to me today on an Ubuntu virtual machine running on VirtualBox. I tried most of the solutions shown above before I noticed that I had resumed from a very old suspended state, and my clock was off by many days.
Updating the clock immediately fixed my issue. Here's the command I used in my case:
sudo service ntp stop && sudo ntpdate pool.ntp.org && sudo service ntp start
You can use getChanges()
on Eloquent model even after persisting.
So this isn't what the requester was asking for but it is the answer to "SQL selecting rows by most recent date".
Modified from http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row
SELECT t.chargeId, t.chargeType, t.serviceMonth FROM(
SELECT chargeId,MAX(serviceMonth) AS serviceMonth
FROM invoice
GROUP BY chargeId) x
JOIN invoice t ON x.chargeId =t.chargeId
AND x.serviceMonth = t.serviceMonth
Following Glens idea, here it goes another possibility. It would allow you to scroll inside the div, but would prevent the body to scroll with it, when the div scroll ends. However, it seems to accumulate too many preventDefault if you scroll too much, and then it creates a lag if you want to scroll up. Does anybody have a suggestion to fix that?
$(".scrollInsideThisDiv").bind("mouseover",function(){
var bodyTop = document.body.scrollTop;
$('body').on({
'mousewheel': function(e) {
if (document.body.scrollTop == bodyTop) return;
e.preventDefault();
e.stopPropagation();
}
});
});
$(".scrollInsideThisDiv").bind("mouseleave",function(){
$('body').unbind("mousewheel");
});
An Int-based pow function that computes the value directly via bit shift for base 2 in Swift 5:
func pow(base: Int, power: UInt) -> Int {
if power == 0 { return 1 }
// for base 2, use a bit shift to compute the value directly
if base == 2 { return 2 << Int(power - 1) }
// otherwise multiply base repeatedly to compute the value
return repeatElement(base, count: Int(power)).reduce(1, *)
}
(Make sure the result is within the range of Int - this does not check for the out of bounds case)
@alessioalex answer is a perfect demo for fresh node user. But anyway, it's hard to write checkAuth middleware into all routes except login, so it's better to move the checkAuth from every route to one entry with app.use. For example:
function checkAuth(req, res, next) {
// if logined or it's login request, then go next route
if (isLogin || (req.path === '/login' && req.method === 'POST')) {
next()
} else {
res.send('Not logged in yet.')
}
}
app.use('/', checkAuth)
You can use the following in your controller:
return redirect('login')->with(Auth::logout());
Try this:
$('.checkAll').on('click', function(e) {
$('.cb-element').prop('checked', $(e.target).prop('checked'));
});
e
is the event generated when you do click
, and e.target
is the element clicked (.checkAll
),
so you only have to put the property checked
of elements with class .cb-element
like that of element
with class .checkAll`.
PS: Excuse my bad English!
I worked so much, I hope my effort might help you out.
Just paste this into your SSMS and press F5:
Declare @Object as Int;
DECLARE @hr int
Declare @json as table(Json_Table nvarchar(max))
Exec @hr=sp_OACreate 'MSXML2.ServerXMLHTTP.6.0', @Object OUT;
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'open', NULL, 'get',
'http://overpass-api.de/api/interpreter?data=[out:json];area[name=%22Auckland%22]-%3E.a;(node(area.a)[amenity=cinema];way(area.a)[amenity=cinema];rel(area.a)[amenity=cinema];);out;', --Your Web Service Url (invoked)
'false'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'send'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'responseText', @json OUTPUT
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
INSERT into @json (Json_Table) exec sp_OAGetProperty @Object, 'responseText'
-- select the JSON string
select * from @json
-- Parse the JSON string
SELECT * FROM OPENJSON((select * from @json), N'$.elements')
WITH (
[type] nvarchar(max) N'$.type' ,
[id] nvarchar(max) N'$.id',
[lat] nvarchar(max) N'$.lat',
[lon] nvarchar(max) N'$.lon',
[amenity] nvarchar(max) N'$.tags.amenity',
[name] nvarchar(max) N'$.tags.name'
)
EXEC sp_OADestroy @Object
This query will give you 3 results:
1. Catch the error in case something goes wrong (don't panic, it will always show you an error above 4000 characters because NVARCHAR(MAX) can only store till 4000 characters)
2. Put the JSON into a string (which is what we want)
3. BONUS: parse the JSON and nicely store the data into a table (how cool is that?)
Based on my experience on Ubuntu 18.04:
1. Check Jupyter installation
first of all make sure that you have installed and/or upgraded Jupyter-notebook (also for virtual-environment):
pip install --upgrade jupyter
2. Change the Access Permissions (Use with Caution!)
then try to change the access permission for you
sudo chmod -R 777 ~/.local
where 777 is a three-digit representation of the access permission. In sense that each of the digits representing short format of the binary one (e.g. 7 for 111). So, 777 means that we set permission access to read, write and execute to 1 for all users (Owner, Group or Other)
Example.1
777 : 111 111 111
or
777 : rwx-rwx-rwx
Example.2
755 : 111 101 101
(More about chmod : File Permissions and attributes)
3. Run jupyter
afterwards run your jupyter notebook:
jupyter-notebook
Note: (These steps also solve your Visual-Studio code (VS-Code) problems regarding permissions while using ipython and jupyter for python-interactive-console.)
i think this add new property in desired type without having to set a primitive value, like when property defined in class definition
var x = new ExpandoObject();
x.NewProp = default(string)
maybe something like
$('div#someDiv').css("height", "auto");
Change the name of the .CSS file Load the page and then change the file again in the original name it works for me.
Apart from read the big file line by line, you also can read it chunk by chunk. For more refer to this article
var offset = 0;
var chunkSize = 2048;
var chunkBuffer = new Buffer(chunkSize);
var fp = fs.openSync('filepath', 'r');
var bytesRead = 0;
while(bytesRead = fs.readSync(fp, chunkBuffer, 0, chunkSize, offset)) {
offset += bytesRead;
var str = chunkBuffer.slice(0, bytesRead).toString();
var arr = str.split('\n');
if(bytesRead = chunkSize) {
// the last item of the arr may be not a full line, leave it to the next chunk
offset -= arr.pop().length;
}
lines.push(arr);
}
console.log(lines);
This is the shortest, most practical I can comeup with without importing extra modules.
text = "hello cruel world. This is a sample text"
d = dict.fromkeys(text, 0)
for c in text: d[c] += 1
print d['a'] would output 2
And it's also fast.
setState(updater[, callback])
is an async function:
https://facebook.github.io/react/docs/react-component.html#setstate
You can execute a function after setState is finishing using the second param callback
like:
this.setState({
someState: obj
}, () => {
this.afterSetStateFinished();
});
The same can be done with hooks in React functional component:
https://github.com/the-road-to-learn-react/use-state-with-callback#usage
Look at useStateWithCallbackLazy:
import { useStateWithCallbackLazy } from 'use-state-with-callback';
const [count, setCount] = useStateWithCallbackLazy(0);
setCount(count + 1, () => {
afterSetCountFinished();
});
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_
You can try U2U Query Builder http://www.u2u.net/res/Tools/CamlQueryBuilder.aspx you can use their API U2U.SharePoint.CAML.Server.dll and U2U.SharePoint.CAML.Client.dll
I didn't use them but I'm sure it will help you achieving your task.
For MultiIndex you can extract its subindex using
df['si_name'] = R.index.get_level_values('si_name')
where si_name
is the name of the subindex.
If
side_effect_func
is a function then whatever that function returns is what calls to the mock return. Theside_effect_func
function is called with the same arguments as the mock. This allows you to vary the return value of the call dynamically, based on the input:>>> def side_effect_func(value): ... return value + 1 ... >>> m = MagicMock(side_effect=side_effect_func) >>> m(1) 2 >>> m(2) 3 >>> m.mock_calls [call(1), call(2)]
We can use _.difference
function to see if there is any difference or not.
function isSame(arrayOne, arrayTwo) {
var a = _.uniq(arrayOne),
b = _.uniq(arrayTwo);
return a.length === b.length &&
_.isEmpty(_.difference(b.sort(), a.sort()));
}
// examples
console.log(isSame([1, 2, 3], [1, 2, 3])); // true
console.log(isSame([1, 2, 4], [1, 2, 3])); // false
console.log(isSame([1, 2], [2, 3, 1])); // false
console.log(isSame([2, 3, 1], [1, 2])); // false
// Test cases pointed by Mariano Desanze, Thanks.
console.log(isSame([1, 2, 3], [1, 2, 2])); // false
console.log(isSame([1, 2, 2], [1, 2, 2])); // true
console.log(isSame([1, 2, 2], [1, 2, 3])); // false
I hope this will help you.
Adding example link at StackBlitz
I think Semaphore is what you are looking for, it will block the main process after counting down to 0. Sample code:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# simulate a time-consuming task by sleeping
time.sleep(5)
# `release` will add 1 to `sema`, allowing other
# processes blocked on it to continue
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
# once 20 processes are running, the following `acquire` call
# will block the main process since `sema` has been reduced
# to 0. This loop will continue only after one or more
# previously created processes complete.
sema.acquire()
p = Process(target=f, args=(i, sema))
all_processes.append(p)
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The following code is more structured since it acquires and releases sema
in the same function. However, it will consume too much resources if total_task_num
is very large:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# `sema` is acquired and released in the same
# block of code here, making code more readable,
# but may lead to problem.
sema.acquire()
time.sleep(5)
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
p = Process(target=f, args=(i, sema))
all_processes.append(p)
# the following line won't block after 20 processes
# have been created and running, instead it will carry
# on until all 1000 processes are created.
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The above code will create total_task_num
processes but only concurrency
processes will be running while other processes are blocked, consuming precious system resources.
Maybe, you need to specify more exactly what didn't work and in what environment you are.
As to the claim that the dot is special in a charackter class, this is not true in every programming environment. For example the following perl script
use warnings;
use strict;
my $str = '!!!.###';
$str =~ s/[A-Za-z_.]/X/g;
print "$str\n";
produces
!!!X###
Let’s take a simple vector class:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
We want to have a method which calculates the length. What would it look like if we wanted to define it inside the class?
def length(self):
return math.sqrt(self.x ** 2 + self.y ** 2)
What should it look like when we were to define it as a global method/function?
def length_global(vector):
return math.sqrt(vector.x ** 2 + vector.y ** 2)
So the whole structure stays the same. How can me make use of this? If we assume for a moment that we hadn’t written a length
method for our Vector
class, we could do this:
Vector.length_new = length_global
v = Vector(3, 4)
print(v.length_new()) # 5.0
This works because the first parameter of length_global
, can be re-used as the self
parameter in length_new
. This would not be possible without an explicit self
.
Another way of understanding the need for the explicit self
is to see where Python adds some syntactical sugar. When you keep in mind, that basically, a call like
v_instance.length()
is internally transformed to
Vector.length(v_instance)
it is easy to see where the self
fits in. You don't actually write instance methods in Python; what you write is class methods which must take an instance as a first parameter. And therefore, you’ll have to place the instance parameter somewhere explicitly.
I know this is quite out of date, but this might still be useful for those coming late to the party. (EDIT: updated since this still gets traffic and @Goozak has pointed out in the comments that my original analysis of the sample was incorrect as well.)
I pulled this from the example code in your link:
IF !%1==! GOTO VIEWDATA
REM IF NO COMMAND-LINE ARG...
FIND "%1" C:\BOZO\BOOKLIST.TXT
GOTO EXIT0
REM PRINT LINE WITH STRING MATCH, THEN EXIT.
:VIEWDATA
TYPE C:\BOZO\BOOKLIST.TXT | MORE
REM SHOW ENTIRE FILE, 1 PAGE AT A TIME.
:EXIT0
!%1==!
is simply an idiomatic use of ==
intended to verify that the thing on the left, that contains your variable, is different from the thing on the right, that does not. The !
in this case is just a character placeholder. It could be anything. If %1
has content, then the equality will be false, if it does not you'll just be comparing !
to !
and it will be true.
!==!
is not an operator, so writing "asdf" !==! "fdas"
is pretty nonsensical.
The suggestion to use if not "asdf" == "fdas"
is definitely the way to go.
You can try
document.getElementById("textboxid").readOnly = true;
Your css with doesn't have any effect as the outer element doesn't have a width defined (and body is missing as well).
A different approach is to deliver already scaled images. http://www.sencha.com/products/io/ for example delivers the image already scaled down depending on the viewing device.
VBA has the collection object:
Dim c As Collection
Set c = New Collection
c.Add "Data1", "Key1"
c.Add "Data2", "Key2"
c.Add "Data3", "Key3"
'Insert data via key into cell A1
Range("A1").Value = c.Item("Key2")
The Collection
object performs key-based lookups using a hash so it's quick.
You can use a Contains()
function to check whether a particular collection contains a key:
Public Function Contains(col As Collection, key As Variant) As Boolean
On Error Resume Next
col(key) ' Just try it. If it fails, Err.Number will be nonzero.
Contains = (Err.Number = 0)
Err.Clear
End Function
Edit 24 June 2015: Shorter Contains()
thanks to @TWiStErRob.
Edit 25 September 2015: Added Err.Clear()
thanks to @scipilot.
Compromise minimum solution:
| One | Two | Three | Four | Five | Six
| -
| Span <td colspan=3>triple <td colspan=2>double
So you can omit closing </td>
for speed, ?r can leave for consistency.
Result from http://markdown-here.com/livedemo.html :
Works in Jupyter Markdown.
As of 2019 year all pipes in the second line are compulsory in Jupyter Markdown.
| One | Two | Three | Four | Five | Six
|-|-|-|-|-|-
| Span <td colspan=3>triple <td colspan=2>double
minimally:
One | Two | Three | Four | Five | Six
-|||||-
Span <td colspan=3>triple <td colspan=2>double
For folks using Python 3.0+ (which should be everyone now):
Unfortunately, MySQL-Python 1.2.5 does not support Python 3.0+ yet (which is kinda unreasonable IMHO, Python 3+ has been out for a while). Reference : https://pypi.python.org/pypi/MySQL-python/1.2.5
So, my workaround is to use Oracle's MySQL connector. In settings.py, change DATABASE's 'ENGINE' field to: 'ENGINE': 'mysql.connector.django',
More info could be found in the last paragraph of the first answer to this question: Setting Django up to use MySQL
Hope this helps!!
Or you can do
public class Person
{
public Person(int id)
{
this.Id=id;
}
public string Name { get; set; }
public int Id { get; private set; }
public int Age { get; set; }
}
Taken from here - Introduction to Time Complexity of an Algorithm
In computer science, the time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the string representing the input.
The time complexity of an algorithm is commonly expressed using big O notation, which excludes coefficients and lower order terms. When expressed this way, the time complexity is said to be described asymptotically, i.e., as the input size goes to infinity.
For example, if the time required by an algorithm on all inputs of size n is at most 5n3 + 3n, the asymptotic time complexity is O(n3). More on that later.
Few more Examples:
An algorithm is said to run in constant time if it requires the same amount of time regardless of the input size.
Examples:
An algorithm is said to run in linear time if its time execution is directly proportional to the input size, i.e. time grows linearly as input size increases.
Consider the following examples, below I am linearly searching for an element, this has a time complexity of O(n).
int find = 66;
var numbers = new int[] { 33, 435, 36, 37, 43, 45, 66, 656, 2232 };
for (int i = 0; i < numbers.Length - 1; i++)
{
if(find == numbers[i])
{
return;
}
}
More Examples:
An algorithm is said to run in logarithmic time if its time execution is proportional to the logarithm of the input size.
Example: Binary Search
Recall the "twenty questions" game - the task is to guess the value of a hidden number in an interval. Each time you make a guess, you are told whether your guess is too high or too low. Twenty questions game implies a strategy that uses your guess number to halve the interval size. This is an example of the general problem-solving method known as binary search
An algorithm is said to run in quadratic time if its time execution is proportional to the square of the input size.
Examples:
you can do like this also
long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 }};
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i,j]+" ");
}
Console.WriteLine();
}
if you are calling from static
method, use :
TestGameTable.class.getClassLoader().getResource("dice.jpg");
You've not shown how you're creating the string 2016-01-12T23:00:00.000Z
, but I assume via .format()
.
Anyway, .set()
is using your local time zone, but the Z
in the time string indicates zero time, otherwise known as UTC.
https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators
So I assume your local timezone is 23 hours from UTC?
saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format()
call that outputs using your local timezone, rather than UTC.
http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/
Add this ModelCollection.cs to your Models
using System;
using System.Collections.Generic;
namespace ModelContainer
{
public class ModelCollection
{
private Dictionary<Type, object> models = new Dictionary<Type, object>();
public void AddModel<T>(T t)
{
models.Add(t.GetType(), t);
}
public T GetModel<T>()
{
return (T)models[typeof(T)];
}
}
}
Controller:
public class SampleController : Controller
{
public ActionResult Index()
{
var model1 = new Model1();
var model2 = new Model2();
var model3 = new Model3();
// Do something
var modelCollection = new ModelCollection();
modelCollection.AddModel(model1);
modelCollection.AddModel(model2);
modelCollection.AddModel(model3);
return View(modelCollection);
}
}
The View:
enter code here
@using Models
@model ModelCollection
@{
ViewBag.Title = "Model1: " + ((Model.GetModel<Model1>()).Name);
}
<h2>Model2: @((Model.GetModel<Model2>()).Number</h2>
@((Model.GetModel<Model3>()).SomeProperty