For me , when the list crosses one line on my IDE, then it's one parameter too many. I want to see all the parameters in one line without breaking eye contact. But that's just my personal preference.
To delete all files and directories within the current directory:
find . -mtime +3 | xargs rm -Rf
Or alternatively, more in line with the OP's original command:
find . -mtime +3 -exec rm -Rf -- {} \;
for
loop, you're iterating through the elements of a list a
. But in the body of the loop, you're using those items to index that list, when you actually want indexes.a
would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the list a
, which obviously is not there. This will give you an IndexError
. We can fix this issue by iterating over a range of indexes instead:
for i in range(len(a))
and access the a
's items like that: a[i]
. This won't give any errors.
a[i]
, but also a[i+1]
. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get an IndexError
. Why? Because range(5)
is essentially 0 1 2 3 4
, so when the loop reaches 4, you will attempt to get the a[5]
item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting the a[5]
would mean getting the sixth element which does not exist.To fix that, you should subtract 1 from len(a)
in order to get a range sequence 0 1 2 3
. Since you're using an index i+1
, you'll still get the last element, but this way you will avoid the error.
b = [a[i] + a[i+1] for i in range(len(a) - 1)]
This does the job in only one line.
Easiest Way to Uplaod a file
$FileName = $file_name;
$path = 'Users/Desktop/uploads/images';
$location = $path . $data['name'];
move_uploaded_file($data['temp_name'],$location);
You can use the fnSort function, see the details here:
You can also use std::list
instead of std::vector
. list
has a built-in function list::reverse for reversing elements.
This is the best way (IMHO).
List<String> myArrayList = new ArrayList<String>();
//.....
String[] myArray = myArrayList.toArray(new String[myArrayList.size()]);
This code works also:
String[] myArray = myArrayList.toArray(new String[0]);
But it less effective: the string array is created twice: first time zero-length array is created, then the real-size array is created, filled and returned. So, if since you know the needed size (from list.size()
) you should create array that is big enough to put all elements. In this case it is not re-allocated.
On my projects i give all rows the class "borders" which I want it to display more like a table with even borders. Giving each child element a border on the bottom and right and the first element of each row a left border will make all of your boxes have an even border:
First give all of the rows children a border on the right and bottom
.borders div{
border-right:1px solid #999;
border-bottom:1px solid #999;
}
Next give the first child of each or a left border
.borders div:first-child{
border-left:
1px solid #999;
}
Last make sure to clear the borders for their child elements
.borders div > div{
border:0;
}
HTML:
<div class="row borders">
<div class="col-xs-5 col-md-2">Email</div>
<div class="col-xs-7 col-md-4">[email protected]</div>
<div class="col-xs-5 col-md-2">Phone</div>
<div class="col-xs-7 col-md-4">555-123-4567</div>
</div>
I use the power of awk to delete some of my stopped docker containers. Observe carefully how i construct the cmd
string first before passing it to system
.
docker ps -a | awk '$3 ~ "/bin/clish" { cmd="docker rm "$1;system(cmd)}'
Here, I use the 3rd column having the pattern "/bin/clish" and then I extract the container ID in the first column to construct my cmd
string and passed that to system
.
There are two ways you could do this. Either create your own custom exception class to represent a divide by zero error or throw the same type of exception the java runtime would throw in this situation.
public class DivideByZeroException() extends ArithmeticException {
}
Then in your code you would check for a divide by zero and throw this exception:
if (divisor == 0) throw new DivideByZeroException();
Add to your code the check for a divide by zero and throw an arithmetic exception:
if (divisor == 0) throw new java.lang.ArithmeticException("/ by zero");
Additionally, you could consider throwing an illegal argument exception since a divisor of zero is an incorrect argument to pass to your setKp() method:
if (divisor == 0) throw new java.lang.IllegalArgumentException("divisor == 0");
try this it worked in my case
backgroundImage: `url("${Background}")`
This error is cause by security clutches between the web application and your java. To resolve it, look into your java setting under control panel. Move the security level to a medium.
To prevent deadlocks I always try to use Task.Run()
when I have to call an async method synchronously that @Heinzi mentions.
However the method has to be modified if the async method uses parameters. For example Task.Run(GenerateCodeAsync("test")).Result
gives the error:
Argument 1: cannot convert from '
System.Threading.Tasks.Task<string>
' to 'System.Action'
This could be called like this instead:
string code = Task.Run(() => GenerateCodeAsync("test")).Result;
what you need is:
[\-\+]?[0-9]*(\.[0-9]+)?
I escaped the "+" and "-" sign and also grouped the decimal with its following digits since something like "1." is not a valid number.
The changes will allow you to match integers and floats. for example:
0
+1
-2.0
2.23442
This is changed in Java 6 update 18.
Assuming that we have more than 1 GB of physical memory (quite common these days), it's always 1/4th of your physical memory for the server vm.
I got this to work as follows:
First ensure that in your dataTable
definition your aoColumns
array includes sWidth
data expressed as a % not fixed pixels or ems.
Then ensure you have set the bAutoWidth
property to false
Then add this little but of JS:
update_table_size = function(a_datatable) {
if (a_datatable == null) return;
var dtb;
if (typeof a_datatable === 'string') dtb = $(a_datatable)
else dtb = a_datatable;
if (dtb == null) return;
dtb.css('width', dtb.parent().width());
dtb.fnAdjustColumSizing();
}
$(window).resize(function() {
setTimeout(function(){update_table_size(some_table_selector_or_table_ref)}, 250);
});
Works a treat and my table cells handle the white-space: wrap;
CSS (which wasn't working without setting the sWidth
, and was what led me to this question.)
Try This
private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath + "/AudioRecorder" );
if (!file.exists()) {
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".mp4");
}
I have encountered that same problem: newer php version doesn't deal the same with multiple incluse of the same file (as a library), so now I have to change all my include by some include_once.
Or this tricks could help, if you d'ont have too much class in your library...
if( class_exists('TestClass') != true )
{
//your definition of TestClass
}
Underscore and Lodash have the _.last(Array)
method, that returns the last element in an Array. They both work about the same
_.last([5, 4, 3, 2, 1]);
=> 1
Ramda also has a _.last
function
R.last(['fi', 'fo', 'fum']); //=> 'fum'
Swift 5.0 + , Simple and Short
example:
Style 1
func methodName(completionBlock: () -> Void) {
print("block_Completion")
completionBlock()
}
Style 2
func methodName(completionBlock: () -> ()) {
print("block_Completion")
completionBlock()
}
Use:
override func viewDidLoad() {
super.viewDidLoad()
methodName {
print("Doing something after Block_Completion!!")
}
}
Output
block_Completion
Doing something after Block_Completion!!
if you just need to get a key-value from a simple dictionary like e.g:
os_type = {'ubuntu': '20.04'}
use popitem()
method:
os, version = os_type.popitem()
print(os) # 'ubuntu'
print(version) # '20.04'
I Got the Solution Guys
You need to keep some points in your mind .
There are two different dependency one is (poi) & other dependency is (poi- ooxml) but make sure you must use poi-ooxml dependency in your code.
Just Add the following dependency in pom.xml & Save it.
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
3 .After you have saved the pom.xml then you need to try a small thing ,Use (.) operator will try to import/fetch it & finally will not see any sort of error because now it has imported that thing in your package.
Sample Code to Understand Better !!
package ReadFile;// package
import org.apache.poi.xssf.usermodel.XSSFWorkbook; // automatically added to your code after importing
public class Test
{
public static void Hello() // Method
{
XSSFWorkbook workbook = new XSSFWorkbook();
}
}
I tried my best to give you the solution , If you face any issue comment here i will try
to solve it .
Keep Learning Guys !!
Try This... It's very simple just use confirm dialog box for alert with YES|NO.
if(confirm("Do you want to upgrade?")){ Your code }
I changed the DrawerLayout a bit to get the events and be able to consume and event, such as if you want to use the actionToggle as back if you are in detail view:
public class ListenableDrawerLayout extends DrawerLayout {
private OnToggleButtonClickedListener mOnToggleButtonClickedListener;
private boolean mManualCall;
public ListenableDrawerLayout(Context context) {
super(context);
}
public ListenableDrawerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ListenableDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Sets the listener for the toggle button
*
* @param mOnToggleButtonClickedListener
*/
public void setOnToggleButtonClickedListener(OnToggleButtonClickedListener mOnToggleButtonClickedListener) {
this.mOnToggleButtonClickedListener = mOnToggleButtonClickedListener;
}
/**
* Opens the navigation drawer manually from code<br>
* <b>NOTE: </b>Use this function instead of the normal openDrawer method
*
* @param drawerView
*/
public void openDrawerManual(View drawerView) {
mManualCall = true;
openDrawer(drawerView);
}
/**
* Closes the navigation drawer manually from code<br>
* <b>NOTE: </b>Use this function instead of the normal closeDrawer method
*
* @param drawerView
*/
public void closeDrawerManual(View drawerView) {
mManualCall = true;
closeDrawer(drawerView);
}
@Override
public void openDrawer(View drawerView) {
// Check for listener and for not manual open
if (!mManualCall && mOnToggleButtonClickedListener != null) {
// Notify the listener and behave on its reaction
if (mOnToggleButtonClickedListener.toggleOpenDrawer()) {
return;
}
}
// Manual call done
mManualCall = false;
// Let the drawer layout to its stuff
super.openDrawer(drawerView);
}
@Override
public void closeDrawer(View drawerView) {
// Check for listener and for not manual close
if (!mManualCall && mOnToggleButtonClickedListener != null) {
// Notify the listener and behave on its reaction
if (mOnToggleButtonClickedListener.toggleCloseDrawer()) {
return;
}
}
// Manual call done
mManualCall = false;
// Let the drawer layout to its stuff
super.closeDrawer(drawerView);
}
/**
* Interface for toggle button callbacks
*/
public static interface OnToggleButtonClickedListener {
/**
* The ActionBarDrawerToggle has been pressed in order to open the drawer
*
* @return true if we want to consume the event, false if we want the normal behaviour
*/
public boolean toggleOpenDrawer();
/**
* The ActionBarDrawerToggle has been pressed in order to close the drawer
*
* @return true if we want to consume the event, false if we want the normal behaviour
*/
public boolean toggleCloseDrawer();
}
}
I tend not to use the .on() syntax, if not necessary. For example you can migrate easier like this:
old:
$('.myButton').live('click', function);
new:
$('.myButton').click(function)
Here is a list of valid event handlers: https://api.jquery.com/category/forms/
VBA is not VB/VB.NET
The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:
Do While counter < 20
counter = counter + 1
Loop
(But a For..Next might be more appropriate here.)
Happy coding.
No there isn't and it's probably not there, because there are very few valid uses for it. I would think twice before using it. Also, it is indeed easy to create yourself.
Please refer to this discussion about why it's even in .NET.
I guess UnsupportedOperationException
comes close, although it doesn't say the operation is just not implemented, but unsupported even. That could imply no valid implementation is possible. Why would the operation be unsupported? Should it even be there?
Interface segregation or Liskov substitution issues maybe?
If it's work in progress I'd go for ToBeImplementedException
, but I've never caught myself defining a concrete method and then leave it for so long it makes it into production and there would be a need for such an exception.
I figured it out that x.view(-1, 16 * 5 * 5)
is equivalent to x.flatten(1)
, where the parameter 1 indicates the flatten process starts from the 1st dimension(not flattening the 'sample' dimension)
As you can see, the latter usage is semantically more clear and easier to use, so I prefer flatten()
.
In order for the client to be able to read cookies from cross-origin requests, you need to have:
All responses from the server need to have the following in their header:
Access-Control-Allow-Credentials: true
The client needs to send all requests with withCredentials: true
option
In my implementation with Angular 7 and Spring Boot, I achieved that with the following:
Server-side:
@CrossOrigin(origins = "http://my-cross-origin-url.com", allowCredentials = "true")
@Controller
@RequestMapping(path = "/something")
public class SomethingController {
...
}
The origins = "http://my-cross-origin-url.com"
part will add Access-Control-Allow-Origin: http://my-cross-origin-url.com
to every server's response header
The allowCredentials = "true"
part will add Access-Control-Allow-Credentials: true
to every server's response header, which is what we need in order for the client to read the cookies
Client-side:
import { HttpInterceptor, HttpXsrfTokenExtractor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from 'rxjs';
@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
constructor(private tokenExtractor: HttpXsrfTokenExtractor) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// send request with credential options in order to be able to read cross-origin cookies
req = req.clone({ withCredentials: true });
// return XSRF-TOKEN in each request's header (anti-CSRF security)
const headerName = 'X-XSRF-TOKEN';
let token = this.tokenExtractor.getToken() as string;
if (token !== null && !req.headers.has(headerName)) {
req = req.clone({ headers: req.headers.set(headerName, token) });
}
return next.handle(req);
}
}
With this class you actually inject additional stuff to all your request.
The first part req = req.clone({ withCredentials: true });
, is what you need in order to send each request with withCredentials: true
option. This practically means that an OPTION request will be send first, so that you get your cookies and the authorization token among them, before sending the actual POST/PUT/DELETE requests, which need this token attached to them (in the header), in order for the server to verify and execute the request.
The second part is the one that specifically handles an anti-CSRF token for all requests. Reads it from the cookie when needed and writes it in the header of every request.
The desired result is something like this:
I was facing the same problem trying to truncate a VARCHAR from 32 to 8 and getting the ERROR: value too long for type character varying(8)
. I want to stay as close to SQL as possible because I'm using a self-made JPA-like structure that we might have to switch to different DBMS according to customer's choices (PostgreSQL being the default one). Hence, I don't want to use the trick of altering System tables.
I ended using the USING
statement in the ALTER TABLE
:
ALTER TABLE "MY_TABLE" ALTER COLUMN "MyColumn" TYPE varchar(8)
USING substr("MyColumn", 1, 8)
As @raylu noted, ALTER
acquires an exclusive lock on the table so all other operations will be delayed until it completes.
You need to do the following
git fetch -p
This will update the local database of remote branches.
Ken's answer is basically right but I'd like to chime in on the "why would you want to use one over the other?" part of your question.
The base interface you choose for your repository has two main purposes. First, you allow the Spring Data repository infrastructure to find your interface and trigger the proxy creation so that you inject instances of the interface into clients. The second purpose is to pull in as much functionality as needed into the interface without having to declare extra methods.
The Spring Data core library ships with two base interfaces that expose a dedicated set of functionalities:
CrudRepository
- CRUD methodsPagingAndSortingRepository
- methods for pagination and sorting (extends CrudRepository
)The individual store modules (e.g. for JPA or MongoDB) expose store-specific extensions of these base interfaces to allow access to store-specific functionality like flushing or dedicated batching that take some store specifics into account. An example for this is deleteInBatch(…)
of JpaRepository
which is different from delete(…)
as it uses a query to delete the given entities which is more performant but comes with the side effect of not triggering the JPA-defined cascades (as the spec defines it).
We generally recommend not to use these base interfaces as they expose the underlying persistence technology to the clients and thus tighten the coupling between them and the repository. Plus, you get a bit away from the original definition of a repository which is basically "a collection of entities". So if you can, stay with PagingAndSortingRepository
.
The downside of directly depending on one of the provided base interfaces is two-fold. Both of them might be considered as theoretical but I think they're important to be aware of:
Page
or Pageable
in your code anyway. Spring Data is not any different from any other general purpose library like commons-lang or Guava. As long as it provides reasonable benefit, it's just fine.CrudRepository
, you expose a complete set of persistence method at once. This is probably fine in most circumstances as well but you might run into situations where you'd like to gain more fine-grained control over the methods expose, e.g. to create a ReadOnlyRepository
that doesn't include the save(…)
and delete(…)
methods of CrudRepository
.The solution to both of these downsides is to craft your own base repository interface or even a set of them. In a lot of applications I have seen something like this:
interface ApplicationRepository<T> extends PagingAndSortingRepository<T, Long> { }
interface ReadOnlyRepository<T> extends Repository<T, Long> {
// Al finder methods go here
}
The first repository interface is some general purpose base interface that actually only fixes point 1 but also ties the ID type to be Long
for consistency. The second interface usually has all the find…(…)
methods copied from CrudRepository
and PagingAndSortingRepository
but does not expose the manipulating ones. Read more on that approach in the reference documentation.
The repository abstraction allows you to pick the base repository totally driven by you architectural and functional needs. Use the ones provided out of the box if they suit, craft your own repository base interfaces if necessary. Stay away from the store specific repository interfaces unless unavoidable.
If url contains a certen string, redirect to index.php . You need to match against the %{REQUEST_URI} variable to check if the url contains a certen string.
To redirect example.com/foo/bar to /index.php if the uri contains bar anywhere in the uri string , you can use this :
RewriteEngine on
RewriteCond %{REQUEST_URI} bar
RewriteRule ^ /index.php [L,R]
Post 2020 method, using dynamic import, self executing IIFE, asynchronous function!
(async () => {
await import('https://code.jquery.com/jquery-2.2.4.min.js')
// Library ready
console.log(jQuery)
})()
_x000D_
Take command prompt with administrator privilege
Change directory to where the .sql file stored
Execute the following command
sqlcmd -S 'your server name' -U 'user name of server' -P 'password of server' -d 'db name'-i script.sql
Well, this has a bunch of answers already, but unfortunately there's not a "true" random in the bunch. The version below is an adaptation of broofa's answer, but updated to include a "true" random function that uses crypto libraries where available, and the Alea() function as a fallback.
Math.log2 = Math.log2 || function(n){ return Math.log(n) / Math.log(2); }
Math.trueRandom = (function() {
var crypt = window.crypto || window.msCrypto;
if (crypt && crypt.getRandomValues) {
// if we have a crypto library, use it
var random = function(min, max) {
var rval = 0;
var range = max - min;
if (range < 2) {
return min;
}
var bits_needed = Math.ceil(Math.log2(range));
if (bits_needed > 53) {
throw new Exception("We cannot generate numbers larger than 53 bits.");
}
var bytes_needed = Math.ceil(bits_needed / 8);
var mask = Math.pow(2, bits_needed) - 1;
// 7776 -> (2^13 = 8192) -1 == 8191 or 0x00001111 11111111
// Create byte array and fill with N random numbers
var byteArray = new Uint8Array(bytes_needed);
crypt.getRandomValues(byteArray);
var p = (bytes_needed - 1) * 8;
for(var i = 0; i < bytes_needed; i++ ) {
rval += byteArray[i] * Math.pow(2, p);
p -= 8;
}
// Use & to apply the mask and reduce the number of recursive lookups
rval = rval & mask;
if (rval >= range) {
// Integer out of acceptable range
return random(min, max);
}
// Return an integer that falls within the range
return min + rval;
}
return function() {
var r = random(0, 1000000000) / 1000000000;
return r;
};
} else {
// From https://web.archive.org/web/20120502223108/http://baagoe.com/en/RandomMusings/javascript/
// Johannes Baagøe <[email protected]>, 2010
function Mash() {
var n = 0xefc8249d;
var mash = function(data) {
data = data.toString();
for (var i = 0; i < data.length; i++) {
n += data.charCodeAt(i);
var h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
mash.version = 'Mash 0.9';
return mash;
}
// From http://baagoe.com/en/RandomMusings/javascript/
function Alea() {
return (function(args) {
// Johannes Baagøe <[email protected]>, 2010
var s0 = 0;
var s1 = 0;
var s2 = 0;
var c = 1;
if (args.length == 0) {
args = [+new Date()];
}
var mash = Mash();
s0 = mash(' ');
s1 = mash(' ');
s2 = mash(' ');
for (var i = 0; i < args.length; i++) {
s0 -= mash(args[i]);
if (s0 < 0) {
s0 += 1;
}
s1 -= mash(args[i]);
if (s1 < 0) {
s1 += 1;
}
s2 -= mash(args[i]);
if (s2 < 0) {
s2 += 1;
}
}
mash = null;
var random = function() {
var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32
s0 = s1;
s1 = s2;
return s2 = t - (c = t | 0);
};
random.uint32 = function() {
return random() * 0x100000000; // 2^32
};
random.fract53 = function() {
return random() +
(random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
};
random.version = 'Alea 0.9';
random.args = args;
return random;
}(Array.prototype.slice.call(arguments)));
};
return Alea();
}
}());
Math.guid = function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.trueRandom() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
As mentioned in .NET Framework documentation
We don't recommend that you use the
ArrayList
class for new development. Instead, we recommend that you use the genericList<T>
class. TheArrayList
class is designed to hold heterogeneous collections of objects. However, it does not always offer the best performance. Instead, we recommend the following:
- For a heterogeneous collection of objects, use the
List<Object>
(in C#) orList(Of Object)
(in Visual Basic) type.- For a homogeneous collection of objects, use the
List<T>
class.
This is a circular dependency issue. Golang programs must be acyclic. In Golang cyclic imports are not allowed (That is its import graph must not contain any loops)
Lets say your project go-circular-dependency
have 2 packages "package one" & it has "one.go" & "package two" & it has "two.go" So your project structure is as follows
+--go-circular-dependency
+--one
+-one.go
+--two
+-two.go
This issue occurs when you try to do something like following.
Step 1 - In one.go
you import package two
(Following is one.go
)
package one
import (
"go-circular-dependency/two"
)
//AddOne is
func AddOne() int {
a := two.Multiplier()
return a + 1
}
Step 2 - In two.go
you import package one
(Following is two.go
)
package two
import (
"fmt"
"go-circular-dependency/one"
)
//Multiplier is going to be used in package one
func Multiplier() int {
return 2
}
//Total is
func Total() {
//import AddOne from "package one"
x := one.AddOne()
fmt.Println(x)
}
In Step 2, you will receive an error "can't load package: import cycle not allowed" (This is called "Circular Dependency" error)
Technically speaking this is bad design decision and you should avoid this as much as possible, but you can "Break Circular Dependencies via implicit interfaces" (I personally don't recommend, and highly discourage this practise, because by design Go programs must be acyclic)
Try to keep your import dependency shallow. When the dependency graph becomes deeper (i.e package x imports y, y imports z, z imports x) then circular dependencies become more likely.
Sometimes code repetition is not bad idea, which is exactly opposite of DRY (don't repeat yourself)
So in Step 2 that is in two.go
you should not import package one. Instead in two.go
you should actually replicate the functionality of AddOne()
written in one.go
as follows.
package two
import (
"fmt"
)
//Multiplier is going to be used in package one
func Multiplier() int {
return 2
}
//Total is
func Total() {
// x := one.AddOne()
x := Multiplier() + 1
fmt.Println(x)
}
Pythonic way to do this is ...
np.divide(data.T,vector).T
This takes care of reshaping and also the results are in floating point format. In other answers results are in rounded integer format.
#NOTE: No of columns in both data and vector should match
I use SingleOrDefault
in situations where my logic dictates that the will be either zero or one results. If there are more, it's an error situation, which is helpful.
public static Date convertTimestampToDate(Timestamp timestamp) {
Instant ins=timestamp.toLocalDateTime().atZone(ZoneId.systemDefault()).toInstant();
return Date.from(ins);
}
You should do like this:
@Html.DropDownListFor(m => m.ContribType,
new SelectList(Model.ContribTypeOptions,
"ContribId", "Value"))
Where:
m => m.ContribType
is a property where the result value will be.
extern std::pair<std::string_view, Base*(*)()> const factories[2];
decltype(factories) factories{
{"blah", []() -> Base*{return new Blah;}},
{"foo", []() -> Base*{return new Foo;}}
};
I have been trying to think of a good convention to use when placing text next to components on different lines, and found a couple good options:
<p>
Hello {
<span>World</span>
}!
</p>
or
<p>
Hello {}
<span>World</span>
{} again!
</p>
Each of these produces clean html without additional
or other extraneous markup. It creates fewer text nodes than using {' '}
, and allows using of html entities where {' hello & goodbye '}
does not.
Using single quotes for keys are not allowed in JSON. You need to use double quotes.
For your use-case perhaps this would be the easiest solution:
str = '{"a":1}';
If a property requires quotes, double quotes must be used. All property names must be surrounded by double quotes.
Installing the Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019 worked for me with a similar problem, and helped with another (slightly different) driver issue.
Pass the string and replace space with line break, it gives you desired result.
select replace('shailendra kumar',' ',chr(10)) from dual;
Sometimes two classes may have some parameter names in common. In that case, you can't pop the key-value pairs off of **kwargs
or remove them from *args
. Instead, you can define a Base
class which unlike object
, absorbs/ignores arguments:
class Base(object):
def __init__(self, *args, **kwargs): pass
class A(Base):
def __init__(self, *args, **kwargs):
print "A"
super(A, self).__init__(*args, **kwargs)
class B(Base):
def __init__(self, *args, **kwargs):
print "B"
super(B, self).__init__(*args, **kwargs)
class C(A):
def __init__(self, arg, *args, **kwargs):
print "C","arg=",arg
super(C, self).__init__(arg, *args, **kwargs)
class D(B):
def __init__(self, arg, *args, **kwargs):
print "D", "arg=",arg
super(D, self).__init__(arg, *args, **kwargs)
class E(C,D):
def __init__(self, arg, *args, **kwargs):
print "E", "arg=",arg
super(E, self).__init__(arg, *args, **kwargs)
print "MRO:", [x.__name__ for x in E.__mro__]
E(10)
yields
MRO: ['E', 'C', 'A', 'D', 'B', 'Base', 'object']
E arg= 10
C arg= 10
A
D arg= 10
B
Note that for this to work, Base
must be the penultimate class in the MRO.
With Cinchoo ETL - an open source library, it can automatically handles columns values containing separators.
string csv = @"2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,""Corvallis, OR"",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";
using (var p = ChoCSVReader.LoadText(csv)
)
{
Console.WriteLine(p.Dump());
}
Output:
Key: Column1 [Type: String]
Value: 2
Key: Column2 [Type: String]
Value: 1016
Key: Column3 [Type: String]
Value: 7/31/2008 14:22
Key: Column4 [Type: String]
Value: Geoff Dalgas
Key: Column5 [Type: String]
Value: 6/5/2011 22:21
Key: Column6 [Type: String]
Value: http://stackoverflow.com
Key: Column7 [Type: String]
Value: Corvallis, OR
Key: Column8 [Type: String]
Value: 7679
Key: Column9 [Type: String]
Value: 351
Key: Column10 [Type: String]
Value: 81
Key: Column11 [Type: String]
Value: b437f461b3fd27387c5d8ab47a293d35
Key: Column12 [Type: String]
Value: 34
For more information, please visit codeproject article.
Hope it helps.
My trick is to put inside the div a table with 1 row and 1 column, set 100% of width and height, and the property vertical-align:middle.
<div>
<table style="width:100%; height:100%;">
<tr>
<td style="vertical-align:middle;">
BUTTON TEXT
</td>
</tr>
</table>
</div>
There's typically two levels of buffering involved:
The internal buffers are buffers created by the runtime/library/language that you're programming against and is meant to speed things up by avoiding system calls for every write. Instead, when you write to a file object, you write into its buffer, and whenever the buffer fills up, the data is written to the actual file using system calls.
However, due to the operating system buffers, this might not mean that the data is written to disk. It may just mean that the data is copied from the buffers maintained by your runtime into the buffers maintained by the operating system.
If you write something, and it ends up in the buffer (only), and the power is cut to your machine, that data is not on disk when the machine turns off.
So, in order to help with that you have the flush
and fsync
methods, on their respective objects.
The first, flush
, will simply write out any data that lingers in a program buffer to the actual file. Typically this means that the data will be copied from the program buffer to the operating system buffer.
Specifically what this means is that if another process has that same file open for reading, it will be able to access the data you just flushed to the file. However, it does not necessarily mean it has been "permanently" stored on disk.
To do that, you need to call the os.fsync
method which ensures all operating system buffers are synchronized with the storage devices they're for, in other words, that method will copy data from the operating system buffers to the disk.
Typically you don't need to bother with either method, but if you're in a scenario where paranoia about what actually ends up on disk is a good thing, you should make both calls as instructed.
Addendum in 2018.
Note that disks with cache mechanisms is now much more common than back in 2013, so now there are even more levels of caching and buffers involved. I assume these buffers will be handled by the sync/flush calls as well, but I don't really know.
Example:
Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.
DROP TABLE IF EXISTS B,C,A;
This can be placed in the beginning of the script instead of individually dropping each table.
Try this code to use:
/* For Mozile Firefox Browser */
::-moz-selection { background-color: #4CAF50; }
/* For Other Browser*/
::selection { background-color: #4CAF50; }
I prefer a css only scheme based on horizontal scroll, like tabs on android. This's my solution, just wrap with a class nav-tabs-responsive:
<div class="nav-tabs-responsive">
<ul class="nav nav-tabs" role="tablist">
<li>...</li>
</ul>
</div>
And two css lines:
.nav-tabs { min-width: 600px; }
.nav-tabs-responsive { overflow: auto; }
600px is the point over you will be responsive (you can set it using bootstrap variables)
This solution is no more supported since jQuery 1.8 as we can read on the blog here:
$(element).data(“events”): This is now removed in 1.8, but you can still get to the events data for debugging purposes via $._data(element, "events"). Note that this is not a supported public interface; the actual data structures may change incompatibly from version to version.
So, you should unbind/rebind it or simply, use a boolean to determine if your event as been attached or not (which is in my opinion the best solution).
Another approach is to use android.intent.action.USER_PRESENT
instead of android.intent.action.BOOT_COMPLETED
to avoid slow downs during the boot process. But this is only true
if the user has enabled the lock Screen - otherwise this intent is never broadcasted.
Reference blog - The Problem With Android’s ACTION_USER_PRESENT Intent
Checking for MSIE only is not enough to detect IE. You need also "Trident" which is only used in IE11. So here is my solution which worked an versions 8 to 11.
$agent=strtoupper($_SERVER['HTTP_USER_AGENT']);
$isIE=(strpos($agent,'MSIE')!==false || strpos($agent,'TRIDENT')!==false);
This is how I did it.
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--disable-extensions')
chrome = webdriver.Chrome(chrome_options=chrome_options)
You can create a Date
object, and call getTime
on it:
new Date(2010, 6, 26).getTime() / 1000
If you are in .NET stack with MVC with AngularJS, this is what you have to do to remove the '#' from url:
Set up your base href in your _Layout page: <head> <base href="/"> </head>
Then, add following in your angular app config : $locationProvider.html5Mode(true)
Above will remove '#' from url but page refresh won't work e.g. if you are in "yoursite.com/about" page refreash will give you a 404. This is because MVC does not know about angular routing and by MVC pattern it will look for a MVC page for 'about' which does not exists in MVC routing path. Workaround for this is to send all MVC page request to a single MVC view and you can do that by adding a route that catches all
url:
routes.MapRoute(
name: "App",
url: "{*url}",
defaults: new {
controller = "Home", action = "Index"
}
);
Re: Tanktalus's (accepted) answer above, a slightly cleaner way is to use:
me=$(readlink --canonicalize --no-newline $0)
If your script has been sourced from another bash script, you can use:
me=$(readlink --canonicalize --no-newline $BASH_SOURCE)
I agree that it would be confusing to dereference symlinks if your objective is to provide feedback to the user, but there are occasions when you do need to get the canonical name to a script or other file, and this is the best way, imo.
The openssl
documentation says that file supplied as the -in
argument must be in PEM format.
Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer
is not PEM format rather it is PKCS7.
In order to create my .p12
, I had to first convert the certificate to PEM:
openssl pkcs7 -in myCert.cer -print_certs -out certs.pem
and then execute
openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem
On Older versions of Python...
map(int,str(123))
On New Version 3k
list(map(int,str(123)))
Thanks to Renato answer, I have created a really basic example:
const exec = require('child_process').exec
exec('git config --global user.name', (err, stdout, stderr) => console.log(stdout))
It will just print your global git username :)
Use immediate children selector >
:
$('#tblOne > tbody > tr')
Description: Selects all direct child elements specified by "child" of elements specified by "parent".
There is no concept of a "background image" in a JPanel
, so one would have to write their own way to implement such a feature.
One way to achieve this would be to override the paintComponent
method to draw a background image on each time the JPanel
is refreshed.
For example, one would subclass a JPanel
, and add a field to hold the background image, and override the paintComponent
method:
public class JPanelWithBackground extends JPanel {
private Image backgroundImage;
// Some code to initialize the background image.
// Here, we use the constructor to load the image. This
// can vary depending on the use case of the panel.
public JPanelWithBackground(String fileName) throws IOException {
backgroundImage = ImageIO.read(new File(fileName));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw the background image.
g.drawImage(backgroundImage, 0, 0, this);
}
}
(Above code has not been tested.)
The following code could be used to add the JPanelWithBackground
into a JFrame
:
JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));
In this example, the ImageIO.read(File)
method was used to read in the external JPEG file.
You can solve this problem using this code:
if(!empty($_GET['variable from which you get']))
{
$_SESSION['something']= $_GET['variable from which you get'];
}
So you get the variable from a GET form, you will store in the $_SESSION['whatever']
variable just once when $_GET['variable from which you get']
is set and if it is empty $_SESSION['something']
will store the old parameter
public static int nth(String source, String pattern, int n) {
int i = 0, pos = 0, tpos = 0;
while (i < n) {
pos = source.indexOf(pattern);
if (pos > -1) {
source = source.substring(pos+1);
tpos += pos+1;
i++;
} else {
return -1;
}
}
return tpos - 1;
}
You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do
for (var i = myArray.length - 1; i >= 0; i--) { console.log(eval(myArray[i])); };
More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.
var result = {}; for (var i = myArray.length - 1; i >= 0; i--) { result[myArray[i]] = eval(myArray[i]); };
I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via
window['myVarName'] = 'namingCollisionsAreFun';
(per comment)
That would be the destructor(freeing up any dynamic memory)
You have to specify the name of the custom view and its related model in Controller Action method.
public ActionResult About()
{
return View("NameOfViewYouWantToReturn",Model);
}
yes if it is SharePoint 2010 and above by using the Office feature co-authoring
A good way to implement containsAny for sets is using the Guava Sets.intersection().
containsAny
would return a boolean
, so the call looks like:
Sets.intersection(set1, set2).isEmpty()
This returns true iff the sets are disjoint, otherwise false. The time complexity of this is likely slightly better than retainAll because you dont have to do any cloning to avoid modifying your original set.
This is really old, but I wanted to add my slight variation for anyone else who may stumble across this. Regular expressions are powerful things.
To keep the text which falls between the equal sign and the comma:
-replace "^.*?=(.*?),.*?$",'$1'
This regular expression starts at the beginning of the line, wipes all characters until the first equal sign, captures every character until the next comma, then wipes every character until the end of the line. It then replaces the entire line with the capture group (anything within the parentheses). It will match any line that contains at least one equal sign followed by at least one comma. It is similar to the suggestion by Trix, but unlike that suggestion, this will not match lines which only contain either an equal sign or a comma, it must have both in order.
I checked on my side by just adding '1.0' and it start working
tex.delete('1.0', END)
you can also try this
Try this:
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
It will work.
find ./someDir -name "*.php" -o -name "*.html" | tar -cf my_archive -T -
for the entire line
^(\w+)\s+(\w+)\s+(\d+(?:\/\d+){2})\s+(\w+)$
If you're in Spring-land you can use PathMatchingResourcePatternResolver
;
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath*:some/package/name/*.class");
Arrays.asList(resources).forEach(r->{
...
});
If you are on a system where netstat
is not available (e.g. RHEL 7 and more recent Debian releases) you can use ss
, as below:
sudo ss -tlpn | grep mysql
And you'll get something like the following for output:
LISTEN 0 50 *:3306 *:* users:(("mysqld",pid=5307,fd=14))
The fourth column is Local Address:Port
. So in this case Mysql is listening on port 3306, the default.
In many situations, a custom attribute attached to a pd.DataFrame
object is not necessary. In addition, note that pandas
-object attributes may not serialize. So pickling will lose this data.
Instead, consider creating a dictionary with appropriately named keys and access the dataframe via dfs['some_label']
.
df = pd.DataFrame()
dfs = {'some_label': df}
read() is equivalent to recv() with a flags parameter of 0. Other values for the flags parameter change the behaviour of recv(). Similarly, write() is equivalent to send() with flags == 0.
Be careful. For this you need @GET (not @PUT).
Unfortunately, PostgreSQL
supports neither MERGE
nor ON DUPLICATE KEY UPDATE
, so you'll have to do it in two statements:
UPDATE invoices
SET billed = 'TRUE'
WHERE invoices = '12345'
INSERT
INTO invoices (invoiceid, billed)
SELECT '12345', 'TRUE'
WHERE '12345' NOT IN
(
SELECT invoiceid
FROM invoices
)
You can wrap it into a function:
CREATE OR REPLACE FUNCTION fn_upd_invoices(id VARCHAR(32), billed VARCHAR(32))
RETURNS VOID
AS
$$
UPDATE invoices
SET billed = $2
WHERE invoices = $1;
INSERT
INTO invoices (invoiceid, billed)
SELECT $1, $2
WHERE $1 NOT IN
(
SELECT invoiceid
FROM invoices
);
$$
LANGUAGE 'sql';
and just call it:
SELECT fn_upd_invoices('12345', 'TRUE')
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind
functions to each result callback; the order of parameters is: (success, failure)
. So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: @get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401
I realize this is an old question, but it took me several hours to find a good solution and thought I'd pass on what I learned here and save someone else the trouble. Try, for example,
SELECT * FROM some_table WHERE id_column = ANY(@id_list)
where @id_list is bound to an int[] parameter by way of
command.Parameters.Add("@id_list", NpgsqlDbType.Array | NpgsqlDbType.Integer).Value = my_id_list;
where command is a NpgsqlCommand (using C# and Npgsql in Visual Studio).
s='foo bar baz'
a=( $s )
echo ${a[0]}
echo ${a[1]}
...
.getJson is simply a wrapper around .ajax but it provides a simpler method signature as some of the settings are defaulted e.g dataType to json, type to get etc
N.B .load, .get and .post are also simple wrappers around the .ajax method.
Did you try showing your window using the ShowDialog method?
Don't forget to set the Owner property on the dialog window to the main window. This will avoid weird behavior when Alt+Tabbing, etc.
Use the :not
pseudo-class to exclude the classes you don't want the hover to apply to:
<div class="test"> blah </div>
<div class="test"> blah </div>
<div class="test nohover"> blah </div>
.test:not(.nohover):hover {
border: 1px solid red;
}
This does what you want in one css rule!
You can use your own custom fonts by setting the font path using pygame.font.Font
pygame.font.Font(filename, size): return Font
example:
pygame.font.init()
font_path = "./fonts/newfont.ttf"
font_size = 32
fontObj = pygame.font.Font(font_path, font_size)
Then render the font using fontObj.render and blit to a surface as in veiset's answer above. :)
When you add TestNG to your Maven dependencies , Change scope from test to compile.Hope this would solve your issue..
Explicit cursors are rarely needed in plpgsql. Use the simpler and faster implicit cursor of a FOR
loop:
Note: Since table names are not unique per database, you have to schema-qualify table names to be sure. Also, I limit the function to the default schema 'public'. Adapt to your needs, but be sure to exclude the system schemas pg_*
and information_schema
.
Be very careful with these functions. They nuke your database. I added a child safety device. Comment the RAISE NOTICE
line and uncomment EXECUTE
to prime the bomb ...
CREATE OR REPLACE FUNCTION f_truncate_tables(_username text)
RETURNS void AS
$func$
DECLARE
_tbl text;
_sch text;
BEGIN
FOR _sch, _tbl IN
SELECT schemaname, tablename
FROM pg_tables
WHERE tableowner = _username
AND
-- dangerous, test before you execute!
RAISE NOTICE '%', -- once confident, comment this line ...
-- EXECUTE -- ... and uncomment this one
format('TRUNCATE TABLE %I.%I CASCADE', _sch, _tbl);
END LOOP;
END
$func$ LANGUAGE plpgsql;
format()
requires Postgres 9.1 or later. In older versions concatenate the query string like this:
'TRUNCATE TABLE ' || quote_ident(_sch) || '.' || quote_ident(_tbl) || ' CASCADE';
Since we can TRUNCATE
multiple tables at once we don't need any cursor or loop at all:
Aggregate all table names and execute a single statement. Simpler, faster:
CREATE OR REPLACE FUNCTION f_truncate_tables(_username text)
RETURNS void AS
$func$
BEGIN
-- dangerous, test before you execute!
RAISE NOTICE '%', -- once confident, comment this line ...
-- EXECUTE -- ... and uncomment this one
(SELECT 'TRUNCATE TABLE '
|| string_agg(format('%I.%I', schemaname, tablename), ', ')
|| ' CASCADE'
FROM pg_tables
WHERE tableowner = _username
AND schemaname = 'public'
);
END
$func$ LANGUAGE plpgsql;
Call:
SELECT truncate_tables('postgres');
You don't even need a function. In Postgres 9.0+ you can execute dynamic commands in a DO
statement. And in Postgres 9.5+ the syntax can be even simpler:
DO
$func$
BEGIN
-- dangerous, test before you execute!
RAISE NOTICE '%', -- once confident, comment this line ...
-- EXECUTE -- ... and uncomment this one
(SELECT 'TRUNCATE TABLE ' || string_agg(oid::regclass::text, ', ') || ' CASCADE'
FROM pg_class
WHERE relkind = 'r' -- only tables
AND relnamespace = 'public'::regnamespace
);
END
$func$;
About the difference between pg_class
, pg_tables
and information_schema.tables
:
About regclass
and quoted table names:
Create a "template" database (let's name it my_template
) with your vanilla structure and all empty tables. Then go through a DROP
/ CREATE DATABASE
cycle:
DROP DATABASE mydb;
CREATE DATABASE mydb TEMPLATE my_template;
This is extremely fast, because Postgres copies the whole structure on the file level. No concurrency issues or other overhead slowing you down.
If concurrent connections keep you from dropping the DB, consider:
Will open your pdf in a new tab with pdf viewer and can download too
<a className=""
href="/project_path_to_your_pdf_asset/failename.pdf"
target="_blank"
>
View PDF
</a>
Disclamer: This is just a wild guess
I know everybody loves an easy-to-read list:
toBe(<value>)
- The returned value is the same as <value>
toBeTrue()
- Checks if the returned value is true
toBeTruthy()
- Check if the value, when cast to a boolean, will be a truthy value
Truthy values are all values that aren't 0
, ''
(empty string), false
, null
, NaN
, undefined
or []
(empty array)*.
* Notice that when you run !![]
, it returns true
, but when you run [] == false
it also returns true
. It depends on how it is implemented. In other words: (!![]) === ([] == false)
On your example, toBe(true)
and toBeTrue()
will yield the same results.
git stash show -p | git apply --reverse
Warning, that would not in every case: "git apply -R
"(man) did not handle patches that touch the same path twice correctly, which has been corrected with Git 2.30 (Q1 2021).
This is most relevant in a patch that changes a path from a regular file to a symbolic link (and vice versa).
See commit b0f266d (20 Oct 2020) by Jonathan Tan (jhowtan
).
(Merged by Junio C Hamano -- gitster
-- in commit c23cd78, 02 Nov 2020)
apply
: when-R
, also reverse list of sectionsHelped-by: Junio C Hamano
Signed-off-by: Jonathan Tan
A patch changing a symlink into a file is written with 2 sections (in the code, represented as "struct patch"): firstly, the deletion of the symlink, and secondly, the creation of the file.
When applying that patch with
-R
, the sections are reversed, so we get: (1) creation of a symlink, then (2) deletion of a file.This causes an issue when the "deletion of a file" section is checked, because Git observes that the so-called file is not a file but a symlink, resulting in a "wrong type" error message.
What we want is: (1) deletion of a file, then (2) creation of a symlink.
In the code, this is reflected in the behavior of
previous_patch()
when invoked fromcheck_preimage()
when the deletion is checked.
Creation then deletion means that when the deletion is checked,previous_patch()
returns the creation section, triggering a mode conflict resulting in the "wrong type" error message.But deletion then creation means that when the deletion is checked,
previous_patch()
returnsNULL
, so the deletion mode is checked against lstat, which is what we want.There are also other ways a patch can contain 2 sections referencing the same file, for example, in 7a07841c0b ("
git-apply
: handle a patch that touches the same path more than once better", 2008-06-27, Git v1.6.0-rc0 -- merge). "git apply -R
"(man) fails in the same way, and this commit makes this case succeed.Therefore, when building the list of sections, build them in reverse order (by adding to the front of the list instead of the back) when
-R
is passed.
You can use the convert
statement in Microsoft SQL Server to convert a date to a string. An example of the syntax used would be:
SELECT convert(varchar(20), getdate(), 120)
The above would return the current date and time in a string with the format of YYYY-MM-DD HH:MM:SS
in 24 hour clock.
You can change the number at the end of the statement to one of many which will change the returned strings format. A list of these codes can be found on the MSDN in the CAST and CONVERT reference section.
To expand on the @PostConstruct
suggestion in other answers, this really is the best solution, in my opinion.
@PostConstruct
is in javax.*
)Get the Sothink SWF decompiler. Not free, but worth it. Recently used it to decompile an SWF that I had lost the fla for, and I could completely round-trip swf-fla and back!
link text
The ng-if
directive, like other directives creates a child scope. See the script below (or this jsfiddle)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>_x000D_
_x000D_
<script>_x000D_
function main($scope) {_x000D_
$scope.testa = false;_x000D_
$scope.testb = false;_x000D_
$scope.testc = false;_x000D_
$scope.obj = {test: false};_x000D_
}_x000D_
</script>_x000D_
_x000D_
<div ng-app >_x000D_
<div ng-controller="main">_x000D_
_x000D_
Test A: {{testa}}<br />_x000D_
Test B: {{testb}}<br />_x000D_
Test C: {{testc}}<br />_x000D_
{{obj.test}}_x000D_
_x000D_
<div>_x000D_
testa (without ng-if): <input type="checkbox" ng-model="testa" />_x000D_
</div>_x000D_
<div ng-if="!testa">_x000D_
testb (with ng-if): <input type="checkbox" ng-model="testb" /> {{testb}}_x000D_
</div>_x000D_
<div ng-if="!someothervar">_x000D_
testc (with ng-if): <input type="checkbox" ng-model="testc" />_x000D_
</div>_x000D_
<div ng-if="!someothervar">_x000D_
object (with ng-if): <input type="checkbox" ng-model="obj.test" />_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>
_x000D_
So, your checkbox changes the testb
inside of the child scope, but not the outer parent scope.
Note, that if you want to modify the data in the parent scope, you'll need to modify the internal properties of an object like in the last div that I added.
to detect when the iframe has loaded and its document is ready?
It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set ‘var isready= true;’ in its own scope, and have the parent script sniff for ‘contentWindow.isready’ (and add the onload handler if not).
If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:
<img id="x" ... />
<script type="text/javascript">
document.getElementById('x').onload= function() {
...
};
</script>
there is no guarantee that the item won't already have loaded by the time the script executes.
The ways out of load-races are:
on IE, you can use the ‘readyState’ property to see if something's already loaded;
if having the item available only with JavaScript enabled is acceptable, you can create it dynamically, setting the ‘onload’ event function before setting source and appending to the page. In this case it cannot be loaded before the callback is set;
the old-school way of including it in the markup:
<img onload="callback(this)" ... />
Inline ‘onsomething’ handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.
awk 'NR>1{print buf}{buf = $0}'
Essentially, this code says the following:
For each line after the first, print the buffered line
for each line, reset the buffer
The buffer is lagged by one line, hence you end up printing lines 1 to n-1
You need to turn this into a string. You can do this using the stringify method in the JSON2 library.
The code would look something like:
var myJSONText = JSON.stringify(myObject);
So
['Location Zero', 'Location One', 'Location Two'];
Will become:
"['Location Zero', 'Location One', 'Location Two']"
You'll have to refer to a PHP guru on how to handle this on the server. I think other answers here intimate a solution.
Data can be returned from the server in a similar way. I.e. you can turn it back into an object.
var myObject = JSON.parse(myJSONString);
doAnswer
and thenReturn
do the same thing if:
Let's mock this BookService
public interface BookService {
String getAuthor();
void queryBookTitle(BookServiceCallback callback);
}
You can stub getAuthor() using doAnswer
and thenReturn
.
BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return "Joshua";
}
}).when(service).getAuthor();
Note that when using doAnswer
, you can't pass a method on when
.
// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());
So, when would you use doAnswer
instead of thenReturn
? I can think of two use cases:
Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.
BookServiceCallback callback = new BookServiceCallback() {
@Override
public void onSuccess(String bookTitle) {
assertEquals("Effective Java", bookTitle);
}
};
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
callback.onSuccess("Effective Java");
// return null because queryBookTitle is void
return null;
}
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:
List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));
Using doAnswer we can stub it safely.
List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));
Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn
.
List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));
You can try
WebElement navigationPageButton = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("navigationPageButton")));
navigationPageButton.click();
Starting file:
line 1
line 2
line 3
line 4
Code:
with open("filename.txt", "r") as f:
lines = f.readlines()
for line in lines:
stripped = line.strip()
print(stripped)
Output:
line 1
line 2
line 3
line 4
You may use this class to test two accessing threads and one mutating the shared instance of ConcurrentHashMap
:
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentMapIteration
{
private final Map<String, String> map = new ConcurrentHashMap<String, String>();
private final static int MAP_SIZE = 100000;
public static void main(String[] args)
{
new ConcurrentMapIteration().run();
}
public ConcurrentMapIteration()
{
for (int i = 0; i < MAP_SIZE; i++)
{
map.put("key" + i, UUID.randomUUID().toString());
}
}
private final ExecutorService executor = Executors.newCachedThreadPool();
private final class Accessor implements Runnable
{
private final Map<String, String> map;
public Accessor(Map<String, String> map)
{
this.map = map;
}
@Override
public void run()
{
for (Map.Entry<String, String> entry : this.map.entrySet())
{
System.out.println(
Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']'
);
}
}
}
private final class Mutator implements Runnable
{
private final Map<String, String> map;
private final Random random = new Random();
public Mutator(Map<String, String> map)
{
this.map = map;
}
@Override
public void run()
{
for (int i = 0; i < 100; i++)
{
this.map.remove("key" + random.nextInt(MAP_SIZE));
this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
private void run()
{
Accessor a1 = new Accessor(this.map);
Accessor a2 = new Accessor(this.map);
Mutator m = new Mutator(this.map);
executor.execute(a1);
executor.execute(m);
executor.execute(a2);
}
}
No exception will be thrown.
Sharing the same iterator between accessor threads can lead to deadlock:
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentMapIteration
{
private final Map<String, String> map = new ConcurrentHashMap<String, String>();
private final Iterator<Map.Entry<String, String>> iterator;
private final static int MAP_SIZE = 100000;
public static void main(String[] args)
{
new ConcurrentMapIteration().run();
}
public ConcurrentMapIteration()
{
for (int i = 0; i < MAP_SIZE; i++)
{
map.put("key" + i, UUID.randomUUID().toString());
}
this.iterator = this.map.entrySet().iterator();
}
private final ExecutorService executor = Executors.newCachedThreadPool();
private final class Accessor implements Runnable
{
private final Iterator<Map.Entry<String, String>> iterator;
public Accessor(Iterator<Map.Entry<String, String>> iterator)
{
this.iterator = iterator;
}
@Override
public void run()
{
while(iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
try
{
String st = Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']';
} catch (Exception e)
{
e.printStackTrace();
}
}
}
}
private final class Mutator implements Runnable
{
private final Map<String, String> map;
private final Random random = new Random();
public Mutator(Map<String, String> map)
{
this.map = map;
}
@Override
public void run()
{
for (int i = 0; i < 100; i++)
{
this.map.remove("key" + random.nextInt(MAP_SIZE));
this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
}
}
}
private void run()
{
Accessor a1 = new Accessor(this.iterator);
Accessor a2 = new Accessor(this.iterator);
Mutator m = new Mutator(this.map);
executor.execute(a1);
executor.execute(m);
executor.execute(a2);
}
}
As soon as you start sharing the same Iterator<Map.Entry<String, String>>
among accessor and mutator threads java.lang.IllegalStateException
s will start popping up.
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentMapIteration
{
private final Map<String, String> map = new ConcurrentHashMap<String, String>();
private final Iterator<Map.Entry<String, String>> iterator;
private final static int MAP_SIZE = 100000;
public static void main(String[] args)
{
new ConcurrentMapIteration().run();
}
public ConcurrentMapIteration()
{
for (int i = 0; i < MAP_SIZE; i++)
{
map.put("key" + i, UUID.randomUUID().toString());
}
this.iterator = this.map.entrySet().iterator();
}
private final ExecutorService executor = Executors.newCachedThreadPool();
private final class Accessor implements Runnable
{
private final Iterator<Map.Entry<String, String>> iterator;
public Accessor(Iterator<Map.Entry<String, String>> iterator)
{
this.iterator = iterator;
}
@Override
public void run()
{
while (iterator.hasNext())
{
Map.Entry<String, String> entry = iterator.next();
try
{
String st =
Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']';
} catch (Exception e)
{
e.printStackTrace();
}
}
}
}
private final class Mutator implements Runnable
{
private final Random random = new Random();
private final Iterator<Map.Entry<String, String>> iterator;
private final Map<String, String> map;
public Mutator(Map<String, String> map, Iterator<Map.Entry<String, String>> iterator)
{
this.map = map;
this.iterator = iterator;
}
@Override
public void run()
{
while (iterator.hasNext())
{
try
{
iterator.remove();
this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
} catch (Exception ex)
{
ex.printStackTrace();
}
}
}
}
private void run()
{
Accessor a1 = new Accessor(this.iterator);
Accessor a2 = new Accessor(this.iterator);
Mutator m = new Mutator(map, this.iterator);
executor.execute(a1);
executor.execute(m);
executor.execute(a2);
}
}
A good example of using the Generic Repository pattern and implementing a generic solution for this might look something like this.
public IList<TEntity> Get<TParamater>(IList<Expression<Func<TEntity, TParamater>>> includeProperties)
{
foreach (var include in includeProperties)
{
query = query.Include(include);
}
return query.ToList();
}
check this if it works it works fine for me
<script>
var windowObjectReference;
var strWindowFeatures = "menubar=no,location=no,resizable=no,scrollbars=no,status=yes,width=400,height=350";
function openRequestedPopup() {
windowObjectReference = window.open("http://www.flyingedge.in/", "CNN_WindowName", strWindowFeatures);
}
</script>
So wait, this is just a list-within-a-list?
The easiest way is probably just to use nested for loops:
>>> a = [[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> a
[[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> for list in a:
... for number in list:
... print number
...
1
3
4
2
4
4
3
4
5
Or is it something more complicated than that? Arbitrary nesting or something? Let us know if there's something else as well.
Also, for performance reasons, you might want to look at using list comprehensions to do this:
http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions
In your example, the TMP
variable is set (and the temporary directory created) whenever the rules for out.tar
are evaluated. In order to create the directory only when out.tar
is actually fired, you need to move the directory creation down into the steps:
out.tar :
$(eval TMP := $(shell mktemp -d))
@echo hi $(TMP)/hi.txt
tar -C $(TMP) cf $@ .
rm -rf $(TMP)
The eval function evaluates a string as if it had been typed into the makefile manually. In this case, it sets the TMP
variable to the result of the shell
function call.
edit (in response to comments):
To create a unique variable, you could do the following:
out.tar :
$(eval $@_TMP := $(shell mktemp -d))
@echo hi $($@_TMP)/hi.txt
tar -C $($@_TMP) cf $@ .
rm -rf $($@_TMP)
This would prepend the name of the target (out.tar, in this case) to the variable, producing a variable with the name out.tar_TMP
. Hopefully, that is enough to prevent conflicts.
The modular crypt format for bcrypt consists of
$2$
, $2a$
or $2y$
identifying the hashing algorithm and format$
.
, /
, 0
–9
, A
–Z
, a
–z
that is different to the standard Base 64 Encoding alphabet) consisting of:
Thus the total length is 59 or 60 bytes respectively.
As you use the 2a format, you’ll need 60 bytes. And thus for MySQL I’ll recommend to use the CHAR(60) BINARY
or BINARY(60)
(see The _bin and binary Collations for information about the difference).
CHAR
is not binary safe and equality does not depend solely on the byte value but on the actual collation; in the worst case A
is treated as equal to a
. See The _bin
and binary
Collations for more information.
Consider that you work with RDBMS and have to select what to use - full table scans, or index access - but only one of them.
If you select full table scan - use hive. If index access - HBase.
Beautiful! Your solution was 99%... instead of "this.scrollY", I used "$(window).scrollTop()". What's even better is that this solution only requires the jQuery1.2.6 library (no additional libraries needed).
The reason I wanted that version in particular is because that's what ships with MVC currently.
Here's the code:
$(document).ready(function() {
$("#topBar").css("position", "absolute");
});
$(window).scroll(function() {
$("#topBar").css("top", $(window).scrollTop() + "px");
});
Step:-1 Open the folder “application/config” and open the file “config.php“. find and replace the below code in config.php file.
//find the below code
$config['index_page'] = "index.php"
//replace with the below code
$config['index_page'] = ""
Step:-2 Go to your CodeIgniter folder and create .htaccess
Path:
Your_website_folder/
application/
assets/
system/
.htaccess <——— this file
index.php
Step:-3 Write below code in .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Step:-4 In some case the default setting for uri_protocol does not work properly. To solve this problem just open the file “application/config/config.php“, then find and replace the below code
//Not needed for CodeIgniter 3 its already there.
//find the below code
$config['uri_protocol'] = "AUTO"
//replace with the below code
$config['uri_protocol'] = "REQUEST_URI"
Thats all but in wamp server it does not work because rewrite_module by default disabled so we have need to enable it. for this do the following
Not quite, although generally you can usually use some workaround on one of the forms
[^abc]
, which is character by character not a
or b
or c
, a(?!b)
, which is a
not followed by b
(?<!a)b
, which is b
not preceeded by a
Docker for Mac users, here is the solution:
Find log file path by:
$ docker inspect | grep log
SSH into the docker machine( suppose the name is default
, if not, run docker-machine ls
to find out):
$ docker-machine ssh default
Change to root user(reference):
$ sudo -i
Delete the log file content:
$ echo "" > log_file_path_from_step1
Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.
Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:
/link/mybackend/?field1=value1&field2=value2&field3=value3
and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET
.
So your urlconf would be:
url(r'^link/(?P<backend>\w+?)/$', my_function)
and the view would look like:
def my_function(request, backend):
data = request.GET
and the reverse would be (after importing urllib
):
return "%s?%s" % (redirect('my_function', args=(backend,)),
urllib.urlencode(form.cleaned_data))
Edited after comment
The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.
If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.
That said, if all you want to do is store the data, then just put it in the session:
request.session['temp_data'] = form.cleaned_data
You can invoke reflections and also, set order of sequence for getter for values through annotations
public class Student {
private String grade;
private String name;
private String id;
private String gender;
private Method[] methods;
@Retention(RetentionPolicy.RUNTIME)
public @interface Order {
int value();
}
/**
* Sort methods as per Order Annotations
*
* @return
*/
private void sortMethods() {
methods = Student.class.getMethods();
Arrays.sort(methods, new Comparator<Method>() {
public int compare(Method o1, Method o2) {
Order or1 = o1.getAnnotation(Order.class);
Order or2 = o2.getAnnotation(Order.class);
if (or1 != null && or2 != null) {
return or1.value() - or2.value();
}
else if (or1 != null && or2 == null) {
return -1;
}
else if (or1 == null && or2 != null) {
return 1;
}
return o1.getName().compareTo(o2.getName());
}
});
}
/**
* Read Elements
*
* @return
*/
public void readElements() {
int pos = 0;
/**
* Sort Methods
*/
if (methods == null) {
sortMethods();
}
for (Method method : methods) {
String name = method.getName();
if (name.startsWith("get") && !name.equalsIgnoreCase("getClass")) {
pos++;
String value = "";
try {
value = (String) method.invoke(this);
}
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(name + " Pos: " + pos + " Value: " + value);
}
}
}
// /////////////////////// Getter and Setter Methods
/**
* @param grade
* @param name
* @param id
* @param gender
*/
public Student(String grade, String name, String id, String gender) {
super();
this.grade = grade;
this.name = name;
this.id = id;
this.gender = gender;
}
/**
* @return the grade
*/
@Order(value = 4)
public String getGrade() {
return grade;
}
/**
* @param grade the grade to set
*/
public void setGrade(String grade) {
this.grade = grade;
}
/**
* @return the name
*/
@Order(value = 2)
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the id
*/
@Order(value = 1)
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the gender
*/
@Order(value = 3)
public String getGender() {
return gender;
}
/**
* @param gender the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* Main
*
* @param args
* @throws IOException
* @throws SQLException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void main(String args[]) throws IOException, SQLException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Student student = new Student("A", "Anand", "001", "Male");
student.readElements();
}
}
Output when sorted
getId Pos: 1 Value: 001
getName Pos: 2 Value: Anand
getGender Pos: 3 Value: Male
getGrade Pos: 4 Value: A
After 8 years the situation is changed a bit.
I'm unable to open a new session of Google Chrome without other parameters and allow 'file:' schema.
On macOS I do:
open -n -a "Google Chrome" --args \
--disable-web-security \ # This disable all CORS and other security checks
--user-data-dir=$HOME/fakeChromeDir # This let you to force open a new Google Chrome session
Without this arguments I'm unable to test the XSL stylesheet in local.
\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
or
\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
I recommend php-ffmpeg library.
Extracting image
You can extract a frame at any timecode using the
FFMpeg\Media\Video::frame
method.This code returns a
FFMpeg\Media\Frame
instance corresponding to the second 42. You can pass anyFFMpeg\Coordinate\TimeCode
as argument, see dedicated documentation below for more information.
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');
If you want to extract multiple images from the video, you can use the following filter:
$video
->filters()
->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
By default, this will save the frames as jpg images.
You are able to override this using setFrameFileType
to save the frames in another format:
$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);
$video->addFilter($filter);
Environment.getExternalStorageDirectory().getAbsolutePath()
Gives you the full path the SDCard. You can then do normal File I/O operations using standard Java.
Here's a simple example for writing a file:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
// Not sure if the / is on the path or not
File f = new File(baseDir + File.separator + fileName);
f.write(...);
f.flush();
f.close();
Edit:
Oops - you wanted an example for reading ...
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
// Not sure if the / is on the path or not
File f = new File(baseDir + File.Separator + fileName);
FileInputStream fiStream = new FileInputStream(f);
byte[] bytes;
// You might not get the whole file, lookup File I/O examples for Java
fiStream.read(bytes);
fiStream.close();
Objective-C code for copy Table from a Database to another Database
-(void) createCopyDatabase{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *maindbPath = [documentsDir stringByAppendingPathComponent:@"User.sqlite"];;
NSString *newdbPath = [documentsDir stringByAppendingPathComponent:@"User_copy.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
char *error;
if ([fileManager fileExistsAtPath:newdbPath]) {
[fileManager removeItemAtPath:newdbPath error:nil];
}
sqlite3 *database;
//open database
if (sqlite3_open([newdbPath UTF8String], &database)!=SQLITE_OK) {
NSLog(@"Error to open database");
}
NSString *attachQuery = [NSString stringWithFormat:@"ATTACH DATABASE \"%@\" AS aDB",maindbPath];
sqlite3_exec(database, [attachQuery UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to Attach = %s",error);
}
//Query for copy Table
NSString *sqlString = @"CREATE TABLE Info AS SELECT * FROM aDB.Info";
sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to copy database = %s",error);
}
//Query for copy Table with Where Clause
sqlString = @"CREATE TABLE comments AS SELECT * FROM aDB.comments Where user_name = 'XYZ'";
sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to copy database = %s",error);
}
}
Select the labels above the bar. Format Data Labels. Instead of selecting "VALUE" (unclick). SELECT Value from cells. Select the value. Use the following statement: if(cellvalue="","",cellvalue) where cellvalue is what ever the calculation is in the cell.
These are equivalent.
#pragma omp parallel
spawns a group of threads, while #pragma omp for
divides loop iterations between the spawned threads. You can do both things at once with the fused #pragma omp parallel for
directive.
find
supports -delete
operation, so:
find /base/dir/* -ctime +10 -delete;
I think there's a catch that the files need to be 10+ days older too. Haven't tried, someone may confirm in comments.
The most voted solution here is missing -maxdepth 0
so it will call rm -rf
for every subdirectory, after deleting it. That doesn't make sense, so I suggest:
find /base/dir/* -maxdepth 0 -type d -ctime +10 -exec rm -rf {} \;
The -delete
solution above doesn't use -maxdepth 0
because find
would complain the dir is not empty. Instead, it implies -depth
and deletes from the bottom up.
This problem looked familiar so I thought I'd see if I could replicate from the limited amount of information.
A quick search turned up an entry in James Bennett's blog here which mentions that when working with the UserProfile to extend the User model a common mistake in settings.py can cause Django to throw this error.
To quote the blog entry:
The value of the setting is not "appname.models.modelname", it's just "appname.modelname". The reason is that Django is not using this to do a direct import; instead, it's using an internal model-loading function which only wants the name of the app and the name of the model. Trying to do things like "appname.models.modelname" or "projectname.appname.models.modelname" in the AUTH_PROFILE_MODULE setting will cause Django to blow up with the dreaded "too many values to unpack" error, so make sure you've put "appname.modelname", and nothing else, in the value of AUTH_PROFILE_MODULE.
If the OP had copied more of the traceback I would expect to see something like the one below which I was able to duplicate by adding "models" to my AUTH_PROFILE_MODULE setting.
TemplateSyntaxError at /
Caught an exception while rendering: too many values to unpack
Original Traceback (most recent call last):
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 71, in render_node
result = node.render(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 87, in render
output = force_unicode(self.filter_expression.resolve(context))
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 535, in resolve
obj = self.var.resolve(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 676, in resolve
value = self._resolve_lookup(context)
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 711, in _resolve_lookup
current = current()
File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/contrib/auth/models.py", line 291, in get_profile
app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
ValueError: too many values to unpack
This I think is one of the few cases where Django still has a bit of import magic that tends to cause confusion when a small error doesn't throw the expected exception.
You can see at the end of the traceback that I posted how using anything other than the form "appname.modelname" for the AUTH_PROFILE_MODULE would cause the line "app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')" to throw the "too many values to unpack" error.
I'm 99% sure that this was the original problem encountered here.
While the w32tm /resync
in theory does the job, it only does so under certain conditions. When "down to the millisecond" matters, however, I found that Windows wouldn't actually make the adjustment; as if "oh, I'm off by 2.5 seconds, close enough bro, nothing to see or do here".
In order to truly force the resync (Windows 7):
w32tm /resync
watch -n 0.1 date
on a Linux machine on the network that I had SSH'd over into)--- Rapid Method ---
net start w32time
(Time Service must be running)time 8
(where 8 may be replaced by any 'hour' value, presumably 0-23)w32tm /resync
Swift 3, xcode version 8.3.2, storyboard->choose your table View->inspector->Separator.
Have you tried
document.getElementById('body').style.display = "none";
instead of
document.getElementById('body').style.display = "hidden";
?
Declare it as a decimal
which uses the int
variable and divide this by 100
int number = 700
decimal correctNumber = (decimal)number / 100;
Edit: Bala was faster with his reaction
This simple oneliner works for me
String result = new BigInteger(1, inputBytes).toString(16);
EDIT - Using this will remove the leading zeros, but hey worked for my use-case. Thanks @Voicu for pointing it out
from http://www.vmware.com/products/player/faqs.html:
How does VMware Player compare to VMware Workstation? VMware Player enables you to quickly and easily create and run virtual machines. However, VMware Player lacks many powerful features, remote connections to vSphere, drag and drop upload to vSphere, multiple Snapshots and Clones, and much more.
Not being able to revert snapshots it's a big no for me.
It's possible, but you have to add some JVM flags when you start your application.
You have to add remote debug configuration: Edit configuration -> Remote.
Then you'lll find in displayed dialog window parametrs that you have to add to program execution, like:
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
Then when your application is launched you can attach your debugger. If you want your application to wait until debugger is connected just change suspend flag to y (suspend=y
)
You can use the .position() for this
var link = $(element);
var position = link.position(); //cache the position
var right = $(window).width() - position.left - link.width();
var bottom = $(window).height() - position.top - link.height();
The syntax for using an alias in an update statement on SQL Server is as follows:
UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;
The alias should not be necessary here though.
I got this error: "Source option 5 is no longer supported. Use 6 or later" after I changed the pom.xml
<java.version>7</java.version>
to
<java.version>11</java.version>
Later to realise the property was used with a dash insteal of a dot:
<source>${java-version}</source>
<target>${java-version}</target>
(swearings), I replaced the dot with a dash and the error went away:
<java-version>11</javaversion>
It looks like you're writing PHP, in which case you want:
<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>
Notice that the ('us'=>'United', 'ca'=>'canada')
needs to be a parameter to the array function in PHP.
Most programming languages that support associative arrays or dictionaries use arr['key']
to retrieve the item specified by 'key'
For instance:
ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
=> {"us"=>"USA", "ca"=>"Canada"}
ruby-1.9.1-p378 > h['ca']
=> "Canada"
>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'
#
class P
{
static void Main()
{
var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
System.Console.WriteLine(d["ca"]);
}
}
t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables
Whitespace just means characters which are used for spacing, and have an "empty" representation. In the context of python, it means tabs and spaces (it probably also includes exotic unicode spaces, but don't use them). The definitive reference is here: http://docs.python.org/2/reference/lexical_analysis.html#indentation
I'm not sure exactly how to use it.
Put it at the front of the line you want to indent. If you mix spaces and tabs, you'll likely see funky results, so stick with one or the other. (The python community usually follows PEP8 style, which prescribes indentation of four spaces).
You need to create a new indent level after each colon:
for x in range(0, 50):
print x
print 2*x
print x
In this code, the first two print
statements are "inside" the body of the for
statement because they are indented more than the line containing the for
. The third print
is outside because it is indented less than the previous (nonblank) line.
If you don't indent/unindent consistently, you will get indentation errors. In addition, all compound statements (i.e. those with a colon) can have the body supplied on the same line, so no indentation is required, but the body must be composed of a single statement.
Finally, certain statements, like lambda
feature a colon, but cannot have a multiline block as the body.
I've been using Nuitka and PyInstaller with my package, PySimpleGUI.
Nuitka There were issues getting tkinter to compile with Nuikta. One of the project contributors developed a script that fixed the problem.
If you're not using tkinter it may "just work" for you. If you are using tkinter say so and I'll try to get the script and instructions published.
PyInstaller I'm running 3.6 and PyInstaller is working great! The command I use to create my exe file is:
pyinstaller -wF myfile.py
The -wF will create a single EXE file. Because all of my programs have a GUI and I do not want to command window to show, the -w option will hide the command window.
This is as close to getting what looks like a Winforms program to run that was written in Python.
[Update 20-Jul-2019]
There is PySimpleGUI GUI based solution that uses PyInstaller. It uses PySimpleGUI. It's called pysimplegui-exemaker and can be pip installed.
pip install PySimpleGUI-exemaker
To run it after installing:
python -m pysimplegui-exemaker.pysimplegui-exemaker
add java security in your run command
java -jar -Djava.security.egd="file:///dev/urandom" yourjarfilename.jar
Consider this code,
int some_int = 100;
while(some_int == 100)
{
//your code
}
When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int
, so it may be tempted to optimize the while
loop by changing it from while(some_int == 100)
to something which is equivalent to while(true)
so that the execution could be fast (since the condition in while
loop appears to be true
always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int
and compare it with 100, in each iteration which obviously is a little bit slow.)
However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int
from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!
So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while
loop. That is where the volatile
keyword plays its role. All you need to do is this,
volatile int some_int = 100; //note the 'volatile' qualifier now!
In other words, I would explain this as follows:
volatile
tells the compiler that,
"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"
Well, that is how volatile
prevents the compiler from optimizing code. Now search the web to see some sample examples.
Quoting from the C++ Standard ($7.1.5.1/8)
[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]
Related topic:
Does making a struct volatile make all its members volatile?
So you're trying to grab numeric values that are preceded by the token "%download%#"?
Try this pattern:
(?<=%download%#)\d+
That should work. I don't think #
or %
are special characters in .NET Regex, but you'll have to either escape the backslash like \\
or use a verbatim string for the whole pattern:
var regex = new Regex(@"(?<=%download%#)\d+");
return regex.Matches(strInput);
Tested here: http://rextester.com/BLYCC16700
NOTE: The lookbehind assertion (?<=...)
is important because you don't want to include %download%#
in your results, only the numbers after it. However, your example appears to require it before each string you want to capture. The lookbehind group will make sure it's there in the input string, but won't include it in the returned results. More on lookaround assertions here.
Is your query returning array or object? If you dump it out, you might find that it's an array and all you need is an array access ([]) instead of an object access (->).
There's always a goto
statement, but I would recommend nesting an if
with an inverse of the breaking condition.
It depends on what you mean by "dropped". For TCP sockets, if the other end closes the connection either through close() or the process terminating, you'll find out by reading an end of file, or getting a read error, usually the errno being set to whatever 'connection reset by peer' is by your operating system. For python, you'll read a zero length string, or a socket.error will be thrown when you try to read or write from the socket.
I got this issue when Eclipse was unable to find the JDBC driver. Had to do a gradle refresh from the eclipse to get this work.
Use a DataTrigger
:
<DataGrid ItemsSource="{Binding YourItemsSource}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="State1">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="State2">
<Setter Property="Background" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
I had a different cause for this error. I tried to insert a date without using quotes and received a strange error telling me I had tried to insert a date from 2003.
Although I was already using the YYYY-MM-DD format, I forgot to add quotes around the date. Even though it is a date and not a string, quotes are still required.
Side-by-side view of how the array and $@ are practically the same.
Code:
#!/bin/bash
echo "Dollar-1 : $1"
echo "Dollar-2 : $2"
echo "Dollar-3 : $3"
echo "Dollar-AT: $@"
echo ""
myArray=( "$@" )
echo "A Val 0: ${myArray[0]}"
echo "A Val 1: ${myArray[1]}"
echo "A Val 2: ${myArray[2]}"
echo "A All Values: ${myArray[@]}"
Input:
./bash-array-practice.sh 1 2 3 4
Output:
Dollar-1 : 1
Dollar-2 : 2
Dollar-3 : 3
Dollar-AT: 1 2 3 4
A Val 0: 1
A Val 1: 2
A Val 2: 3
A All Values: 1 2 3 4
I think you better write something like this:
db.getCollection('Blog').find({"_id":ObjectId("58f6724e97990e9de4f17c23")})
You could use dplyr
:
df %>% group_by("Amount") %>% slice(which.min(x))
For JavaScript arrays, you use Both push() and concat() function.
var array = [1, 2, 3];
array.push(4, 5); //use push for appending a single array.
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = array1.concat(array2); //It is better use concat for appending more then one array.
In C# 5.0, this problem is fixed and you can close over loop variables and get the results you expect.
The language specification says:
8.8.4 The foreach statement
(...)
A foreach statement of the form
foreach (V v in x) embedded-statement
is then expanded to:
{ E e = ((C)(x)).GetEnumerator(); try { while (e.MoveNext()) { V v = (V)(T)e.Current; embedded-statement } } finally { … // Dispose e } }
(...)
The placement of
v
inside the while loop is important for how it is captured by any anonymous function occurring in the embedded-statement. For example:int[] values = { 7, 9, 13 }; Action f = null; foreach (var value in values) { if (f == null) f = () => Console.WriteLine("First value: " + value); } f();
If
v
was declared outside of the while loop, it would be shared among all iterations, and its value after the for loop would be the final value,13
, which is what the invocation off
would print. Instead, because each iteration has its own variablev
, the one captured byf
in the first iteration will continue to hold the value7
, which is what will be printed. (Note: earlier versions of C# declaredv
outside of the while loop.)
Try like this:
$data = array('current_login' => date('Y-m-d H:i:s'));
$this->db->set('last_login', 'current_login', false);
$this->db->where('id', 'some_id');
$this->db->update('login_table', $data);
Pay particular attention to the set()
call's 3rd parameter. false
prevents CodeIgniter from quoting the 2nd parameter -- this allows the value to be treated as a table column and not a string value. For any data that doesn't need to special treatment, you can lump all of those declarations into the $data
array.
The query generated by above code:
UPDATE `login_table`
SET last_login = current_login, `current_login` = '2018-01-18 15:24:13'
WHERE `id` = 'some_id'
DataGrid.DataSource = null;
DataGrid.DataBind();
public static int[] merge(int[] a, int[] b) {
int[] answer = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
answer[k++] = a[i] < b[j] ? a[i++] : b[j++];
while (i < a.length)
answer[k++] = a[i++];
while (j < b.length)
answer[k++] = b[j++];
return answer;
}
Is a little bit more compact but exactly the same!
LoadLibrary
does not do what you think it does. It loads the DLL into the memory of the current process, but it does not magically import functions defined in it! This wouldn't be possible, as function calls are resolved by the linker at compile time while LoadLibrary
is called at runtime (remember that C++ is a statically typed language).
You need a separate WinAPI function to get the address of dynamically loaded functions: GetProcAddress
.
Example
#include <windows.h>
#include <iostream>
/* Define a function pointer for our imported
* function.
* This reads as "introduce the new type f_funci as the type:
* pointer to a function returning an int and
* taking no arguments.
*
* Make sure to use matching calling convention (__cdecl, __stdcall, ...)
* with the exported function. __stdcall is the convention used by the WinAPI
*/
typedef int (__stdcall *f_funci)();
int main()
{
HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\Documents and Settings\\User\\Desktop\\test.dll");
if (!hGetProcIDDLL) {
std::cout << "could not load the dynamic library" << std::endl;
return EXIT_FAILURE;
}
// resolve function address here
f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");
if (!funci) {
std::cout << "could not locate the function" << std::endl;
return EXIT_FAILURE;
}
std::cout << "funci() returned " << funci() << std::endl;
return EXIT_SUCCESS;
}
Also, you should export your function from the DLL correctly. This can be done like this:
int __declspec(dllexport) __stdcall funci() {
// ...
}
As Lundin notes, it's good practice to free the handle to the library if you don't need them it longer. This will cause it to get unloaded if no other process still holds a handle to the same DLL.
If you look into the source of java.lang.Runtime, you'll see exec finally call protected method: execVM, which means it uses Virtual memory. So for Unix-like system, VM depends on amount of swap space + some ratio of physical memory.
Michael's answer did solve your problem but it might (or to say, would eventually) cause the O.S. deadlock in memory allocation issue since 1 tell O.S. less careful of memory allocation & 0 is just guessing & obviously that you are lucky that O.S. guess you can have memory THIS TIME. Next time? Hmm.....
Better approach is that you experiment your case & give a good swap space & give a better ratio of physical memory used & set value to 2 rather than 1 or 0.
Depending on what you want the file to contain:
touch /path/to/file
for an empty filesomecommand > /path/to/file
for a file containing the output of some command.
eg: grep --help > randomtext.txt
echo "This is some text" > randomtext.txt
nano /path/to/file
or vi /path/to/file
(or any other editor emacs,gedit etc
)
It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist
Create the file using cat
$ cat > myfile.txt
Now, just type whatever you want in the file:
Hello World!
CTRL-D to save and exit
There are several possible solutions:
touch file
>file
echo -n > file
printf '' > file
The echo
version will work only if your version of echo
supports the -n
switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.
echo '' > file
printf '\n' > file
This is a valid "text file" because it ends in a newline.
"$EDITOR" file
echo 'text' > file
cat > file <<END \
text
END
printf 'text\n' > file
These are equivalent. The $EDITOR
command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat
version presumes a literal newline after the \
and after each other line. Other than that these will all work in a POSIX shell.
Of course there are many other methods of writing and creating files, too.
Assuming the submodule's repository does contain a commit you want to use (unlike the commit that is referenced from current state of the super-project), there are two ways to do it.
The first requires you to already know the commit from the submodule that you want to use. It works from the “inside, out” by directly adjusting the submodule then updating the super-project. The second works from the “outside, in” by finding the super-project's commit that modified the submodule and then reseting the super-project's index to refer to a different submodule commit.
If you already know which commit you want the submodule to use, cd
to the submodule, check out the commit you want, then git add
and git commit
it back in the super-project.
Example:
$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'
Oops, someone made a super-project commit that refers to an unpublished commit in the submodule sub
. Somehow, we already know that we want the submodule to be at commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
. Go there and check it out directly.
$ cd sub
$ git checkout 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
Note: moving to '5d5a3ee314476701a20f2c6ec4a53f88d651df6c' which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
git checkout -b <new_branch_name>
HEAD is now at 5d5a3ee... quux
$ cd ..
Since we are checking out a commit, this produces a detached HEAD in the submodule. If you want to make sure that the submodule is using a branch, then use git checkout -b newbranch <commit>
to create and checkout a branch at the commit or checkout the branch that you want (e.g. one with the desired commit at the tip).
A checkout in the submodule is reflected in the super-project as a change to the working tree. So we need to stage the change in the super-project's index and verify the results.
$ git add sub
$ git submodule update
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
The submodule update was silent because the submodule is already at the specified commit. The first diff shows that the index and worktree are the same. The third diff shows that the only staged change is moving the sub
submodule to a different commit.
git commit
This commits the fixed-up submodule entry.
If you are not sure which commit you should use from the submodule, you can look at the history in the superproject to guide you. You can also manage the reset directly from the super-project.
$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'
This is the same situation as above. But this time we will focus on fixing it from the super-project instead of dipping into the submodule.
$ git log --oneline -p -- sub
ce5d37c local change in sub
diff --git a/sub b/sub
index 5d5a3ee..e47c0a1 160000
--- a/sub
+++ b/sub
@@ -1 +1 @@
-Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
+Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
bca4663 added sub
diff --git a/sub b/sub
new file mode 160000
index 0000000..5d5a3ee
--- /dev/null
+++ b/sub
@@ -0,0 +1 @@
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
OK, it looks like it went bad in ce5d37c
, so we will restore the submodule from its parent (ce5d37c~
).
Alternatively, you can take the submodule's commit from the patch text (5d5a3ee314476701a20f2c6ec4a53f88d651df6c
) and use the above “inside, out” process instead.
$ git checkout ce5d37c~ -- sub
This reset the submodule entry for sub
to what it was at commit ce5d37c~
in the super-project.
$ git submodule update
Submodule path 'sub': checked out '5d5a3ee314476701a20f2c6ec4a53f88d651df6c'
The submodule update went OK (it indicates a detached HEAD).
$ git diff ce5d37c~ -- sub
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
The first diff shows that sub
is now the same in ce5d37c~
. The second diff shows that the index and worktree are the same. The third diff shows the only staged change is moving the sub
submodule to a different commit.
git commit
This commits the fixed-up submodule entry.
go to Run Configuration and in argument tab you can write your argument
Adding a small attribute as android:spinnerMode="dialog"
would show the spinner contents in a pop-up.
Spring is moving away from XML files and uses annotations heavily. The following example is a simple standalone Spring application which uses annotation instead of XML files.
package com.zetcode.bean;
import org.springframework.stereotype.Component;
@Component
public class Message {
private String message = "Hello there!";
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
return message;
}
}
This is a simple bean. It is decorated with the @Component
annotation for auto-detection by Spring container.
package com.zetcode.main;
import com.zetcode.bean.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = "com.zetcode")
public class Application {
public static void main(String[] args) {
ApplicationContext context
= new AnnotationConfigApplicationContext(Application.class);
Application p = context.getBean(Application.class);
p.start();
}
@Autowired
private Message message;
private void start() {
System.out.println("Message: " + message.getMessage());
}
}
This is the main Application
class. The @ComponentScan
annotation searches for components. The @Autowired
annotation injects the bean into the message
variable. The AnnotationConfigApplicationContext
is used to create the Spring application context.
My Standalone Spring tutorial shows how to create a standalone Spring application with both XML and annotations.
Try this
select *
from jobdetails
where job_no between '0711' and '0713'
the only problem is that job '0713'
is going to be returned as well
so can use '07299999999999'
or just add and job_no <> '0713'
Dan zamir
To reference an element by id, you need to use the #
qualifier.
Try:
alert($("#link1").text());
To replace it, you could use:
$("#link1").text('New text');
The .html()
function would work in this case too.
You should've kept that DOM ready function
$(function() {
$("#projectKey").change(function() {
alert( $('option:selected', this).text() );
});
});
The document isn't ready if you added the javascript before the elements in the DOM, you have to either use a DOM ready function or add the javascript after the elements, the usual place is right before the </body>
tag
To create a read-only user, you have to setup a different user than the one owning the tables you want to access.
If you just create the user and grant SELECT permission to the read-only user, you'll need to prepend the schema name to each table name. To avoid this, you have basically two options:
ALTER SESSION SET CURRENT_SCHEMA=XYZ
CREATE SYNONYM READER_USER.TABLE1 FOR XYZ.TABLE1
So if you haven't been told the name of the owner schema, you basically have three options. The last one should always work:
SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL
SELECT * FROM ALL_SYNONYMS WHERE OWNER = USER
SELECT * FROM ALL_TABLES WHERE OWNER NOT IN ('SYS', 'SYSTEM', 'CTXSYS', 'MDSYS');
This is simple, and works with Django 1.4:
class ClientAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ClientAdminForm, self).__init__(*args, **kwargs)
# access object through self.instance...
self.fields['base_rate'].queryset = Rate.objects.filter(company=self.instance.company)
class ClientAdmin(admin.ModelAdmin):
form = ClientAdminForm
....
You don't need to specify this in a form class, but can do it directly in the ModelAdmin, as Django already includes this built-in method on the ModelAdmin (from the docs):
ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)¶
'''The formfield_for_foreignkey method on a ModelAdmin allows you to
override the default formfield for a foreign keys field. For example,
to return a subset of objects for this foreign key field based on the
user:'''
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "car":
kwargs["queryset"] = Car.objects.filter(owner=request.user)
return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
An even niftier way to do this (for example in creating a front-end admin interface that users can access) is to subclass the ModelAdmin and then alter the methods below. The net result is a user interface that ONLY shows them content that is related to them, while allowing you (a super-user) to see everything.
I've overridden four methods, the first two make it impossible for a user to delete anything, and it also removes the delete buttons from the admin site.
The third override filters any query that contains a reference to (in the example 'user' or 'porcupine' (just as an illustration).
The last override filters any foreignkey field in the model to filter the choices available the same as the basic queryset.
In this way, you can present an easy to manage front-facing admin site that allows users to mess with their own objects, and you don't have to remember to type in the specific ModelAdmin filters we talked about above.
class FrontEndAdmin(models.ModelAdmin):
def __init__(self, model, admin_site):
self.model = model
self.opts = model._meta
self.admin_site = admin_site
super(FrontEndAdmin, self).__init__(model, admin_site)
remove 'delete' buttons:
def get_actions(self, request):
actions = super(FrontEndAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
prevents delete permission
def has_delete_permission(self, request, obj=None):
return False
filters objects that can be viewed on the admin site:
def get_queryset(self, request):
if request.user.is_superuser:
try:
qs = self.model.objects.all()
except AttributeError:
qs = self.model._default_manager.get_queryset()
return qs
else:
try:
qs = self.model.objects.all()
except AttributeError:
qs = self.model._default_manager.get_queryset()
if hasattr(self.model, ‘user’):
return qs.filter(user=request.user)
if hasattr(self.model, ‘porcupine’):
return qs.filter(porcupine=request.user.porcupine)
else:
return qs
filters choices for all foreignkey fields on the admin site:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if request.employee.is_superuser:
return super(FrontEndAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
else:
if hasattr(db_field.rel.to, 'user'):
kwargs["queryset"] = db_field.rel.to.objects.filter(user=request.user)
if hasattr(db_field.rel.to, 'porcupine'):
kwargs["queryset"] = db_field.rel.to.objects.filter(porcupine=request.user.porcupine)
return super(ModelAdminFront, self).formfield_for_foreignkey(db_field, request, **kwargs)
code for a simple copy.
cp -r ./SourceFolder ./DestFolder
code for a copy with success result
cp -rv ./SourceFolder ./DestFolder
code for Forcefully if source contains any readonly file it will also copy
cp -rf ./SourceFolder ./DestFolder
for details help
cp --help
In 32 bit format system the hexadecimal value 0xff
represents 00000000000000000000000011111111
that is 255(15*16^1+15*16^0)
in decimal. and the bitwise & operator masks the same 8 right most bits as in first operand.
Struggled to find this as well.
Heres a screenshot of how to do it:
What happens when the string contains a duplicate character?
from my experience with index()
I saw that for duplicate you get back the same index.
For example:
s = 'abccde'
for c in s:
print('%s, %d' % (c, s.index(c)))
would return:
a, 0
b, 1
c, 2
c, 2
d, 4
In that case you can do something like that:
for i, character in enumerate(my_string):
# i is the position of the character in the string
I encountered this issue it turned out to be.
Project B references Project A.
Project A compiled as A.dll (assembly name = A).
Project B compiled as A.dll (assembly name A).
Visual Studio 2010 wasn't catching this. Resharper was okay, but wouldn't compile. WinForms designer gave misleading error message saying likely resulting from incompatbile platform targets.
The solution, after a painful day, was to make sure assemblies don't have same name.
This topic (e.g. step="0.01"
) relates to stepMismatch and is supported by all browsers as follows:
Less code is better than more!
If the users say "that's it?", and your work remains invisible, it's done right. Glory can be found elsewhere.
Another possibe option for SQL Server 2017+, without loops and/or recursion, is a string-based approach using TRANSLATE()
and REPLACE()
.
T-SQL statement:
DECLARE @pattern varchar(52) = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
SELECT
v.[Text],
REPLACE(
TRANSLATE(
v.[Text],
REPLACE(TRANSLATE(v.[Text], @pattern, REPLICATE('a', LEN(@pattern))), 'a', ''),
REPLICATE('0', LEN(REPLACE(TRANSLATE(v.[Text], @pattern, REPLICATE('a', LEN(@pattern))), 'a', '')))
),
'0',
''
) AS AlphabeticCharacters
FROM (VALUES
('abc1234def5678ghi90jkl#@$&'),
('1234567890'),
('JAHDBESBN%*#*@*($E*sd55bn')
) v ([Text])
or as a function:
CREATE FUNCTION dbo.RemoveNonAlphabeticCharacters (@Text varchar(1000))
RETURNS varchar(1000)
AS BEGIN
DECLARE @pattern varchar(52) = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
SET @text = REPLACE(
TRANSLATE(
@Text,
REPLACE(TRANSLATE(@Text, @pattern, REPLICATE('a', LEN(@pattern))), 'a', ''),
REPLICATE('0', LEN(REPLACE(TRANSLATE(@Text, @pattern, REPLICATE('a', LEN(@pattern))), 'a', '')))
),
'0',
''
)
RETURN @Text
END
For Web API 2 my methods consistently return IHttpActionResult so I use...
public IHttpActionResult Save(MyEntity entity)
{
....
return ResponseMessage(
Request.CreateResponse(
HttpStatusCode.BadRequest,
validationErrors));
}
Single quotes work fine too, even without escaping the double quotes, at least in Excel 2016:
'text with spaces, and a comma','more text with spaces','spaces and "quoted text" and more spaces','nospaces','NOSPACES1234'
Excel will put that in 5 columns (if you choose the single quote as "Text qualifier" in the "Text to columns" wizard)
rysnc can be useful to run on slow and unreliable connections. So if your download aborts in the middle of a large file rysnc will be able to continue from where it left off when invoked again.
Use rsync -vP username@host:/path/to/file .
The -P option preserves partially downloaded files and also shows progress.
As usual check man rsync
I found the following Regex for URLs, tested successfully with 500+ URLs:
/\b(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?\b/gi
I know it looks ugly, but the good thing is that it works. :)
I did this by using data attributes. Is a lot cleaner than other methods attempting to explode etc.
HTML
<select class="example">
<option value="1" data-value="A">One</option>
<option value="2" data-value="B">Two</option>
<option value="3" data-value="C">Three</option>
<option value="4" data-value="D">Four</option>
</select>
JS
$('select.example').change(function() {
var other_val = $('select.example option[value="' + $(this).val() + '"]').data('value');
console.log(other_val);
});
You can set values from html like this. I don't think there is a direct solution from angular yet.
<div style="visibility: hidden;">{{activeTitle='home'}}</div>
unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(
As the accepted answer indicates, you can do this by resetting the entire commit. But this is a rather heavy handed approach.
A cleaner way to do this would be to keep the commit, and simply remove the changed files from it.
git reset HEAD^ -- path/to/file
git commit --amend --no-edit
The git reset
will take the file as it was in the previous commit, and stage it in the index. The file in the working directory is untouched.
The git commit
will then commit and squash the index into the current commit.
This essentially takes the version of the file that was in the previous commit and adds it to the current commit. This results in no net change, and so the file is effectively removed from the commit.
Use characterAtIndex:
. If the first character is an asterisk, use substringFromIndex:
to get the string sans '*'.
If you need by several params:
$ids = [1,2,3,4];
$not_ids = [5,6,7,8];
DB::table('table')->whereIn('id', $ids)
->whereNotIn('id', $not_ids)
->where('status', 1)
->get();
If you want a date ($date) to get expired in some interval for example a token expiration date when performing a password reset, here's how you can do:
$date = $row->expireDate;
$date->add(new DateInterval('PT24H')); // adds 24 hours
$now = new \DateTime();
if($now < $date) { /* expired after 24 hours */ }
But in your case you could do the comparison just as the following:
$today = new DateTime('Y-m-d');
$date = $row->expireDate;
if($today < $date) { /* do something */ }
Example for OUT : Variable gets value initialized after going into the method. Later the same value is returned to the main method.
namespace outreftry
{
class outref
{
static void Main(string[] args)
{
yyy a = new yyy(); ;
// u can try giving int i=100 but is useless as that value is not passed into
// the method. Only variable goes into the method and gets changed its
// value and comes out.
int i;
a.abc(out i);
System.Console.WriteLine(i);
}
}
class yyy
{
public void abc(out int i)
{
i = 10;
}
}
}
Output:
10
===============================================
Example for Ref : Variable should be initialized before going into the method. Later same value or modified value will be returned to the main method.
namespace outreftry
{
class outref
{
static void Main(string[] args)
{
yyy a = new yyy(); ;
int i = 0;
a.abc(ref i);
System.Console.WriteLine(i);
}
}
class yyy
{
public void abc(ref int i)
{
System.Console.WriteLine(i);
i = 10;
}
}
}
Output:
0 10
=================================
Hope its clear now.
There is specific purpose to design these methods. We can't say use anyone to check file exist or not.
/**
* Remove an onclick listener
*
* @param view
* @author [email protected]
* @website https://github.com/androidmalin
* @data 2016-05-16
*/
public static void unBingListener(View view) {
if (view != null) {
try {
if (view.hasOnClickListeners()) {
view.setOnClickListener(null);
}
if (view.getOnFocusChangeListener() != null) {
view.setOnFocusChangeListener(null);
}
if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
ViewGroup viewGroup = (ViewGroup) view;
int viewGroupChildCount = viewGroup.getChildCount();
for (int i = 0; i < viewGroupChildCount; i++) {
unBingListener(viewGroup.getChildAt(i));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Is this what you mean?
SELECT DISTINCT C.valueC
FROM
C
INNER JOIN B ON C.id = B.lookupC
INNER JOIN A ON B.id = A.lookupB
It depends on the type of data you need access to. If you have some kind of data pool that needs to persist across Activity
s then Erich's answer is the way to go. If you just need to pass a few objects from one activity to another then you can have them implement Serializable
and pass them in the extras of the Intent
to start the new Activity
.
SELECT tab.*,
row_number() OVER () as rnum
FROM tab;
Here's the relevant section in the docs.
P.S. This, in fact, fully matches the answer in the referenced question.