A quick example:
List<List<string>> myList = new List<List<string>>();
myList.Add(new List<string> { "a", "b" });
myList.Add(new List<string> { "c", "d", "e" });
myList.Add(new List<string> { "qwerty", "asdf", "zxcv" });
myList.Add(new List<string> { "a", "b" });
// To iterate over it.
foreach (List<string> subList in myList)
{
foreach (string item in subList)
{
Console.WriteLine(item);
}
}
Is that what you were looking for? Or are you trying to create a new class
that extends List<T>
that has a member that is a `List'?
There is a ToObject method now.
var obj = jsonObject["date_joined"];
var result = obj.ToObject<DateTime>();
It also works with any complex type, and obey to JsonPropertyAttribute rules
var result = obj.ToObject<MyClass>();
public class MyClass
{
[JsonProperty("date_field")]
public DateTime MyDate {get;set;}
}
-is and -as operators requires a type you can compare against. If you're not sure what the type might be, try to evaluate the content (partial type list):
(Invoke-Expression '1.5').GetType().Name -match 'byte|short|int32|long|sbyte|ushort|uint32|ulong|float|double|decimal'
Good or bad, it can work against hex values as well (Invoke-Expression '0xA' ...)
The difference is that the uint
and ulong
are unsigned data types, meaning the range is different: They do not accept negative values:
int range: -2,147,483,648 to 2,147,483,647
uint range: 0 to 4,294,967,295
long range: –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong range: 0 to 18,446,744,073,709,551,615
Try this:
#ifdef _WIN64
// 64 bit code
#elif _WIN32
// 32 bit code
#else
if(sizeof(void*)==4)
// 32 bit code
else
// 64 bit code
#endif
You can do it for a const reference, but not for a non-const one. This is because C++ does not allow a temporary (the default value in this case) to be bound to non-const reference.
One way round this would be to use an actual instance as the default:
static int AVAL = 1;
void f( int & x = AVAL ) {
// stuff
}
int main() {
f(); // equivalent to f(AVAL);
}
but this is of very limited practical use.
In C, I tested the i && !(i & (i - 1)
trick and compared it with __builtin_popcount(i)
, using gcc on Linux, with the -mpopcnt flag to be sure to use the CPU's POPCNT instruction. My test program counted the # of integers between 0 and 2^31 that were a power of two.
At first I thought that i && !(i & (i - 1)
was 10% faster, even though I verified that POPCNT was used in the disassembly where I used__builtin_popcount
.
However, I realized that I had included an if statement, and branch prediction was probably doing better on the bit twiddling version. I removed the if and POPCNT ended up faster, as expected.
Results:
Intel(R) Core(TM) i7-4771 CPU max 3.90GHz
Timing (i & !(i & (i - 1))) trick
30
real 0m13.804s
user 0m13.799s
sys 0m0.000s
Timing POPCNT
30
real 0m11.916s
user 0m11.916s
sys 0m0.000s
AMD Ryzen Threadripper 2950X 16-Core Processor max 3.50GHz
Timing (i && !(i & (i - 1))) trick
30
real 0m13.675s
user 0m13.673s
sys 0m0.000s
Timing POPCNT
30
real 0m13.156s
user 0m13.153s
sys 0m0.000s
Note that here the Intel CPU seems slightly slower than AMD with the bit twiddling, but has a much faster POPCNT; the AMD POPCNT doesn't provide as much of a boost.
popcnt_test.c:
#include "stdio.h"
// Count # of integers that are powers of 2 up to 2^31;
int main() {
int n;
for (int z = 0; z < 20; z++){
n = 0;
for (unsigned long i = 0; i < 1<<30; i++) {
#ifdef USE_POPCNT
n += (__builtin_popcount(i)==1); // Was: if (__builtin_popcount(i) == 1) n++;
#else
n += (i && !(i & (i - 1))); // Was: if (i && !(i & (i - 1))) n++;
#endif
}
}
printf("%d\n", n);
return 0;
}
Run tests:
gcc popcnt_test.c -O3 -o test.exe
gcc popcnt_test.c -O3 -DUSE_POPCNT -mpopcnt -o test-popcnt.exe
echo "Timing (i && !(i & (i - 1))) trick"
time ./test.exe
echo
echo "Timing POPCNT"
time ./test-opt.exe
Are you sure the page you are redirecting too doesn't have a redirection within that if no session data is found? That could be your problem
Also yes always add whitespace like @Peter O suggested.
Delete
operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirementsInsert
for arrays is basically Set
as mentioned in the beginning public bool roomSelected()
{
int a = 0;
foreach (RadioButton rb in GroupBox1.Controls)
{
if (rb.Checked == true)
{
a = 1;
}
}
if (a == 1)
{
return true;
}
else
{
return false;
}
}
this how I solved my problem
This is documented on ?logical
. The pertinent section of which is:
Details:
‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants
in the R language, whereas ‘T’ and ‘F’ are global variables whose
initial values set to these. All four are ‘logical(1)’ vectors.
Logical vectors are coerced to integer vectors in contexts where a
numerical value is required, with ‘TRUE’ being mapped to ‘1L’,
‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.
The second paragraph there explains the behaviour you are seeing, namely 5 == 1L
and 5 == 0L
respectively, which should both return FALSE
, where as 1 == 1L
and 0 == 0L
should be TRUE for 1 == TRUE
and 0 == FALSE
respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE
and FALSE
in R, i.e. what numeric values they take when coerced to numeric.
However, only TRUE
is guaranteed to the be TRUE
:
> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE
isTRUE
is a wrapper for identical(x, TRUE)
, and from ?isTRUE
we note:
Details:
....
‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
true if and only if ‘x’ is a length-one logical vector whose only
element is ‘TRUE’ and which has no attributes (not even names).
So by the same virtue, only FALSE
is guaranteed to be exactly equal to FALSE
.
> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE
If this concerns you, always use isTRUE()
or identical(x, FALSE)
to check for equivalence with TRUE
and FALSE
respectively. ==
is not doing what you think it is.
It also happens when the view returned by onCreateView() isn't the view that was inflated.
Example:
View rootView = inflater.inflate(R.layout.my_fragment, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.text_view);
textView.setText("Some text.");
return textView;
Fix:
return rootView;
Instead of:
return textView; // or whatever you returned
There's no need for "else" in this case:
IF EXISTS(SELECT * FROM table1 WHERE Name='John' ) return 1
return 0
Scenario:
I have a navigation menu like this. Note: Link <a> is child of list item <li>
. I wanted to change the background of the selected list item and remove the background color of unselected list item.
<nav>
<ul>
<li><a href="#">Intro</a></li>
<li><a href="#">Size</a></li>
<li><a href="#">Play</a></li>
<li><a href="#">Food</a></li>
</ul>
<div class="clear"></div>
</nav>
I tried to add a class .active into the list item using jQuery but it was not working
.active
{
background-color: #480048;
}
$("nav li a").click(function () {
$(this).parent().addClass("active");
$(this).parent().siblings().removeClass("active");
});
Solution:
Basically, using .active class changing the background-color of list item does not work. So I changed the css class name from .active to "nav li.active a" so using the same javascript it will add the .active class into the selected list item. Now if the list item <li>
has .active class then css will change the background color of the child of that list item <a>.
nav li.active a
{
background-color: #480048;
}
You can simply place a forward declaration of your second()
function in your main.cpp
above main()
. If your second.cpp
has more than one function and you want all of it in main()
, put all the forward declarations of your functions in second.cpp
into a header file and #include
it in main.cpp
.
Like this-
Second.h:
void second();
int third();
double fourth();
main.cpp:
#include <iostream>
#include "second.h"
int main()
{
//.....
return 0;
}
second.cpp:
void second()
{
//...
}
int third()
{
//...
return foo;
}
double fourth()
{
//...
return f;
}
Note that: it is not necessary to #include "second.h"
in second.cpp
. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.
Here's a solution for AngularJS using an IIFE and leveraging the fact that services are singletons.
This results in isLocalStorageAvailable
being set immediately when the service is first injected and avoids needlessly running the check every time local storage needs to be accessed.
angular.module('app.auth.services', []).service('Session', ['$log', '$window',
function Session($log, $window) {
var isLocalStorageAvailable = (function() {
try {
$window.localStorage.world = 'hello';
delete $window.localStorage.world;
return true;
} catch (ex) {
return false;
}
})();
this.store = function(key, value) {
if (isLocalStorageAvailable) {
$window.localStorage[key] = value;
} else {
$log.warn('Local Storage is not available');
}
};
}
]);
You need to split the line first.
import csv
with open('log.txt', 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(",") for line in stripped if line)
with open('log.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('title', 'intro'))
writer.writerows(lines)
To change the character set encoding to UTF-8 follow simple steps in PHPMyAdmin
Select your Database
Go To Operations
With conemu on windows 10 I couldn't call atom
from console even after I added %USERPROFILE%\AppData\Local\atom\bin
to PATH in environment variables. I just added
alias atom="C:/Users/me/AppData/local/atom/app-1.12.7/atom"
to my .bashrc
file.
I encountered an issue like this using the Maven Release Plugin. Resolving using relative paths (i.e. for the parent pom in the child module ../parent/pom.xml) did not seem to work in this scenario, it keeps looking for the released parent pom in the Nexus repository. Moving the parent pom to the parent folder of the module resolved this.
Very simple way (Tested) :-
PhotoViewAttacher pAttacher;
pAttacher = new PhotoViewAttacher(Your_Image_View);
pAttacher.update();
Add bellow line in build.gradle :-
compile 'com.commit451:PhotoView:1.2.4'
I fixed the issue by using these command lines
$ rm -rf node_modules/
$ sudo npm update -g npm
$ npm install
It's done!
$(document).ready(function(){_x000D_
$('input').on("cut copy paste",function(e) {_x000D_
e.preventDefault();_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" />
_x000D_
Not possible with vanilla CSS. However you can use something like:
Sass makes CSS fun again. Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.
Or
Rather than constructing long selector names to specify inheritance, in Less you can simply nest selectors inside other selectors. This makes inheritance clear and style sheets shorter.
Example:
#header {
color: red;
a {
font-weight: bold;
text-decoration: none;
}
}
Given the following sample
myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)
then
myData$A <-as.factor(myData$A)
myData$B <-as.factor(myData$B)
or you could select your columns altogether and wrap it up nicely:
# select columns
cols <- c("A", "B")
myData[,cols] <- data.frame(apply(myData[cols], 2, as.factor))
levels(myData$A) <- c("long", "short")
levels(myData$B) <- c("1kg", "2kg", "3kg")
To obtain
> myData
A B Pulse
1 long 1kg 20
2 short 2kg 21
3 long 3kg 22
4 short 1kg 23
5 long 2kg 24
6 short 3kg 25
you can try writing the command using 'sudo':
sudo mkdir DirName
This code:
from scipy.stats import linregress
linregress(x,y) #x and y are arrays or lists.
gives out a list with the following:
slope : float
slope of the regression line
intercept : float
intercept of the regression line
r-value : float
correlation coefficient
p-value : float
two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero
stderr : float
Standard error of the estimate
You can use parseInt(string, radix) to convert string value to integer like this code below
var votevalue = parseInt($('button').data('votevalue'));
?
Solution is just a single line query as below :
grant all on *.* to 'ROOT'@'%' identified by 'PASSWORD' with grant option;
Replace ROOT
with your mysql user name.
Replace PASSWORD
with your mysql password.
I had this same problem in a large Excel 2000 spreadsheet with hundreds of lines of code. My solution was to make the Worksheet active at the beginning of the Class. I.E. ThisWorkbook.Worksheets("WorkSheetName").Activate This was finally discovered when I noticed that if "WorkSheetName" was active when starting the operation (the code) the error didn't occur. Drove me crazy for quite awhile.
follow the steps:(let I assuming you have chosen Android view) app>res>values>strings
<string name="app_name">Put your App's new name here</string>
To check the accurate usage for your services be it is free (as per always free or 12 months free) or Pay-As-You-Go, it is important to monitor the usage so that you know upfront on the cost incurred or when to upgrade your service tier.
To check your free service usage and its limits, Go to search in Portal, search with "Subscription" and click on it. you will see the details of each service that you have used.
In case of free azure from Microsoft, you get to see the cost incurred for each one.
Visit Check usage of free services included with your Azure free account
Hope this helps someone!
Here is an idea as you may have multiple newline in a textbox:
var text=document.getElementById('post-text').value.split('\n');
var html = text.join('<br />');
This HTML value will preserve newline. Hope this helps.
You should be doing this
String input = "hello world, this is a line of text";
int i = input.indexOf(' ');
String word = input.substring(0, i);
String rest = input.substring(i);
The above is the fastest way of doing this task.
To find the exact center of the map you'll need to translate the lat/lon coordinates into pixel coordinates and then find the pixel center and convert that back into lat/lon coordinates.
You might not notice or mind the drift depending how far north or south of the equator you are. You can see the drift by doing map.setCenter(map.getBounds().getCenter()) inside of a setInterval, the drift will slowly disappear as it approaches the equator.
You can use the following to translate between lat/lon and pixel coordinates. The pixel coordinates are based on a plane of the entire world fully zoomed in, but you can then find the center of that and switch it back into lat/lon.
var HALF_WORLD_CIRCUMFERENCE = 268435456; // in pixels at zoom level 21
var WORLD_RADIUS = HALF_WORLD_CIRCUMFERENCE / Math.PI;
function _latToY ( lat ) {
var sinLat = Math.sin( _toRadians( lat ) );
return HALF_WORLD_CIRCUMFERENCE - WORLD_RADIUS * Math.log( ( 1 + sinLat ) / ( 1 - sinLat ) ) / 2;
}
function _lonToX ( lon ) {
return HALF_WORLD_CIRCUMFERENCE + WORLD_RADIUS * _toRadians( lon );
}
function _xToLon ( x ) {
return _toDegrees( ( x - HALF_WORLD_CIRCUMFERENCE ) / WORLD_RADIUS );
}
function _yToLat ( y ) {
return _toDegrees( Math.PI / 2 - 2 * Math.atan( Math.exp( ( y - HALF_WORLD_CIRCUMFERENCE ) / WORLD_RADIUS ) ) );
}
function _toRadians ( degrees ) {
return degrees * Math.PI / 180;
}
function _toDegrees ( radians ) {
return radians * 180 / Math.PI;
}
Are you putting this line inside the class declaration? In that case you should remove the JSONDeserializer::
.
Here is a great way to build dynamic fields for a pivot query:
--summarize values to a tmp table
declare @STR varchar(1000)
SELECT @STr = COALESCE(@STr +', ', '')
+ QUOTENAME(DateRange)
from (select distinct DateRange, ID from ##pivot)d order by ID
---see the fields generated
print @STr
exec(' .... pivot code ...
pivot (avg(SalesAmt) for DateRange IN (' + @Str +')) AS P
order by Decile')
By using map function you can do that. Please refer below code.
var userDetails = [{
"_id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
},{
"_id":"5078c3a803ff4197dc81fbfc",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 2"
}];
var formattedUserDetails = userDetails.map(({ _id:id, email, image, name }) => ({
id,
email,
image,
name
}));
console.log(formattedUserDetails);
Use simple negative margin rather than using display table.
Updated in fiddle JS Fiddle
.container {
border-style: solid;
border-color: red;
border-width: 1px 0 0 1px;
display: inline-block;
}
.column {
float: left; overflow: hidden;
}
.cell {
border: 1px solid red; width: 120px; height: 20px;
margin:-1px 0 0 -1px;
}
.clearfix {
clear:both;
}
I'm sure someone can do better, but this works:
sapply(as.character(q.data$string), function(x, letter = "a"){
sum(unlist(strsplit(x, split = "")) == letter)
})
greatgreat magic not
2 1 0
or in a function:
countLetter <- function(charvec, letter){
sapply(charvec, function(x, letter){
sum(unlist(strsplit(x, split = "")) == letter)
}, letter = letter)
}
countLetter(as.character(q.data$string),"a")
Add this in project gradle file
classpath 'com.google.gms:google-services:3.0.0'
just use a subquery right there like:
INSERT INTO table1 VALUES ("A string", 5, (SELECT ...)).
You should take a look the reference documentation. It's well explained.
In your case, I think you cannot use between because you need to pass two parameters
Between - findByStartDateBetween … where x.startDate between ?1 and ?2
In your case take a look to use a combination of LessThan
or LessThanEqual
with GreaterThan
or GreaterThanEqual
LessThan - findByEndLessThan … where x.start< ?1
LessThanEqual findByEndLessThanEqual … where x.start <= ?1
GreaterThan - findByStartGreaterThan … where x.end> ?1
GreaterThanEqual - findByStartGreaterThanEqual … where x.end>= ?1
You can use the operator And
and Or
to combine both.
Similar in spirit to the Haskell-style solution by @crl, but working with reduce
:
function permutations( base ) {
if (base.length == 0) return [[]]
return permutations( base.slice(1) ).reduce( function(acc,perm) {
return acc.concat( base.map( function(e,pos) {
var new_perm = perm.slice()
new_perm.splice(pos,0,base[0])
return new_perm
}))
},[])
}
I noticed some time ago that a For loop typically generates several more machine instructions than a while loop. However, if you look closely at the examples, which mirror my observations, the difference is two or three machine instructions, hardly worth much consideration.
Note, too, that the initializer for a WHILE loop can be eliminated by baking it into the code, e. g.:
static int intStartWith = 100;
The static modifier bakes the initial value into the code, saving (drum roll) one MOV instruction. Of greater significance, marking a variable as static moves it outside the stack frame. Variable alignment permitting, it may also produce slightly smaller code, too, since the MOV instruction and its operands take more room than, for example an integer, Boolean, or character value (either ANSI or Unicode).
However, if variables are aligned on 8 byte boundaries, a common default setting, an int, bool, or TCHAR baked into code costs the same number of bytes as a MOV instruction.
Use g++ -std=c++11 -o <output_file_name> <file_to_be_compiled>
Try the following code:
select ccode, count(empno)
from company_details
group by ccode;
Swift 4.*
I have created a Xib for UICollectionViewCell which seems to be the good approach.
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return size(indexPath: indexPath)
}
private func size(for indexPath: IndexPath) -> CGSize {
// load cell from Xib
let cell = Bundle.main.loadNibNamed("ACollectionViewCell", owner: self, options: nil)?.first as! ACollectionViewCell
// configure cell with data in it
let data = self.data[indexPath.item]
cell.configure(withData: data)
cell.setNeedsLayout()
cell.layoutIfNeeded()
// width that you want
let width = collectionView.frame.width
let height: CGFloat = 0
let targetSize = CGSize(width: width, height: height)
// get size with width that you want and automatic height
let size = cell.contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: .defaultHigh, verticalFittingPriority: .fittingSizeLevel)
// if you want height and width both to be dynamic use below
// let size = cell.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
return size
}
}
#note: I don't recommend setting image when configuring data in this size determining case. It gave me the distorted/unwanted result. Configuring texts only gave me below result.
I didn't see an answer that's clean and suitable for production-ready software, so here it goes:
/*
* Get current error_reporting value,
* so that we don't lose preferences set in php.ini and .htaccess
* and accidently reenable message types disabled in those.
*
* If you want to disable e.g. E_STRICT on a global level,
* use php.ini (or .htaccess for folder-level)
*/
$old_error_reporting = error_reporting();
/*
* Disable E_STRICT on top of current error_reporting.
*
* Note: do NOT use ^ for disabling error message types,
* as ^ will re-ENABLE the message type if it happens to be disabled already!
*/
error_reporting($old_error_reporting & ~E_STRICT);
// code that should not emit E_STRICT messages goes here
/*
* Optional, depending on if/what code comes after.
* Restore old settings.
*/
error_reporting($old_error_reporting);
Your for
loop looks good.
A possible while
loop to accomplish the same thing:
int sum = 0;
int i = 1;
while (i <= 100) {
sum += i;
i++;
}
System.out.println("The sum is " + sum);
A possible do while
loop to accomplish the same thing:
int sum = 0;
int i = 1;
do {
sum += i;
i++;
} while (i <= 100);
System.out.println("The sum is " + sum);
The difference between the while
and the do while
is that, with the do while
, at least one iteration is sure to occur.
Here is some C code that produces the above mentioned error:
int main(int argc, char **argv) {
exit(1);
}
Compiled like this on Fedora 17 Linux 64 bit with gcc:
el@defiant ~/foo2 $ gcc -o n n2.c
n2.c: In function ‘main’:
n2.c:2:3: warning: incompatible implicit declaration of built-in
function ‘exit’ [enabled by default]
el@defiant ~/foo2 $ ./n
el@defiant ~/foo2 $
To make the warning go away, add this declaration to the top of the file:
#include <stdlib.h>
For trimming your string, Go's "strings" package have TrimSpace()
, Trim()
function that trims leading and trailing spaces.
Check the documentation for more information.
I found myself requiring this functionality often enough that I packaged it into a library called std-pour. It should let you execute a command and view the output in real time. To install simply:
npm install std-pour
Then it's simple enough to execute a command and see the output in realtime:
const { pour } = require('std-pour');
pour('ping', ['8.8.8.8', '-c', '4']).then(code => console.log(`Error Code: ${code}`));
It's promised based so you can chain multiple commands. It's even function signature-compatible with child_process.spawn
so it should be a drop in replacement anywhere you're using it.
I was running into a similar, but not exactly the same issue with swagger. Hopefully this helps someone else.
I was using a custom document title and was not changing the folder path in the SwaggerEndPoint to match the document title. If you leave the endpoint pointing to swagger/v1/swagger.json it won't find the json file in the swagger UI.
Example:
services.AddSwaggerGen(swagger =>
{
swagger.SwaggerDoc("AppAdministration", new Info { Title = "App Administration API", Version = "v1.0" });
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/AppAdministration/swagger.json", "App Administration");
});
One way to sync your database to your django models is to delete your database file and run makemigrations and migrate commands again. This will reflect your django models structure to your database from scratch. Although, make sure to backup your database file before deleting in case you need your records.
This solution worked for me since I wasn't much bothered about the data and just wanted my db and models structure to sync up.
Echoing the answer, above, a full install of the JDK (8u121 at this writing) from here - http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html - did the trick. Updating via the Mac OS Control Panel did not update the profile variable. Installing via the full installer, did. Then Eclipse was happy.
Also another obscure possibility:
$oldDate = '2010-03-20'
$arr = explode('-', $oldDate);
$newDate = $arr[2].'-'.$arr[1].'-'.$arr[0];
I don't know if I would use it but still :)
I have created a function for date manipulation. you can add or subtract any number of days, hours, minutes.
function dateManipulation(date, days, hrs, mins, operator) {
date = new Date(date);
if (operator == "-") {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() - durationInMs);
} else {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() + durationInMs);
}
return newDate;
}
Now, call this function by passing parameters. For example, here is a function call for getting date before 3 days from today.
var today = new Date();
var newDate = dateManipulation(today, 3, 0, 0, "-");
The user comments on the array_unique() documentation have many solutions to this. Here is one of them:
kenrbnsn at rbnsn dot com
27-Sep-2005 12:09Yet another Array_Unique for multi-demensioned arrays. I've only tested this on two-demensioned arrays, but it could probably be generalized for more, or made to use recursion.
This function uses the serialize, array_unique, and unserialize functions to do the work.
function multi_unique($array) { foreach ($array as $k=>$na) $new[$k] = serialize($na); $uniq = array_unique($new); foreach($uniq as $k=>$ser) $new1[$k] = unserialize($ser); return ($new1); }
This is from http://ca3.php.net/manual/en/function.array-unique.php#57202.
I faced the same problem with JBoss 4.2.3 GA when deploying my web application. I solved the issue by copying my commons-codec 1.6 jar into C:\jboss-4.2.3.GA\server\default\lib
If you don't have to support IE, you can use selectionStart
and selectionEnd
attributes of textarea
.
To get caret position just use selectionStart
:
function getCaretPosition(textarea) {
return textarea.selectionStart
}
To get the strings surrounding the selection, use following code:
function getSurroundingSelection(textarea) {
return [textarea.value.substring(0, textarea.selectionStart)
,textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)
,textarea.value.substring(textarea.selectionEnd, textarea.value.length)]
}
See also HTMLTextAreaElement docs.
String[] listOfFiles = getActivity().getFilesDir().list();
or
String[] listOfFiles = Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS).list();
Ken has the right solution, but you don't want to add the picturebox.Image.Load() member method.
If you do it with a Load and the ImageLocation is not set, it will fail with a "Image Location must be set" exception. If you use the picturebox.Refresh() member method, it works without the exception.
Completed code below:
public void showAnimatedPictureBox(PictureBox thePicture)
{
thePicture.Image = Properties.Resources.hamster;
thePicture.Refresh();
thePicture.Visible = true;
}
It is invoked as: showAnimatedPictureBox( myPictureBox );
My XAML looks like:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="myApp.MainWindow"
Title="myApp" Height="679.079" Width="986">
<StackPanel Width="136" Height="Auto" Background="WhiteSmoke" x:Name="statusPanel">
<wfi:WindowsFormsHost>
<winForms:PictureBox x:Name="myPictureBox">
</winForms:PictureBox>
</wfi:WindowsFormsHost>
<Label x:Name="myLabel" Content="myLabel" Margin="10,3,10,5" FontSize="20" FontWeight="Bold" Visibility="Hidden"/>
</StackPanel>
</Window>
I realize this is an old post, but loading the image directly from a resource is was extremely unclear on Microsoft's site, and this was the (partial) solution I came to. Hope it helps someone!
load_weights
only sets the weights of your network. You still need to define its architecture before calling load_weights
:
def create_model():
model = Sequential()
model.add(Dense(64, input_dim=14, init='uniform'))
model.add(LeakyReLU(alpha=0.3))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Dropout(0.5))
model.add(Dense(64, init='uniform'))
model.add(LeakyReLU(alpha=0.3))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Dropout(0.5))
model.add(Dense(2, init='uniform'))
model.add(Activation('softmax'))
return model
def train():
model = create_model()
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)
checkpointer = ModelCheckpoint(filepath="/tmp/weights.hdf5", verbose=1, save_best_only=True)
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose=2, callbacks=[checkpointer])
def load_trained_model(weights_path):
model = create_model()
model.load_weights(weights_path)
Essentially it's a place in code that allows you to tap in to a module to either provide different behavior or to react when something happens.
I wrote a method for this sometime back. It deletes the specified directory and returns true if the directory deletion was successful.
/**
* Delets a dir recursively deleting anything inside it.
* @param dir The dir to delete
* @return true if the dir was successfully deleted
*/
public static boolean deleteDirectory(File dir) {
if(! dir.exists() || !dir.isDirectory()) {
return false;
}
String[] files = dir.list();
for(int i = 0, len = files.length; i < len; i++) {
File f = new File(dir, files[i]);
if(f.isDirectory()) {
deleteDirectory(f);
}else {
f.delete();
}
}
return dir.delete();
}
You should combine a type pointcut with a method pointcut.
These pointcuts will do the work to find all public methods inside a class marked with an @Monitor annotation:
@Pointcut("within(@org.rejeev.Monitor *)")
public void beanAnnotatedWithMonitor() {}
@Pointcut("execution(public * *(..))")
public void publicMethod() {}
@Pointcut("publicMethod() && beanAnnotatedWithMonitor()")
public void publicMethodInsideAClassMarkedWithAtMonitor() {}
Advice the last pointcut that combines the first two and you're done!
If you're interested, I have written a cheat sheet with @AspectJ style here with a corresponding example document here.
Just need:
string stringName = EnumDisplayStatus.Visible.ToString("f");
// stringName == "Visible"
Try this, it will insert the list item at index 0;
DropDownList1.Items.Insert(0, new ListItem("Add New", ""));
use something like:
double step = 1d / 5;
(1d is a cast to double)
mEditText.setFocusableInTouchMode(true);
mEditText.requestFocus();
if(mEditText.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
Try this:
...(to_date('2011/04/22 08:30:00', 'yyyy/mm/dd hh24:mi:ss'));
In your case you can use __FILE__
variable !
It should help.
It is one of predefined.
Read more about predefined constants in PHP http://php.net/manual/en/language.constants.predefined.php
In plain Javascript, you could use Array#reduce
with an object
var cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }],_x000D_
result = cars.reduce(function (r, a) {_x000D_
r[a.make] = r[a.make] || [];_x000D_
r[a.make].push(a);_x000D_
return r;_x000D_
}, Object.create(null));_x000D_
_x000D_
console.log(result);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
You can use cut with a delimiter like this:
with space delim:
cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv
with tab delim:
cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv
I gave you the version of cut in which you can extract a list of intervals...
Hope it helps!
Hello world :)
The best but strange way for me was to do next things.
1) Download postgres93.app or other version. Add this app into /Applications/ folder.
2) Add a row (command) into the file .bash_profile
(which is in my home directory):
export PATH=/Applications/Postgres93.app/Contents/MacOS/bin/:$PATHIt's a PATH to
psql
from Postgres93.app
. The row (command) runs every time console is started.
3) Launch Postgres93.app
from /Applications/
folder. It starts a local server (port is "5432" and host is "localhost").
4) After all of this manipulations I was glad to run $ createuser -SRDP user_name
and other commands and to see that it worked! Postgres93.app
can be made to run every time your system starts.
5) Also if you wanna see your databases graphically you should install PG Commander.app
. It's good way to see your postgres DB as pretty data-tables
Of, course, it's helpful only for local server. I will be glad if this instructions help others who has faced with this problem.
To find first element in a sequence seq
that matches a predicate
:
next(x for x in seq if predicate(x))
Or (itertools.ifilter
on Python 2):
next(filter(predicate, seq))
It raises StopIteration
if there is none.
To return None
if there is no such element:
next((x for x in seq if predicate(x)), None)
Or:
next(filter(predicate, seq), None)
this is one:
ls -l . | egrep -c '^-'
Note:
ls -1 | wc -l
Which means:
ls
: list files in dir
-1
: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|
: pipe output onto...
wc
: "wordcount"
-l
: count l
ines.
You should use the setString()
method to set the userID
. This both ensures that the statement is formatted properly, and prevents SQL injection
:
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
There is a nice tutorial on how to use PreparedStatement
s properly in the Java Tutorials.
If you want to delete a range AFTER a specific line trigger you can use something like this
:g/^TMPDIR/ :.,+11d
That deletes 11 lines (inclusive) after every encounter of ^TMPDIR
.
This answer is a little late, but I stumbled upon a solution that makes everything a LOT easier.
You can actually assign the form name directly to your controller if you're using the controllerAs syntax and then reference it from your "this" variable. Here's how I did it in my code:
I configured the controller via ui-router (but you can do it however you want, even in the HTML directly with something like <div ng-controller="someController as myCtrl">
) This is what it might look like in a ui-router configuration:
views: {
"": {
templateUrl: "someTemplate.html",
controller: "someController",
controllerAs: "myCtrl"
}
}
and then in the HTML, you just set the form name as the "controllerAs"."name" like so:
<ng-form name="myCtrl.someForm">
<!-- example form code here -->
<input name="firstName" ng-model="myCtrl.user.firstName" required>
</ng-form>
now inside your controller you can very simply do this:
angular
.module("something")
.controller("someController",
[
"$scope",
function ($scope) {
var vm = this;
if(vm.someForm.$valid){
// do something
}
}]);
The issue is because of a bad query the time to executing query is taking more than 60 seconds or a Lock on the Table
The issue looks like a deadlock is occurring; we have queries which are blocking the queries to complete in time. The default timeout for a query is 60 secs and beyond that we will have the SQLException for timeout.
Please check the SQL Server logs for deadlocks. The other way to solve the issue to to increase the Timeout on the Command Object (Temp Solution).
You can't forward-declare a function in Python. If you have logic executing before you've defined functions, you've probably got a problem anyways. Put your action in an if __name__ == '__main__'
at the end of your script (by executing a function you name "main" if it's non-trivial) and your code will be more modular and you'll be able to use it as a module if you ever need to.
Also, replace that list comprehension with a generator express (i.e., print "\n".join(str(bla) for bla in sorted(mylist, cmp=cmp_configs))
)
Also, don't use cmp
, which is deprecated. Use key
and provide a less-than function.
The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).
WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.
For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:
ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.
Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.
In the scenarios listed below you should go for WCF:
WEB API is a framework for developing RESTful/HTTP services.
There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.
HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.
if for whatever reason you are interested in navigating up a specific number of directories you could also do: nth_path=$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && cd ../../../ && pwd)
. This would give 3 parents directories up
If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)
So I have to use the following method.
CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.
Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.
Step2:
[Situation A]: target commit is the latest one.
1) In the git command console, input
git commit --amend -m "new comment message"
2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input
git push --force
[Situation B]: target commit is not the latest one.
1) In the git command console, input
git rebase -i HEAD~n
It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2.
This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq
to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq
to save&quit.
2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input
git push --force
Finally: In the sourcetree main window, Press F5
to refresh.
int height(Node* root) {
if(root==NULL) return -1;
return max(height(root->left),height(root->right))+1;
}
Take of maximum height from left and right subtree and add 1 to it.This also handles the base case(height of Tree with 1 node is 0).
var=" a b "
echo "$(set -f; echo $var)"
>a b
if (!$variablename) { Write-Host "variable is null" }
I hope this simple answer will is resolve the question. Source
Just inject the routeParams service:
This can be a pure CSS solution. Given:
<ul class="tileMe">
<li>item 1<li>
<li>item 2<li>
<li>item 3<li>
</ul>
The CSS would be:
.tileMe li {
display: inline;
float: left;
}
Now, since you've changed the display mode from 'block' (implied) to 'inline', any padding, margin, width, or height styles you applied to li elements will not work. You need to nest a block-level element inside the li:
<li><a class="tile" href="home">item 1</a></li>
and add the following CSS:
.tile a {
display: block;
padding: 10px;
border: 1px solid red;
margin-right: 5px;
}
The key concept behind this solution is that you are changing the display style of the li to 'inline', and nesting a block-level element inside to achieve the consistent tiling effect.
There are great responses here. I would like to keep it short to memorize the difference between partition & buckets.
You generally partition on a less unique column. And bucketing on most unique column.
Example if you consider World population with country, person name and their bio-metric id as an example. As you can guess, country field would be the less unique column and bio-metric id would be the most unique column. So ideally you would need to partition the table by country and bucket it by bio-metric id.
No need for custom middleware?! In express:
//you probably have something like this already
app.use("/public", express.static('public'));
Then put your favicon in public and add the following line in your html's head:
<link rel="icon" href="/public/favicon.ico">
another way to find last highest data based on date
SELECT A.JID,A.EntryDate,RefundDate,Comments,Refund, ActionBy FROM (
(select JID, Max(EntryDate) AS EntryDate from refundrequested GROUP BY JID) A
Inner JOIN (SELECT JID,ENTRYDATE,refundDate,Comments,refund,ActionBy from refundrequested) B
ON A.JID=B.JID AND A.EntryDate = B.EntryDate)
yes, something like this would do it, might not be the best though, you might wanna make a backup
$get_query = mysql_query("SELECT `any_field` FROM `your_table`");
$auto_increment_id = 1;
while($row = mysql_fetch_assoc($get_query))
{
$update_query = mysql_query("UPDATE `your_table` SET `auto_increment_id`=$auto_increment_id WHERE `any_field` = '".$row['any_field']."'");
$auto_increment_id++;
}
notice that the the any_field
you select must be the same when updating.
The targetNamespace
of your XML Schema does not match the namespace of the Root element (dot in Test.Namespace
vs. comma in Test,Namespace
)
Once you make the above agree, you have to consider that your element2
has an attribute order that is not in your XSD.
SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE "IMS"."MAX" ';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
EXECUTE IMMEDIATE '
CREATE TABLE "IMS"."MAX"
( "ID" NUMBER NOT NULL ENABLE,
"NAME" VARCHAR2(20 BYTE),
CONSTRAINT "MAX_PK" PRIMARY KEY ("ID")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "SYSAUX" ENABLE
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "SYSAUX" ';
END;
// Doing this code, checks if the table exists and later it creates the table max. this simply works in single compilation
I experienced the same error while using Windows 7 x64, Eclipse, and JDK 1.6.0_30. In the JDK installation folder there is a jre
folder. This threw me off at first as I was adding the aforementioned jars to the JDK's lib/security folder with no luck. Full path:
C:\Program Files\Java\jdk1.6.0_30\jre\lib\security
Download and extract the files contained in the jce
folder of this archive into that folder.
Ok you can use this simply
-webkit-text-stroke-width: .7px;
-webkit-text-stroke-color: #34343b;
-webkit-font-smoothing:antialiased;
Make sure your text color and upper text-stroke-width must me same and that's it.
See numpy.clip:
index = numpy.clip(index, 0, len(my_list) - 1)
This is not a synchronization problem. This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself.
Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
Entry item = it.next();
map.remove(item.getKey());
}
This will throw a ConcurrentModificationException
when the it.hasNext()
is called the second time.
The correct approach would be
Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
Entry item = it.next();
it.remove();
}
Assuming this iterator supports the remove()
operation.
The beauty of *nix tools is you can combine them:
ls -l | sort -k9,9
The output of ls -l
will look like this
-rw-rw-r-- 1 luckydonald luckydonald 532 Feb 21 2017 Makefile
-rwxrwxrwx 1 luckydonald luckydonald 4096 Nov 17 23:47 file.txt
So with 9,9
you sort column 9
up to the column 9
, being the file names. You have to provide where to stop, which is the same column in this case. The columns start with 1
.
Also, if you want to ignore upper/lower case, add --ignore-case
to the sort command.
Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET
command. The first one to stop the service, the second one to start the service. Give them a STOP
and START
argument, followed by the service name.
In this example we restart the Printer Spooler service.
NET STOP "Print Spooler"
NET START "Print Spooler"
Note: unfortunately NET RESTART <service name>
does not exist.
I also had this issue using Lumen, but fixed by setting DB_STRICT_MODE=false
in .env
file.
Example:
perfdb-# \df information_schema.*;
List of functions
Schema | Name | Result data type | Argument data types | Type
information_schema | _pg_char_max_length | integer | typid oid, typmod integer | normal
information_schema | _pg_char_octet_length | integer | typid oid, typmod integer | normal
information_schema | _pg_datetime_precision| integer | typid oid, typmod integer | normal
.....
information_schema | _pg_numeric_scale | integer | typid oid, typmod integer | normal
information_schema | _pg_truetypid | oid | pg_attribute, pg_type | normal
information_schema | _pg_truetypmod | integer | pg_attribute, pg_type | normal
(11 rows)
There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.
Keep it fast, keep it simple
put this in your ~/.bashrc
file.
git_stuff() {
git_branch=$(git branch --show-current 2> /dev/null)
if [[ $git_branch == "" ]];then
echo -e ""
elif [[ $git_branch == *"Nocommit"* ]];then
echo -e "No commits"
else
echo -e "$git_branch"
fi
}
prompt() {
PS1="\e[2m$(date +%H:%M:%S.%3N) \e[4m$(git_stuff)\033[0m\n\w$ "
}
PROMPT_COMMAND=prompt
Then source ~/.bashrc
If the items are numerically ordered, use the key() function to determine the index of the current item and compare it to the length. You'd have to use next() or prev() to cycle through items in a while loop instead of a for loop:
$length = sizeOf($arr);
while (key(current($arr)) != $length-1) {
$v = current($arr); doSomething($v); //do something if not the last item
next($myArray); //set pointer to next item
}
Yes, you can apply CSS to SVG, but you need to match the element, just as when styling HTML. If you just want to apply it to all SVG paths, you could use, for example:
?path {
fill: blue;
}?
External CSS appears to override the path's fill
attribute, at least in WebKit and Gecko-based browsers I tested. Of course, if you write, say, <path style="fill: green">
then that will override external CSS as well.
I just noticed that with C++20, we will have
bool std::map::contains( const Key& key ) const;
That will return true if map holds an element with key key
.
Beginning with MySQL 8.0.19 you can use an alias for that row (see reference).
INSERT INTO beautiful (name, age)
VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29)
AS new
ON DUPLICATE KEY UPDATE
age = new.age
...
For earlier versions use the keyword VALUES
(see reference, deprecated with MySQL 8.0.20).
INSERT INTO beautiful (name, age)
VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29)
ON DUPLICATE KEY UPDATE
age = VALUES(age),
...
I have 1 simpler work around...
What you can do is while inserting data/document into your main collection "things" you must insert the attributes in 1 separate collection lets say "things_attributes".
so every time you insert in "things", you do get from "things_attributes" compare values of that document with your new document keys if any new key present append it in that document and again re-insert it.
So things_attributes will have only 1 document of unique keys which you can easily get when ever you require by using findOne()
Just to add to the previous comment, the documentation for the command line tool for updating the Tomcat service settings (if Tomcat is running as a service on Windows) is here. This tool updates the registry with the proper settings. So if you wanted to update the max memory setting for the Tomcat service you could run this (from the tomcat/bin directory), assuming the default service name of Tomcat5:
tomcat5 //US//Tomcat5 --JvmMx=512
Probably this is an SELinux block. Try this:
# setsebool -P httpd_enable_cgi 1
# chcon -R -t httpd_sys_script_exec_t cgi-bin/your_script.cgi
easier & shorter via indirect: INDIRECT("'..\..\..\..\Supply\SU\SU.ods'#$Data.$A$2:$AC$200")
however indirect() has performance drawbacks if lot of links in workbook
I miss construct like: ['../Data.ods']#Sheet1.A1
in LibreOffice. The intention is here: if I create a bunch of master workbooks and depending report workbooks in limited subtree of directories in source file system, I can zip whole directory subtree with complete package of workbooks and send it to other cooperating person per Email or so. It will be saved in some other absolute pazth on target system, but linkage works again in new absolute path because it was coded relatively to subtree root.
var ua = navigator.userAgent.toString().toLowerCase();
var match = /(trident)(?:.*rv:([\w.]+))?/.exec(ua) ||/(msie) ([\w.]+)/.exec(ua)||['',null,-1];
var rv = match[2];
return rv;
Not sure what is the difference between .cfg & .cnf
In my server I couldn't find .cfg or .cnf
I had created a new file for the same and placed it in the following folder /usr/local/ssl/bin
executed the
.\openssl genrsa -des3 -out <key name>.key 2048
went great..
cat 'filename' | grep '[^ ]' | wc -l
should do the trick just fine
I found one way to access the shared folder without giving the username and password.
We need to change the share folder protect settings in the machine where the folder has been shared.
Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.
By doing the above settings we can access the shared folder without any username/password.
The transform CSS property lets you rotate, scale, skew, or translate an element.
So you can easily use the transform: scale(2.5);
option to scale 2.5 times for example.
If you're having this same issue using Spring Tool Suite:
The Spring Tool Suite's underlying IDE is, in fact, Eclipse. I've gotten this error just now trying to use some com.sun.net
classes. To remove these errors and prevent them from popping up in the Eclipse Luna SR1 (4.4.2) platform of STS:
You're good to go.
Put non-breaking spaces in your text instead of normal spaces. On Ubuntu I do this with (Compose Key)-space-space.
For scanf
, you need to use %hu
since you're passing a pointer to an unsigned short
. For printf
, it's impossible to pass an unsigned short
due to default promotions (it will be promoted to int
or unsigned int
depending on whether int
has at least as many value bits as unsigned short
or not) so %d
or %u
is fine. You're free to use %hu
if you prefer, though.
Another possibility is LaTeX + animate package. You will need to provide the individual frames making the animation. The resulting pdf does NOT require any plugin, the animation is shown in Adobe reader
Warning: Unfortunately I believe most popular platforms have dropped support for comprehensions. See below for the well-supported ES6 method
You can always use something like:
[for (i of Array(7).keys()) i*i];
Running this code on Firefox:
[ 0, 1, 4, 9, 16, 25, 36 ]
This works on Firefox (it was a proposed ES7 feature), but it has been dropped from the spec. IIRC, Babel 5 with "experimental" enabled supports this.
This is your best bet as array-comprehension are used for just this purpose. You can even write a range function to go along with this:
var range = (u, l = 0) => [ for( i of Array(u - l).keys() ) i + l ]
Then you can do:
[for (i of range(5)) i*i] // 0, 1, 4, 9, 16, 25
[for (i of range(5,3)) i*i] // 9, 16, 25
A nice way to do this any of:
[...Array(7).keys()].map(i => i * i);
Array(7).fill().map((_,i) => i*i);
[...Array(7)].map((_,i) => i*i);
This will output:
[ 0, 1, 4, 9, 16, 25, 36 ]
@Test
public void testSearchManagementStaff() throws SQLException
{
boolean res=true;
ManagementDaoImp mdi=new ManagementDaoImp();
boolean b=mdi.searchManagementStaff("[email protected]"," 123456");
assertEquals(res,b);
}
You can use sp_lock
(and sp_lock2
), but in SQL Server 2005 onwards this is being deprecated in favour of querying sys.dm_tran_locks
:
select
object_name(p.object_id) as TableName,
resource_type, resource_description
from
sys.dm_tran_locks l
join sys.partitions p on l.resource_associated_entity_id = p.hobt_id
Sweet alerts also has an 'html' option, set it to true.
var hh = "<b>test</b>";
swal({
title: "" + txt + "",
html: true,
text: "Testno sporocilo za objekt " + hh + "",
confirmButtonText: "V redu",
allowOutsideClick: "true"
});
Assembly code is discussed here.
"An assembly language is a low-level language for programming computers. It implements a symbolic representation of the numeric machine codes and other constants needed to program a particular CPU architecture."
Machine code is discussed here.
"Machine code or machine language is a system of instructions and data executed directly by a computer's central processing unit."
Basically, assembler code is the language and it is translated to object code (the native code that the CPU runs) by an assembler (analogous to a compiler).
One of the nice things about the syntax is that you can be sure that a CREATE OR REPLACE
will never cause you to lose data (the most you will lose is code, which hopefully you'll have stored in source control somewhere).
The equivalent syntax for tables is ALTER, which means you have to explicitly enumerate the exact changes that are required.
EDIT: By the way, if you need to do a DROP + CREATE in a script, and you don't care for the spurious "object does not exist" errors (when the DROP doesn't find the table), you can do this:
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE owner.mytable';
EXCEPTION
WHEN OTHERS THEN
IF sqlcode != -0942 THEN RAISE; END IF;
END;
/
Have you checked in console if data from form is properly serialized? Is ajax request successful? Also you didn't close placeholder quote in, which can cause some problems:
<textarea name="comentarii" cols="36" rows="5" placeholder="Message>
Stripe has a PHP library to accept credit cards without needing a merchant account: https://github.com/stripe/stripe-php
Check out the documentation and FAQ, and feel free to drop by our chatroom if you have more questions.
That method can't return true
. That's the point of Long.MAX_VALUE
. It would be really confusing if its name were... false. Then it should be just called Long.SOME_FAIRLY_LARGE_VALUE
and have literally zero reasonable uses. Just use Android's isUserAGoat
, or you may roll your own function that always returns false
.
Note that a long
in memory takes a fixed number of bytes. From Oracle:
long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
As you may know from basic computer science or discrete math, there are 2^64 possible values for a long, since it is 64 bits. And as you know from discrete math or number theory or common sense, if there's only finitely many possibilities, one of them has to be the largest. That would be Long.MAX_VALUE
. So you are asking something similar to "is there an integer that's >0 and < 1?" Mathematically nonsensical.
If you actually need this for something for real then use BigInteger
class.
You can do this:
/* Clearfix for the menu */
.ui-menu:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
and also set:
.ui-menu .ui-menu-item {
display: inline-block;
float: left;
margin: 0;
padding: 0;
width: auto;
}
<?php
$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$a = 'a';
$a = NULL;
}
$elapsed = microtime(true) - $start;
echo "took $elapsed seconds\r\n";
$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$a = 'a';
unset($a);
}
$elapsed = microtime(true) - $start;
echo "took $elapsed seconds\r\n";
?>
Per that it seems like "= null" is faster.
PHP 5.4 results:
PHP 5.3 results:
PHP 5.2 results:
PHP 5.1 results:
Things start to look different with PHP 5.0 and 4.4.
5.0:
4.4:
Keep in mind microtime(true) doesn't work in PHP 4.4 so I had to use the microtime_float example given in php.net/microtime / Example #1.
Looks like FB just changed the app dev page again and added a feature called "Server IP Whitelist".
Try download the zip files from http://www.nltk.org/nltk_data/ and then unzip, save in your Python folder, such as C:\ProgramData\Anaconda3\nltk_data
I think the easiest thing for you to do would be to install the git plugin for eclipse, works more or less the same as eclipse CVS and SVN plugins:
GL!
If you want to change your number into a list of those numbers, I would first cast it to a string
, then casting it to a list will naturally break on each character:
[int(x) for x in str(n)]
Although not exactly answering the question as formulated, but if you need or can take the end result as string you can also use
string s = Char.ConvertFromUtf32(56);
which will give you surrogate UTF-16 pairs if needed, protecting you if you are out side of the BMP.
You shouldn’t use <h1><a name="foo"/>Foo Title</h1>
in any flavor of HTML served as text/html
, because the XML empty element syntax isn’t supported in text/html
. However, <h1><a name="foo">Foo Title</a></h1>
is OK in HTML4. It is not valid in HTML5 as currently drafted.
<h1 id="foo">Foo Title</h1>
is OK in both HTML4 and HTML5. This won’t work in Netscape 4, but you’ll probably use a dozen other features that don’t work in Netscape 4.
I also ran into the same issue the other day. Google search got me here and several other places, but none gave the solution to this issue. I ended up saving the uploaded file (MultiPartFile) as a tmp file, then use FileSystemResource to upload it via RestTemplate. Here's the code I use,
String tempFileName = "/tmp/" + multiFile.getOriginalFileName();
FileOutputStream fo = new FileOutputStream(tempFileName);
fo.write(asset.getBytes());
fo.close();
parts.add("file", new FileSystemResource(tempFileName));
String response = restTemplate.postForObject(uploadUrl, parts, String.class, authToken, path);
//clean-up
File f = new File(tempFileName);
f.delete();
I am still looking for a more elegant solution to this problem.
Try this:
<?php
$to = "[email protected]";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: [email protected]" . "\r\n" .
"CC: [email protected]";
mail($to,$subject,$txt,$headers);
?>
You are copying singleton's customVar
into a singletonVar
variable and changing that variable does not affect the original value in singleton.
// This does not update singleton variable
// It just assigns value of your local variable
Log.d("Test",singletonVar);
singletonVar="World";
Log.d("Test",singletonVar);
// This actually assigns value of variable in singleton
Singleton.customVar = singletonVar;
There are several good answers here that handle this error in a broad scope. I ran into a specific situation with Spring Security which had a quick, although probably not optimal, fix.
During user authorization (immediately after logging in and passing authentication) I was testing a user entity for a specific authority in a custom class that extends SimpleUrlAuthenticationSuccessHandler.
My user entity implements UserDetails and has a Set of lazy loaded Roles which threw the "org.hibernate.LazyInitializationException - could not initialize proxy - no Session" exception. Changing that Set from "fetch=FetchType.LAZY" to "fetch=FetchType.EAGER" fixed this for me.
This is my sample code for load static variable
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class OnelinkConfig {
public static int MODULE_CODE;
public static int DEFAULT_PAGE;
public static int DEFAULT_SIZE;
@Autowired
public void loadOnelinkConfig(@Value("${onelink.config.exception.module.code}") int code,
@Value("${onelink.config.default.page}") int page, @Value("${onelink.config.default.size}") int size) {
MODULE_CODE = code;
DEFAULT_PAGE = page;
DEFAULT_SIZE = size;
}
}
bootstrap.yml
or bootstrap.properties
It's only used/needed if you're using Spring Cloud and your application's configuration is stored on a remote configuration server (e.g. Spring Cloud Config Server).
From the documentation:
A Spring Cloud application operates by creating a "bootstrap" context, which is a parent context for the main application. Out of the box it is responsible for loading configuration properties from the external sources, and also decrypting properties in the local external configuration files.
Note that the bootstrap.yml
or bootstrap.properties
can contain additional configuration (e.g. defaults) but generally you only need to put bootstrap config here.
Typically it contains two properties:
spring.cloud.config.uri
)spring.application.name
)Upon startup, Spring Cloud makes an HTTP call to the config server with the name of the application and retrieves back that application's configuration.
application.yml
or application.properties
Contains standard application configuration - typically default configuration since any configuration retrieved during the bootstrap process will override configuration defined here.
As unwind noted, keyword arguments with default values can go a long way.
I'll also state that in my opinion, it goes against the spirit of Python to worry a lot about what types are passed into methods. In Python, I think it's more accepted to use duck typing -- asking what an object can do, rather than what it is.
Thus, if your method may accept a string or a tuple, you might do something like this:
def print_names(names):
"""Takes a space-delimited string or an iterable"""
try:
for name in names.split(): # string case
print name
except AttributeError:
for name in names:
print name
Then you could do either of these:
print_names("Ryan Billy")
print_names(("Ryan", "Billy"))
Although an API like that sometimes indicates a design problem.
A BufferedReader can be opened and closed but a File is never opened, it just represents a path in the filesystem.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
String header = dataGridView1.Columns[i].HeaderText;
//String cellText = row.Cells[i].Text;
DataGridViewColumn column = dataGridView1.Columns[i]; // column[1] selects the required column
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; // sets the AutoSizeMode of column defined in previous line
int colWidth = column.Width; // store columns width after auto resize
colWidth += 50; // add 30 pixels to what 'colWidth' already is
this.dataGridView1.Columns[i].Width = colWidth; // set the columns width to the value stored in 'colWidth'
}
}
if you need a straight line shadow (like in bottom of toolbar) you can also use gradient xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:type="linear"
android:angle="-90"
android:startColor="#19000000" <!-- black transparent -->
android:endColor="#00000000" /> <!-- full transparent -->
</shape>
hope this help some one
If you are stuck with c++11, you can get make_unique
from abseil-cpp, an open source collection of C++ libraries drawn from Google’s internal codebase.
linterOptions is currently only handled by the CLI. If you're not using CLI then depending on the code base you're using you'll need to set the ignore somewhere else. webpack, tsconfig, etc
you can use this code to hide the tool tip change its title and show the tooltip again, when the ajax request returns successfully.
$(element).tooltip('hide');
$(element).attr('title','this is new title');
$(element).tooltip('fixTitle');
setTimeout(function() { $(element).tooltip('show');}, 500);
Strictly speaking, you should put something that makes sense - according to the spec here, the most correct version is:
<input name=name id=id type=checkbox checked=checked>
For HTML, you can also use the empty attribute syntax, checked=""
, or even simply checked
(for stricter XHTML, this is not supported).
Effectively, however, most browsers will support just about any value between the quotes. All of the following will be checked:
<input name=name id=id type=checkbox checked>
<input name=name id=id type=checkbox checked="">
<input name=name id=id type=checkbox checked="yes">
<input name=name id=id type=checkbox checked="blue">
<input name=name id=id type=checkbox checked="false">
And only the following will be unchecked:
<input name=name id=id type=checkbox>
See also this similar question on disabled="disabled"
.
Just use awk, it's much simpler than grep in letting you clearly express compound conditions.
If you want to skip lines that contains both loom
and gloom
:
awk '/loom/ && !/gloom/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)
or if you want to print them:
awk '/(^|[^g])loom/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)
and if the reality is you just want lines where loom
appears as a word by itself:
awk '/\<loom\>/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)
This function will produce required table as list of tuples.
def get_documents_by_user_email(email):
query = session.query(
User.email,
User.name,
Document.name,
DocumentsPermissions.readAllowed,
DocumentsPermissions.writeAllowed,
)
join_query = query.join(Document).join(DocumentsPermissions)
return join_query.filter(User.email == email).all()
user_docs = get_documents_by_user_email(email)
CSS Flexbox was designed to simplify creating these types of layouts.
html {
height: 100%;
}
body {
height: 100%;
display: flex;
}
.Content {
flex-grow: 1;
}
.Sidebar {
width: 290px;
flex-shrink: 0;
}
_x000D_
<div class="Content" style="background:#bed">Content</div>
<div class="Sidebar" style="background:#8cc">Sidebar</div>
_x000D_
Try to avoid IN use JOIN
SELECT SQL_CALC_FOUND_ROWS * FROM (SELECT msisdn, callid, Change_color, play_file_name, date_played FROM insert_log
WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent')
ORDER BY callid ASC) t1 JOIN (SELECT MAX(date_played) AS date_played FROM insert_log GROUP BY callid) t2 ON t1.date_played=t2.date_played
If you are using jQuery 1.2 or newer, you can simply use these:
$(window).width();
$(document).width();
$(window).height();
$(document).height();
From there it is a simple matter to decide the height of your element.
From definition of IGrouping :
IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable
you can just iterate through elements like this:
IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.ID)
foreach(IEnumerable<smth> element in groups)
{
//do something
}
git checkout origin/[branch] .
git status
// Note dot (.) at the end. And all will be good
Adding to @mob's answer:
Appending %N
to date +%s
gives us nanosecond accuracy:
start=`date +%s%N`;<command>;end=`date +%s%N`;echo `expr $end - $start`
Logical OR :- returns true if at least one of the operands evaluate to true. Both operands are evaluated before apply the OR operator.
Short Circuit OR :- if left hand side operand returns true, it returns true without evaluating the right hand side operand.
So you have "a list of tuples", let me assume that you are manipulating some 2-dimension matrix, and, in this case, one convenient interface to accomplish what you need is the one numpy
provides.
Say you have an array arr = numpy.array([[1, 2], [3, 4], [5, 6]])
, you can use arr[:, 0]
to get a new array of all the first elements in each "tuple".
function filesModelDirective(){
return {
controller: function($parse, $element, $attrs, $scope){
var exp = $parse($attrs.filesModel);
$element.on('change', function(){
exp.assign($scope, this.files[0]);
$scope.$apply();
});
}
};
}
app.directive('filesModel', filesModelDirective);
Just right click the Project -- Properties and select Resource on the left side menu.
You can now change the Text-file encoding to whatever you wish.
I've created a new data
selector that should enable you to do nested querying and AND conditions. Usage:
$('a:data(category==music,artist.name==Madonna)');
The pattern is:
:data( {namespace} [{operator} {check}] )
"operator" and "check" are optional. So, if you only have :data(a.b.c)
it will simply check for the truthiness of a.b.c
.
You can see the available operators in the code below. Amongst them is ~=
which allows regex testing:
$('a:data(category~=^mus..$,artist.name~=^M.+a$)');
I've tested it with a few variations and it seems to work quite well. I'll probably add this as a Github repo soon (with a full test suite), so keep a look out!
The code:
(function(){
var matcher = /\s*(?:((?:(?:\\\.|[^.,])+\.?)+)\s*([!~><=]=|[><])\s*("|')?((?:\\\3|.)*?)\3|(.+?))\s*(?:,|$)/g;
function resolve(element, data) {
data = data.match(/(?:\\\.|[^.])+(?=\.|$)/g);
var cur = jQuery.data(element)[data.shift()];
while (cur && data[0]) {
cur = cur[data.shift()];
}
return cur || undefined;
}
jQuery.expr[':'].data = function(el, i, match) {
matcher.lastIndex = 0;
var expr = match[3],
m,
check, val,
allMatch = null,
foundMatch = false;
while (m = matcher.exec(expr)) {
check = m[4];
val = resolve(el, m[1] || m[5]);
switch (m[2]) {
case '==': foundMatch = val == check; break;
case '!=': foundMatch = val != check; break;
case '<=': foundMatch = val <= check; break;
case '>=': foundMatch = val >= check; break;
case '~=': foundMatch = RegExp(check).test(val); break;
case '>': foundMatch = val > check; break;
case '<': foundMatch = val < check; break;
default: if (m[5]) foundMatch = !!val;
}
allMatch = allMatch === null ? foundMatch : allMatch && foundMatch;
}
return allMatch;
};
}());
A solution to this problem, without having to introduce complex functions and heavily modify the original one, is to store the value in a temporary file and read / write it when needed.
This approach helped me greatly when I had to mock a bash function called multiple times in a bats test case.
For example, you could have:
# Usage read_value path_to_tmp_file
function read_value {
cat "${1}"
}
# Usage: set_value path_to_tmp_file the_value
function set_value {
echo "${2}" > "${1}"
}
#----
# Original code:
function test1() {
e=4
set_value "${tmp_file}" "${e}"
echo "hello"
}
# Create the temp file
# Note that tmp_file is available in test1 as well
tmp_file=$(mktemp)
# Your logic
e=2
# Store the value
set_value "${tmp_file}" "${e}"
# Run test1
test1
# Read the value modified by test1
e=$(read_value "${tmp_file}")
echo "$e"
The drawback is that you might need multiple temp files for different variables. And also you might need to issue a sync
command to persist the contents on the disk between one write and read operations.
Expanding on Sjoerd's anti-join, you can also use the easy to understand SELECT WHERE X NOT IN (SELECT)
pattern.
SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN (SELECT pd.part_num FROM wpsapi4.product_details pd)
Note that you only need to use `
backticks on reserved words, names with spaces and such, not with normal column names.
On MySQL 5+ this kind of query runs pretty fast.
On MySQL 3/4 it's slow.
Make sure you have indexes on the fields in question
You need to have an index on pm.id
, pd.part_num
.
This should be what you are looking for using jQuery.
$(function(){
$('#header_nav').data('size','big');
});
$(window).scroll(function(){
if($(document).scrollTop() > 0)
{
if($('#header_nav').data('size') == 'big')
{
$('#header_nav').data('size','small');
$('#header_nav').stop().animate({
height:'40px'
},600);
}
}
else
{
if($('#header_nav').data('size') == 'small')
{
$('#header_nav').data('size','big');
$('#header_nav').stop().animate({
height:'100px'
},600);
}
}
});
Demonstration: http://jsfiddle.net/jezzipin/JJ8Jc/
I found it much easier to debut by printing out where each row meets the condition:
for n in df.columns:
if(np.where(df[n] == 103)):
print(n)
print(df[df[n] == 103].index)
You can use the -B
option.
-B, --block-size=SIZE use SIZE-byte blocks
All together,
df -BG
Building on Lucas's answer above, this is an overload that takes a controller name as parameter, similar to ActionLink. Use this overload when your image links to an Action in a different controller.
// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, string controllerName, object routeValues, string imagePath, string alt)
{
var url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
imgBuilder.MergeAttribute("alt", alt);
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
pip install django-cors-headers
and then add it to your installed apps:
INSTALLED_APPS = (
...
'corsheaders',
...
)
You will also need to add a middleware class to listen in on responses:
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
CORS_ORIGIN_ALLOW_ALL = True # If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
'http://localhost:3030',
] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True`
CORS_ORIGIN_REGEX_WHITELIST = [
'http://localhost:3030',
]
more details: https://github.com/ottoyiu/django-cors-headers/#configuration
read the official documentation can resolve almost all problem
You can get all the information of active transaction by the help of below query
SELECT
trans.session_id AS [SESSION ID],
ESes.host_name AS [HOST NAME],login_name AS [Login NAME],
trans.transaction_id AS [TRANSACTION ID],
tas.name AS [TRANSACTION NAME],tas.transaction_begin_time AS [TRANSACTION
BEGIN TIME],
tds.database_id AS [DATABASE ID],DBs.name AS [DATABASE NAME]
FROM sys.dm_tran_active_transactions tas
JOIN sys.dm_tran_session_transactions trans
ON (trans.transaction_id=tas.transaction_id)
LEFT OUTER JOIN sys.dm_tran_database_transactions tds
ON (tas.transaction_id = tds.transaction_id )
LEFT OUTER JOIN sys.databases AS DBs
ON tds.database_id = DBs.database_id
LEFT OUTER JOIN sys.dm_exec_sessions AS ESes
ON trans.session_id = ESes.session_id
WHERE ESes.session_id IS NOT NULL
and it will give below similar result
and you close that transaction by the help below KILL query by refering session id
KILL 77
First, exend JFrame properly with a super() and a constructor then add actionlisteners to the frame and add the buttons.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Calc extends JFrame implements ActionListener {
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
public Calc()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(100, 100);
button1.addActionListener(this);
button2.addActionListener(this);
calcFrame.add(button1);
calcFrame.add(button2);
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source == button1)
{
\\button1 code here
} else if(source == button2)
{
\\button2 code here
}
}
public static void main(String[] args)
{
JFrame calcFrame = new JFrame();
calcFrame.setVisible(true);
}
}
Simply apply Twitter Bootstrap
text-success
class on Glyphicon:
<span class="glyphicon glyphicon-play text-success">????? ??????</span>
Full list of available colors: Bootstrap Documentation: Helper classes
(Blue is present also)
for example I faced this in express node.js when trying to create route for paths not starting with /internal
app.get(`\/(?!internal).*`, (req, res)=>{
and after long trying it just worked when passing it as a RegExp Object using new RegExp()
app.get(new RegExp("\/(?!internal).*"), (req, res)=>{
this may help if you are getting this common issue in routing
With the integration of JEP 325: Switch Expressions (Preview) in JDK-12 early access builds, one can now make use of the new form of the switch label as :-
case text1, text4 -> {
//blah
}
or to rephrase the demo from one of the answers, something like :-
public class RephraseDemo {
public static void main(String[] args) {
int month = 9;
int year = 2018;
int numDays = 0;
switch (month) {
case 1, 3, 5, 7, 8, 10, 12 ->{
numDays = 31;
}
case 4, 6, 9, 11 ->{
numDays = 30;
}
case 2 ->{
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
}
default ->{
System.out.println("Invalid month.");
}
}
System.out.println("Number of Days = " + numDays);
}
}
Here is how you can give it a try - Compile a JDK12 preview feature with Maven
Its simple If you are passing String X from A to B.
A--> B
In Activity A
1) Create Intent
2) Put data in intent using putExtra method of intent
3) Start activity
Intent i = new Intent(A.this, B.class);
i.putExtra("MY_kEY",X);
In Activity B
inside onCreate method
1) Get intent object
2) Get stored value using key(MY_KEY)
Intent intent = getIntent();
String result = intent.getStringExtra("MY_KEY");
This is the standard way to send data from A to B. you can send any data type, it could be int, boolean, ArrayList, String[]. Based on the datatype you stored in Activity as key, value pair retrieving method might differ like if you are passing int value then you will call
intent.getIntExtra("KEY");
You can even send Class objects too but for that, you have to make your class object implement the Serializable or Parceable interface.
How much data you can send across size. If data exceeds a certain amount in size then you might get TransactionTooLargeException. Suppose you are trying to send bitmap across the activity and if the size exceeds certain data size then you might see this exception.
This is pretty simple here is an example
Add your command code here like:
if (cmd === `!dm`) {
let dUser =
message.guild.member(message.mentions.users.first()) ||
message.guild.members.get(args[0]);
if (!dUser) return message.channel.send("Can't find user!");
if (!message.member.hasPermission('ADMINISTRATOR'))
return message.reply("You can't you that command!");
let dMessage = args.join(' ').slice(22);
if (dMessage.length < 1) return message.reply('You must supply a message!');
dUser.send(`${dUser} A moderator from WP Coding Club sent you: ${dMessage}`);
message.author.send(
`${message.author} You have sent your message to ${dUser}`
);
}
Reading a file in batches of BATCH_SIZE
lines (the last batch can be shorter):
BATCH_SIZE = 1000 # lines
with open('/path/to/a/file') as fin:
eof = False
while eof is False:
# We use an iterator to check later if it was fully realized. This
# is a way to know if we reached the EOF.
# NOTE: file.tell() can't be used with iterators.
batch_range = iter(range(BATCH_SIZE))
acc = [line for (_, line) in zip(batch_range, fin)]
# DO SOMETHING WITH "acc"
# If we still have something to iterate, we have read the whole
# file.
if any(batch_range):
eof = True
This is probably what you wanted:
$('#elem').fadeTo('slow', 0.3, function()
{
$(this).css('background-image', 'url(' + $img + ')');
}).fadeTo('slow', 1);
With a 1 second delay:
$('#elem').fadeTo('slow', 0.3, function()
{
$(this).css('background-image', 'url(' + $img + ')');
}).delay(1000).fadeTo('slow', 1);
Add this extension to convert your html code to a regular string:
extension String {
var html2AttributedString: NSAttributedString? {
guard
let data = dataUsingEncoding(NSUTF8StringEncoding)
else { return nil }
do {
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
And then you show your String inside an UITextView Or UILabel
textView.text = yourString.html2String
or
label.text = yourString.html2String
You are logging sup
directly which is a string
console.log('sup')
Also you are using the wrong id
The template says #main_search
but you are using #searchBar
I suppose you are trying this out
$(function() {
var sup = $('#main_search').val('hi')
console.log(sup); // sup is a variable here
});
You can also reference the obj
once you are inside the function instead of this
.
var obj = {
key1: "it",
key2: function(){return obj.key1 + " works!"}
};
alert(obj.key2());
This SO thread will solve your problem. Solution in short:
$url = 'http://www.google.co.in/intl/en_com/images/srpr/logo1w.png';
$img = '/my/folder/my_image.gif';
file_put_contents($img, file_get_contents($url));
This can de done in a relatively elegant way using SELECT DISTINCT
, as follows:
SELECT DISTINCT ON (sensorID)
sensorID, timestamp, sensorField1, sensorField2
FROM sensorTable
ORDER BY sensorID, timestamp DESC;
The above works for PostgreSQL (some more info here) but I think also other engines. In case it's not obvious, what this does is sort the table by sensor ID and timestamp (newest to oldest), and then returns the first row (i.e. latest timestamp) for each unique sensor ID.
In my use case I have ~10M readings from ~1K sensors, so trying to join the table with itself on a timestamp-based filter is very resource-intensive; the above takes a couple of seconds.
In my case I had a symlink for the 404'd file and my Tomcat was not configured to allow symlinks.
I know that it is not likely to be the cause for most people, but if you are desperate, check this possibility just in case.
Best way I have used is to mount the VS 2010 Image or insert the Installation disc and run the uninstall
option, really works well
Probably the path you supplied was not correct. Check that.
I would recomment the article Howto: (Almost) Everything In Active Directory via C# which really helped me in the past in dealing with AD.
You can also do it using phpmyadmin. Just select the table than go to actions. And change the Auto increment below table options. Don't forget to click on start
Now that TypeScript 2.2 supports Mixins through Class expressions we have a much better way to express Mixins on Components. Mind you that you can also use Component inheritance since angular 2.3 (discussion) or a custom decorator as discussed in other answers here. However, I think Mixins have some properties that make them preferable for reusing behavior across components:
I strongly suggest you read the TypeScript 2.2 announcement above to understand how Mixins work. The linked discussions in angular GitHub issues provide additional detail.
You'll need these types:
export type Constructor<T> = new (...args: any[]) => T;
export class MixinRoot {
}
And then you can declare a Mixin like this Destroyable
mixin that helps components keep track of subscriptions that need to be disposed in ngOnDestroy
:
export function Destroyable<T extends Constructor<{}>>(Base: T) {
return class Mixin extends Base implements OnDestroy {
private readonly subscriptions: Subscription[] = [];
protected registerSubscription(sub: Subscription) {
this.subscriptions.push(sub);
}
public ngOnDestroy() {
this.subscriptions.forEach(x => x.unsubscribe());
this.subscriptions.length = 0; // release memory
}
};
}
To mixin Destroyable
into a Component
, you declare your component like this:
export class DashboardComponent extends Destroyable(MixinRoot)
implements OnInit, OnDestroy { ... }
Note that MixinRoot
is only necessary when you want to extend
a Mixin composition. You can easily extend multiple mixins e.g. A extends B(C(D))
. This is the obvious linearization of mixins I was talking about above, e.g. you're effectively composing an inheritnace hierarchy A -> B -> C -> D
.
In other cases, e.g. when you want to compose Mixins on an existing class, you can apply the Mixin like so:
const MyClassWithMixin = MyMixin(MyClass);
However, I found the first way works best for Components
and Directives
, as these also need to be decorated with @Component
or @Directive
anyway.
You can hit the key q (for quit) and it should take you to the prompt.
Please see this link.
You can use the code below:
a {
display: block;
width: 113px;
margin: auto;
}
By setting, in my case, the link to display:block
, it is easier
to position the link.
This works the same when you use a <div>
tag/class.
You can pick any width
you want.
I made two examples from what I think your question might be:
Check this out for storing additional values. It uses data attributes to store the other value:
It means that in table kontakty
you have a row referencing the row in osoby
you want to delete. You have do delete that row first or set a cascade delete on the relation between tables.
Powodzenia!
From Visual Studio 2015 and onward, you need to go to the "Exception Settings" dialog (Ctrl+Alt+E) and check off the "Common Language Runtime Exceptions" (or a specific one you want i.e. ArgumentNullException
) to make it break on handled exceptions.
The HTML tabindex atribute is responsible for indicating if an element is reachable by keyboard navigation. When the user presses the Tab key the focus is shifted from one element to another. By using the tabindex atribute, the tab order flow is shifted.
The Web API basically return 4 type of object: void
, HttpResponseMessage
, IHttpActionResult
, and other strong types. The first version of the Web API returns HttpResponseMessage
which is pretty straight forward HTTP response message.
The IHttpActionResult
was introduced by WebAPI 2 which is a kind of wrap of HttpResponseMessage
. It contains the ExecuteAsync()
method to create an HttpResponseMessage
. It simplifies unit testing of your controller.
Other return type are kind of strong typed classes serialized by the Web API using a media formatter into the response body. The drawback was you cannot directly return an error code such as a 404. All you can do is throwing an HttpResponseException
error.
You will see it only when the file is open. When you'll close the file in Visual Studio the warnings goes away
Here is a great article explaining ByteBuffer benefits. Following are the key points in the article:
Following are benefits specifically for direct ByteBuffer/MappedByteBuffer. Note that direct buffers are created outside of heap:
Unaffected by gc cycles: Direct buffers won't be moved during garbage collection cycles as they reside outside of heap. TerraCota's BigMemory caching technology seems to rely heavily on this advantage. If they were on heap, it would slow down gc pause times.
Performance boost: In stream IO, read calls would entail system calls, which require a context-switch between user to kernel mode and vice versa, which would be costly especially if file is being accessed constantly. However, with memory-mapping this context-switching is reduced as data is more likely to be found in memory (MappedByteBuffer). If data is available in memory, it is accessed directly without invoking OS, i.e., no context-switching.
Note that MappedByteBuffers are very useful especially if the files are big and few groups of blocks are accessed more frequently.
Use given lines in OnActionExecuting for Action and Controller name.
string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();