If you run the Get-Item or Get-ChildItem commands these will output System.IO.FileInfo and System.IO.DirectoryInfo objects that contain this information e.g.:
Get-Item c:\folder | Format-List
Or you can access the property directly like so:
Get-Item c:\folder | Foreach {$_.LastWriteTime}
To start to filter folders & files based on last write time you can do this:
Get-ChildItem c:\folder | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}
ApplicationContext (Root Application Context) : Every Spring MVC web application has an applicationContext.xml file which is configured as the root of context configuration. Spring loads this file and creates an applicationContext for the entire application. This file is loaded by the ContextLoaderListener which is configured as a context param in web.xml file. And there will be only one applicationContext per web application.
WebApplicationContext : WebApplicationContext is a web aware application context i.e. it has servlet context information. A single web application can have multiple WebApplicationContext and each Dispatcher servlet (which is the front controller of Spring MVC architecture) is associated with a WebApplicationContext. The webApplicationContext configuration file *-servlet.xml is specific to a DispatcherServlet. And since a web application can have more than one dispatcher servlet configured to serve multiple requests, there can be more than one webApplicationContext file per web application.
yourTextView.setText(String.format("Value of a: %.2f", a));
No, nothing built-in (until Excel 2013 - see this answer).
There are three versions of URLEncode()
in this answer.
A variant that supports UTF-8 encoding and is based on ADODB.Stream
(include a reference to a recent version of the "Microsoft ActiveX Data Objects" library in your project):
Public Function URLEncode( _
ByVal StringVal As String, _
Optional SpaceAsPlus As Boolean = False _
) As String
Dim bytes() As Byte, b As Byte, i As Integer, space As String
If SpaceAsPlus Then space = "+" Else space = "%20"
If Len(StringVal) > 0 Then
With New ADODB.Stream
.Mode = adModeReadWrite
.Type = adTypeText
.Charset = "UTF-8"
.Open
.WriteText StringVal
.Position = 0
.Type = adTypeBinary
.Position = 3 ' skip BOM
bytes = .Read
End With
ReDim result(UBound(bytes)) As String
For i = UBound(bytes) To 0 Step -1
b = bytes(i)
Select Case b
Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
result(i) = Chr(b)
Case 32
result(i) = space
Case 0 To 15
result(i) = "%0" & Hex(b)
Case Else
result(i) = "%" & Hex(b)
End Select
Next i
URLEncode = Join(result, "")
End If
End Function
This function was found on freevbcode.com:
Public Function URLEncode( _
StringToEncode As String, _
Optional UsePlusRatherThanHexForSpace As Boolean = False _
) As String
Dim TempAns As String
Dim CurChr As Integer
CurChr = 1
Do Until CurChr - 1 = Len(StringToEncode)
Select Case Asc(Mid(StringToEncode, CurChr, 1))
Case 48 To 57, 65 To 90, 97 To 122
TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
Case 32
If UsePlusRatherThanHexForSpace = True Then
TempAns = TempAns & "+"
Else
TempAns = TempAns & "%" & Hex(32)
End If
Case Else
TempAns = TempAns & "%" & _
Right("0" & Hex(Asc(Mid(StringToEncode, _
CurChr, 1))), 2)
End Select
CurChr = CurChr + 1
Loop
URLEncode = TempAns
End Function
I've corrected a little bug that was in there.
I would use more efficient (~2× as fast) version of the above:
Public Function URLEncode( _
StringVal As String, _
Optional SpaceAsPlus As Boolean = False _
) As String
Dim StringLen As Long: StringLen = Len(StringVal)
If StringLen > 0 Then
ReDim result(StringLen) As String
Dim i As Long, CharCode As Integer
Dim Char As String, Space As String
If SpaceAsPlus Then Space = "+" Else Space = "%20"
For i = 1 To StringLen
Char = Mid$(StringVal, i, 1)
CharCode = Asc(Char)
Select Case CharCode
Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
result(i) = Char
Case 32
result(i) = Space
Case 0 To 15
result(i) = "%0" & Hex(CharCode)
Case Else
result(i) = "%" & Hex(CharCode)
End Select
Next i
URLEncode = Join(result, "")
End If
End Function
Note that neither of these two functions support UTF-8 encoding.
I was dealing with this and I noticed that you need to install the offline package for your Language. My language setting was "Español (Estados Unidos)" but there is not offline package for that language, so when I turned off all network connectivity I was getting an alert from RecognizerIntent saying that can't reach Google, then I change the language to "English (US)" (because I already have the offline package) and launched the RecognizerIntent it just worked out.
Keys: Language setting == Offline Voice Recognizer Package
You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".
You can only use real devices.
Emulator Limitations
The functional limitations of the emulator include:
Refer to the documentation
Here is an UIImage extension in Swift 2 based on the accepted answer by @Anomie. It uses a clearer switch case. It also takes the optional value returned by CGBitmapContextCreateImage()
into consideration.
extension UIImage {
func rotateImageByOrientation() -> UIImage {
// No-op if the orientation is already correct
guard self.imageOrientation != .Up else {
return self
}
// We need to calculate the proper transformation to make the image upright.
// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
var transform = CGAffineTransformIdentity;
switch (self.imageOrientation) {
case .Down, .DownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
case .Left, .LeftMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
case .Right, .RightMirrored:
transform = CGAffineTransformTranslate(transform, 0, self.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))
default:
break
}
switch (self.imageOrientation) {
case .UpMirrored, .DownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0)
transform = CGAffineTransformScale(transform, -1, 1)
case .LeftMirrored, .RightMirrored:
transform = CGAffineTransformTranslate(transform, self.size.height, 0)
transform = CGAffineTransformScale(transform, -1, 1)
default:
break
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx = CGBitmapContextCreate(nil, Int(self.size.width), Int(self.size.height),
CGImageGetBitsPerComponent(self.CGImage), 0,
CGImageGetColorSpace(self.CGImage),
CGImageGetBitmapInfo(self.CGImage).rawValue)
CGContextConcatCTM(ctx, transform)
switch (self.imageOrientation) {
case .Left, .LeftMirrored, .Right, .RightMirrored:
CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage)
default:
CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage)
}
// And now we just create a new UIImage from the drawing context
if let cgImage = CGBitmapContextCreateImage(ctx) {
return UIImage(CGImage: cgImage)
} else {
return self
}
}
}
As of nginx 1.8.0, the correct solution is
sudo nginx -t && sudo service nginx reload
Note that due to a bug, configtest
always returns a zero exit code even if the config file has an error.
I tried the above but they didn't work, i found this thought, that works a just fine for me.
var ContactID = db.GetLastInsertId();
Its less code and i easy to put in.
Hope this helps someone.
Unfortunately, not in the .Net BCL. Dates are usually represented as a DateTime object with the time set to midnight.
As you can guess, this means that you have all the attendant timezone issues around it, even though for a Date object you'd want absolutely no timezone handling.
I had much issues with this one too. I finally found out what's the final deal.
Referring to @Gokhan Oner answer, once you've got your Service class and the POJO representing your object, your YAML config file nice and lean, if you use the annotation @ConfigurationProperties, you have to explicitly get the object for being able to use it. Like :
@ConfigurationProperties(prefix = "available-payment-channels-list")
//@Configuration <- you don't specificly need this, instead you're doing something else
public class AvailableChannelsConfiguration {
private String xyz;
//initialize arraylist
private List<ChannelConfiguration> channelConfigurations = new ArrayList<>();
public AvailableChannelsConfiguration() {
for(ChannelConfiguration current : this.getChannelConfigurations()) {
System.out.println(current.getName()); //TADAAA
}
}
public List<ChannelConfiguration> getChannelConfigurations() {
return this.channelConfigurations;
}
public static class ChannelConfiguration {
private String name;
private String companyBankAccount;
}
}
And then here you go. It's simple as hell, but we have to know that we must call the object getter. I was waiting at initialization, wishing the object was being built with the value but no. Hope it helps :)
If the requested commit is in the pull requests of the remote repo, you can get it by its ID:
# Add the remote repo path, let's call it 'upstream':
git remote add upstream https://github.com/repo/project.git
# checkout the pull ID, for example ID '60':
git fetch upstream pull/60/head && git checkout FETCH_HEAD
jQuery("a[href^='#']").click(function(){_x000D_
jQuery('html, body').animate({_x000D_
scrollTop: jQuery( jQuery(this).attr('href') ).offset().top_x000D_
}, 1000);_x000D_
return false;_x000D_
});
_x000D_
Jeff Bridgman is correct. All you need is
background: url('pic.jpg')
and this assumes that pic is in the same folder as your html.
Also, Roberto's answer works fine. Tested in Firefox, and IE. Thanks to Raptor for adding formatting that displays full picture fit to screen, and without scrollbars... In a folder f, on the desktop is this html and a picture, pic.jpg, using your userid. Make those substitutions in the below:
<html>
<head>
<style>
body {
background: url('file:///C:/Users/userid/desktop/f/pic.jpg') no-repeat center center fixed;
background-size: cover; /* for IE9+, Safari 4.1+, Chrome 3.0+, Firefox 3.6+ */
-webkit-background-size: cover; /* for Safari 3.0 - 4.0 , Chrome 1.0 - 3.0 */
-moz-background-size: cover; /* optional for Firefox 3.6 */
-o-background-size: cover; /* for Opera 9.5 */
margin: 0; /* to remove the default white margin of body */
padding: 0; /* to remove the default white margin of body */
overflow: hidden;
}
</style>
</head>
<body>
hello
</body>
</html>
$.get(str, function(data){
var sary=data.split('|');
document.getElementById("select1").options.length = 0;
document.getElementById("select1").options[0] = new Option('Select a State');
for(i=0;i<sary.length-1;i++){
document.getElementById("select1").options[i+1] = new Option(sary[i]);
document.getElementById("select1").options[i+1].value = sary[i];
}
});
$('.formData').attr('value','YOUR_VALUE')
The orderBy
method requires either two strings or an Expr\OrderBy
object. If you want to add multiple order declarations, the correct thing is to use addOrderBy
method, or instantiate an OrderBy
object and populate it accordingly:
# Inside a Repository method:
$myResults = $this->createQueryBuilder('a')
->addOrderBy('a.column1', 'ASC')
->addOrderBy('a.column2', 'ASC')
->addOrderBy('a.column3', 'DESC')
;
# Or, using a OrderBy object:
$orderBy = new OrderBy('a.column1', 'ASC');
$orderBy->add('a.column2', 'ASC');
$orderBy->add('a.column3', 'DESC');
$myResults = $this->createQueryBuilder('a')
->orderBy($orderBy)
;
I faced the same problem but on Ubuntu Server. So all I did is changed to superuser before I activate virtual environment for django and then I ran the django server. It worked fine for me.
First copy paste
sudo su
Then activate the virtual environment if you have one.
source myvenv/bin/activate
At last run your django server.
python3 manage.py runserver
Hope, this will help you.
You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of
function email() {
// Opens SS by its ID
var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");
// Get the name of this SS
var name = ss.getName(); // Not necessary
// Read cell 1,1 * Line below does't work *
// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();
}
The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.
If speed is what you need and extra dependencies are not a problem, you maybe find numba
quite useful (now it is pretty easy to install, on any platform). The classic ray_tracing
approach you proposed can be easily ported to numba
by using numba @jit
decorator and casting the polygon to a numpy array. The code should look like:
@jit(nopython=True)
def ray_tracing(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
The first execution will take a little longer than any subsequent call:
%%time
polygon=np.array(polygon)
inside1 = [numba_ray_tracing_method(point[0], point[1], polygon) for
point in points]
CPU times: user 129 ms, sys: 4.08 ms, total: 133 ms
Wall time: 132 ms
Which, after compilation will decrease to:
CPU times: user 18.7 ms, sys: 320 µs, total: 19.1 ms
Wall time: 18.4 ms
If you need speed at the first call of the function you can then pre-compile the code in a module using pycc
. Store the function in a src.py like:
from numba import jit
from numba.pycc import CC
cc = CC('nbspatial')
@cc.export('ray_tracing', 'b1(f8, f8, f8[:,:])')
@jit(nopython=True)
def ray_tracing(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
if __name__ == "__main__":
cc.compile()
Build it with python src.py
and run:
import nbspatial
import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in
np.linspace(0,2*np.pi,lenpoly)[:-1]]
# random points set of points to test
N = 10000
# making a list instead of a generator to help debug
points = zip(np.random.random(N),np.random.random(N))
polygon = np.array(polygon)
%%time
result = [nbspatial.ray_tracing(point[0], point[1], polygon) for point in points]
CPU times: user 20.7 ms, sys: 64 µs, total: 20.8 ms
Wall time: 19.9 ms
In the numba code I used: 'b1(f8, f8, f8[:,:])'
In order to compile with nopython=True
, each var needs to be declared before the for loop
.
In the prebuild src code the line:
@cc.export('ray_tracing' , 'b1(f8, f8, f8[:,:])')
Is used to declare the function name and its I/O var types, a boolean output b1
and two floats f8
and a two-dimensional array of floats f8[:,:]
as input.
For my use case, I need to check if multiple points are inside a single polygon - In such a context, it is useful to take advantage of numba parallel capabilities to loop over a series of points. The example above can be changed to:
from numba import jit, njit
import numba
import numpy as np
@jit(nopython=True)
def pointinpolygon(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in numba.prange(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
D = np.empty(len(points), dtype=numba.boolean)
for i in numba.prange(0, len(D)):
D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
return D
Note: pre-compiling the above code will not enable the parallel capabilities of numba (parallel CPU target is not supported by pycc/AOT
compilation) see: https://github.com/numba/numba/issues/3336
Test:
import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]
polygon = np.array(polygon)
N = 10000
points = np.random.uniform(-1.5, 1.5, size=(N, 2))
For N=10000
on a 72 core machine, returns:
%%timeit
parallelpointinpolygon(points, polygon)
# 480 µs ± 8.19 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
0
instead of 1
(thanks @mehdi):for i in numba.prange(0, len(D))
Follow-up on the comparison made by @mehdi, I am adding a GPU-based method below. It uses the point_in_polygon
method, from the cuspatial
library:
import numpy as np
import cudf
import cuspatial
N = 100000002
lenpoly = 1000
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in
np.linspace(0,2*np.pi,lenpoly)]
polygon = np.array(polygon)
points = np.random.uniform(-1.5, 1.5, size=(N, 2))
x_pnt = points[:,0]
y_pnt = points[:,1]
x_poly =polygon[:,0]
y_poly = polygon[:,1]
result = cuspatial.point_in_polygon(
x_pnt,
y_pnt,
cudf.Series([0], index=['geom']),
cudf.Series([0], name='r_pos', dtype='int32'),
x_poly,
y_poly,
)
Following @Mehdi comparison. For N=100000002
and lenpoly=1000
- I got the following results:
time_parallelpointinpolygon: 161.54760098457336
time_mpltPath: 307.1664695739746
time_ray_tracing_numpy_numba: 353.07356882095337
time_is_inside_sm_parallel: 37.45389246940613
time_is_inside_postgis_parallel: 127.13793849945068
time_is_inside_rapids: 4.246025562286377
hardware specs:
Notes:
The cuspatial.point_in_poligon
method, is quite robust and powerful, it offers the ability to work with multiple and complex polygons (I guess at the expense of performance)
The numba
methods can also be 'ported' on the GPU - it will be interesting to see a comparison which includes a porting to cuda
of fastest method mentioned by @Mehdi (is_inside_sm
).
It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.
For example, if your sendall
always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).
In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.
Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.
Just add
white-space: initial;
to the text, a line text will come automatically in the next line.
SOA is acronym for Service Oriented Architecture.
SOA is designing and writing software applications in such a way that distinct software modules can be integrated seamlessly with high degree of re-usability.
Most of the people restrict SOA as writing client/server software-web-services. But it is too small context of SOA. SOA is much larger than that and over the past few years web-services have been primary medium of communcation which is probably the reason why people think of SOA as web-services in general restricting the boundaries and meaning of SOA.
You can think of writing a database-access module which is so independent that it can work on its own without any dependencies. This module can expose classes which can be used by any host-software that needs database access. There's no start-up configuration in host-application. Whatever is needed or required is communicated through classes exposes by database-access module. We can call these classes as services and consider the module as service-enabled.
Practicing SOA gives high degree of re-usability by enforcing DRY [Don't repeat your self] which results into highly maintainable software. Maintainability is the first thing any software architecture thinks of - SOA gives you that.
While this is usefull in rare cases (if that was not the case, the language would've allowed it directly), take a look at the Base from Member idiom. It's not a code free solution, you'd have to add an extra layer of inheritance, but it gets the job done. To avoid boilerplate code you could use boost's implementation
# Maybe you search this ??
For example in my case I use Symfony 4.4 (PHP).
If you want to update User, you need to insert the User password
encrypted and test with the current Password not encrypted to verify
if it's the same User.
For example :
public function updateUser(Request $req)
{
$entityManager = $this->getDoctrine()->getManager();
$repository = $entityManager->getRepository(User::class);
$user = $repository->find($req->get(id)); /// get User from your DB
if($user == null){
throw $this->createNotFoundException('User don't exist!!', $user);
}
$password_old_encrypted = $user->getPassword();//in your DB is always encrypted.
$passwordToUpdate = $req->get('password'); // not encrypted yet from request.
$passwordToUpdateEncrypted = password_hash($passwordToUpdate , PASSWORD_DEFAULT);
////////////VERIFY IF IT'S THE SAME PASSWORD
$isPass = password_verify($passwordToUpdateEncrypted , $password_old_encrypted );
if($isPass === false){ // failure
throw $this->createNotFoundException('Your password it's not verify', null);
}
return $isPass; //// true!! it's the same password !!!
}
One should ask why you would want a public getter method for the password. Hibernate, or any other ORM framework, will do with a private getter method. For checking whether the password is correct, you can use
public boolean checkPassword(String password){
return this.password.equals(anyHashingMethod(password));
}
In distributable software, I dont want my customers mucking about in the database by themselves. The program reads and writes it all by itself. The only reason for a user to touch the DB file is to take a backup copy. Therefore I have named it whatever_records.db
The simple .db extension tells the user that it is a binary data file and that's all they have to know. Calling it .sqlite invites the interested user to open it up and mess something up!
Totally depends on your usage scenario I suppose.
Command works only if "use" -command has been first used to define the database where working in. Table column renaming syntax using DATABASE.TABLE throws error and does not work. Version: HIVE 0.12.
EXAMPLE:
hive> ALTER TABLE databasename.tablename CHANGE old_column_name new_column_name;
MismatchedTokenException(49!=90)
at org.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:617)
at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115)
at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatementSuffixExchangePartition(HiveParser.java:11492)
...
hive> use databasename;
hive> ALTER TABLE tablename CHANGE old_column_name new_column_name;
OK
If you don't mind getting your hands dirty, it isn't that difficult to write an RTF to HTML converter.
Writing a general purpose RTF->HTML converter would be somewhat complicated because you would need to deal with hundreds of RTF verbs. However, in your case you are only dealing with those verbs used specifically by Crystal Reports. I'll bet the standard RTF coding generated by Crystal doesn't vary much from report to report.
I wrote an RTF to HTML converter in C++, but it only deals with basic formatting like fonts, paragraph alignments, etc. My translator basically strips out any specialized formatting that it isn't prepared to deal with. It took about 400 lines of C++. It basically scans the text for RTF tags and replaces them with equivalent HTML tags. RTF tags that aren't in my list are simply stripped out. A regex function is really helpful when writing such a converter.
I too encountered the same scenario and found out two solutions after googling for several times. Hope this helps.
Way 01:
Before trying to open the file in Excel, find it in Windows' File Explorer. Right-click the file and select Properties. At the bottom of the General tab, click the Unblock button. Once you unblock a file, Windows should remember and Excel should not ask you again. This option is available for some file types, but not others. If you don't have an Unblock button, use Way 2.
Way 02:
This option is better if you usually store your downloaded Excel files in one folder. In Excel, click File » Options » Trust Center » Trust Center Settings » Trusted Locations. Click Add new location. Browse to the folder where you store your Excel files, select Subfolders of this location are also trusted, and click OK.
Pass the page number for pagination as well. Some thing like this
$currentPg = Input::get('page') ? Input::get('page') : '1';_x000D_
$boards = Cache::remember('boards'.$currentPg, 60, function(){ return WhatEverModel::paginate(15); });
_x000D_
Just a note for @"John Sansom" answer,
If the foreign key dependencies are sought, I think that the PT Where clause should be:
i1.CONSTRAINT_TYPE = 'FOREIGN KEY' -- instead of 'PRIMARY KEY'
and its the ON condition:
ON PT.TABLE_NAME = FK.TABLE_NAME – instead of PK.TABLE_NAME
As commonly is used the primary key of the foreign table, I think this issue has not been noticed before.
You should have a look at date.js. It adds many convenient helpers for working with dates, for example, in your case:
var date = Date.parse('2010-08-10');
console.log(date.toString('dd-MMM-yyyy'));
Getting started: http://www.datejs.com/2007/11/27/getting-started-with-datejs/
In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:
user = UniversityDetails.objects.get(email=email)
is email a str
, or a None
? or an int
?
In your home directory, you should edit .bash_profile if you have Git for Windows 2.21.0 or later (as of this writing).
You could direct .bash_profile to just source .bashrc, but if something happens to your .bash_profile, then it will be unclear why your .bashrc is again not working.
I put all my aliases and other environment stuff in .bash_profile, and I also added this line:
echo "Sourcing ~/.bash_profile - this version of Git Bash doesn't use .bashrc"
And THEN, in .bashrc I have
echo "This version of Git Bash doesn't use .bashrc. Use .bash_profile instead"
(Building on @harsel's response. I woulda commented, but I have no points yet.)
Segmentation fault is also caused by hardware failures, in this case the RAM memories. This is the less common cause, but if you don't find an error in your code, maybe a memtest could help you.
The solution in this case, change the RAM.
edit:
Here there is a reference: Segmentation fault by hardware
Prepare for Segue in Swift 4.2 and Swift 5.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "OrderVC") {
// pass data to next view
let viewController = segue.destination as? MyOrderDetailsVC
viewController!.OrderData = self.MyorderArray[selectedIndex]
}
}
How to Call segue On specific Event(Like Button Click etc):
performSegue(withIdentifier: "OrderVC", sender: self)
Use sprintf
(or snprintf
if like me you can't count) with format string "pre_%d_suff"
.
For what it's worth, with itoa/strcat you could do:
char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");
First, we need to install the cryptography library:
pip3 install cryptography
From the cryptography library, we need to import Fernet
and start generating a key - this key is required for symmetric encryption/decryption.
To generate a key, we call the generate_key()
method.
You need to keep this key in a safe place. If you lose the key, you won't be able to decrypt the data that was encrypted with this key.
Once we have generated a key, we need to load the key with load_key()
This is a three step process:
encrypt()
methodfrom cryptography.fernet import Fernet
def generate_key():
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("secret.key", "wb") as key_file:
key_file.write(key)
def load_key():
"""
Load the previously generated key
"""
return open("secret.key", "rb").read()
def encrypt_message(message):
"""
Encrypts a message
"""
key = load_key()
encoded_message = message.encode()
f = Fernet(key)
encrypted_message = f.encrypt(encoded_message)
print(encrypted_message)
if __name__ == "__main__":
# generate_key() # execute only once
encrypt_message("Hello stackoverflow!")
output:
b'gAAAAABgLX7Zj-kn-We2BI_c9NQhEtfJEnHUVhVqtiqjkDi5dgJafj-_8QUDyeNS2zsJTdBWg6SntRJOjOM1U5mIxxsGny7IEGqpVVdHwheTnwzSBlgpb80='
To decrypt the message, we just call the decrypt()
method from the Fernet
library. Remember, we also need to load the key as well, because the key is needed to decrypt the message.
from cryptography.fernet import Fernet
def load_key():
"""
Load the previously generated key
"""
return open("secret.key", "rb").read()
def decrypt_message(encrypted_message):
"""
Decrypts an encrypted message
"""
key = load_key()
f = Fernet(key)
decrypted_message = f.decrypt(encrypted_message)
print(decrypted_message.decode())
if __name__ == "__main__":
decrypt_message(b'gAAAAABgLX7Zj-kn-We2BI_c9NQhEtfJEnHUVhVqtiqjkDi5dgJafj-_8QUDyeNS2zsJTdBWg6SntRJOjOM1U5mIxxsGny7IEGqpVVdHwheTnwzSBlgpb80=')
output:
Hello stackoverflow!
Your password is in the secret.key
in a form similar to the password below:
B8wtXqwBA_zb2Iaz5pW8CIQIwGSYSFoBiLsVz-vTqzw=
Easy, example with txt file
echo $null >> filename.txt
You can also do something like this ..
function MyCtrl1($scope) {
$rootScope.$root.name = 'anonymous';
}
function MyCtrl2($scope) {
var name = $rootScope.$root.name;
}
Install mysysgit. (Same as Greg Hewgill's answer.)
Install Tortoisegit. (Tortoisegit requires mysysgit or something similiar like Cygwin.)
After TortoiseGit is installed, right-click on a folder, select Git Clone..., then enter the Url of the repository, then click Ok.
This answer is not any better than just installing mysysgit, but you can avoid the dreaded command line. :)
Below, code snippet, will help you in understanding the mutex-lock-unlock concept. Attempt dry-run on the code. (further by varying the wait-time and process-time, you can build you understanding).
Code for your reference:
#include <stdio.h>
#include <pthread.h>
void in_progress_feedback(int);
int global = 0;
pthread_mutex_t mutex;
void *compute(void *arg) {
pthread_t ptid = pthread_self();
printf("ptid : %08x \n", (int)ptid);
int i;
int lock_ret = 1;
do{
lock_ret = pthread_mutex_trylock(&mutex);
if(lock_ret){
printf("lock failed(%08x :: %d)..attempt again after 2secs..\n", (int)ptid, lock_ret);
sleep(2); //wait time here..
}else{ //ret =0 is successful lock
printf("lock success(%08x :: %d)..\n", (int)ptid, lock_ret);
break;
}
} while(lock_ret);
for (i = 0; i < 10*10 ; i++)
global++;
//do some stuff here
in_progress_feedback(10); //processing-time here..
lock_ret = pthread_mutex_unlock(&mutex);
printf("unlocked(%08x :: %d)..!\n", (int)ptid, lock_ret);
return NULL;
}
void in_progress_feedback(int prog_delay){
int i=0;
for(;i<prog_delay;i++){
printf(". ");
sleep(1);
fflush(stdout);
}
printf("\n");
fflush(stdout);
}
int main(void)
{
pthread_t tid0,tid1;
pthread_mutex_init(&mutex, NULL);
pthread_create(&tid0, NULL, compute, NULL);
pthread_create(&tid1, NULL, compute, NULL);
pthread_join(tid0, NULL);
pthread_join(tid1, NULL);
printf("global = %d\n", global);
pthread_mutex_destroy(&mutex);
return 0;
}
Optimum buffer size is related to a number of things: file system block size, CPU cache size and cache latency.
Most file systems are configured to use block sizes of 4096 or 8192. In theory, if you configure your buffer size so you are reading a few bytes more than the disk block, the operations with the file system can be extremely inefficient (i.e. if you configured your buffer to read 4100 bytes at a time, each read would require 2 block reads by the file system). If the blocks are already in cache, then you wind up paying the price of RAM -> L3/L2 cache latency. If you are unlucky and the blocks are not in cache yet, the you pay the price of the disk->RAM latency as well.
This is why you see most buffers sized as a power of 2, and generally larger than (or equal to) the disk block size. This means that one of your stream reads could result in multiple disk block reads - but those reads will always use a full block - no wasted reads.
Now, this is offset quite a bit in a typical streaming scenario because the block that is read from disk is going to still be in memory when you hit the next read (we are doing sequential reads here, after all) - so you wind up paying the RAM -> L3/L2 cache latency price on the next read, but not the disk->RAM latency. In terms of order of magnitude, disk->RAM latency is so slow that it pretty much swamps any other latency you might be dealing with.
So, I suspect that if you ran a test with different cache sizes (haven't done this myself), you will probably find a big impact of cache size up to the size of the file system block. Above that, I suspect that things would level out pretty quickly.
There are a ton of conditions and exceptions here - the complexities of the system are actually quite staggering (just getting a handle on L3 -> L2 cache transfers is mind bogglingly complex, and it changes with every CPU type).
This leads to the 'real world' answer: If your app is like 99% out there, set the cache size to 8192 and move on (even better, choose encapsulation over performance and use BufferedInputStream to hide the details). If you are in the 1% of apps that are highly dependent on disk throughput, craft your implementation so you can swap out different disk interaction strategies, and provide the knobs and dials to allow your users to test and optimize (or come up with some self optimizing system).
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
You can go to jwt.io
, paste your token and read the contents. This is jarring for a lot of people initially.
The short answer is that JWT doesn't concern itself with encryption. It cares about validation. That is to say, it can always get the answer for "Have the contents of this token been manipulated"? This means user manipulation of the JWT token is futile because the server will know and disregard the token. The server adds a signature based on the payload when issuing a token to the client. Later on it verifies the payload and matching signature.
The logical question is what is the motivation for not concerning itself with encrypted contents?
The simplest reason is because it assumes this is a solved problem for the most part. If dealing with a client like the web browser for example, you can store the JWT tokens in a cookie that is secure
(is not transmitted via HTTP, only via HTTPS) and httpOnly
(can't be read by Javascript) and talks to the server over an encrypted channel (HTTPS). Once you know you have a secure channel between the server and client you can securely exchange JWT or whatever else you want.
This keeps thing simple. A simple implementation makes adoption easier but it also lets each layer do what it does best (let HTTPS handle encryption).
JWT isn't meant to store sensitive data. Once the server receives the JWT token and validates it, it is free to lookup the user ID in its own database for additional information for that user (like permissions, postal address, etc). This keeps JWT small in size and avoids inadvertent information leakage because everyone knows not to keep sensitive data in JWT.
It's not too different from how cookies themselves work. Cookies often contain unencrypted payloads. If you are using HTTPS then everything is good. If you aren't then it's advisable to encrypt sensitive cookies themselves. Not doing so will mean that a man-in-the-middle attack is possible--a proxy server or ISP reads the cookies and then replays them later on pretending to be you. For similar reasons, JWT should always be exchanged over a secure layer like HTTPS.
Ctrl-ww
This will move between open windows (so you could hop between the NERDTree window, the file you are editing and the help window, for example... just hold down Ctrl and press w twice).
Sometimes when you download plugins you may get (.zip) files then just rename with (.hpi) and then extract all the plugins and move to <jenkinsHome>/plugins/
directory.
Math.abs(x)
or if you are certain the value is negative before the conversion just prepend a regular minus sign: x = -x
.
Ok - for me the source of the problem was in serialisation/deserialisation. The object that was being sent and received was as follows where the code is submitted and the code and maskedPhoneNumber is returned.
@ApiObject(description = "What the object is for.")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CodeVerification {
@ApiObjectField(description = "The code which is to be verified.")
@NotBlank(message = "mandatory")
private final String code;
@ApiObjectField(description = "The masked mobile phone number to which the code was verfied against.")
private final String maskedMobileNumber;
public codeVerification(@JsonProperty("code") String code, String maskedMobileNumber) {
this.code = code;
this.maskedMobileNumber = maskedMobileNumber;
}
public String getcode() {
return code;
}
public String getMaskedMobileNumber() {
return maskedMobileNumber;
}
}
The problem was that I didn't have a JsonProperty defined for the maskedMobileNumber in the constructor. i.e. Constructor should have been
public codeVerification(@JsonProperty("code") String code, @JsonProperty("maskedMobileNumber") String maskedMobileNumber) {
this.code = code;
this.maskedMobileNumber = maskedMobileNumber;
}
SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log
method has been changed (added Object[] p5):
SLF4J 1.5.11:
LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
String p4, Throwable p5 )
SLF4J 1.6.0:
LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
String p4, Object[] p5, Throwable p6 )
See compatibility reports for other SLF4J versions on this page.
You can generate such reports by the japi-compliance-checker tool.
Thought I'd give a full answer combining some of the possible intricacies required for completeness.
w3wp.exe
. If it's showing as w3wp*32.exe
then it's 32-bit.One way that you can do it is creating a new object in the module instead of replacing it.
for example:
var testone = function () {
console.log('test one');
};
var testTwo = function () {
console.log('test two');
};
module.exports.testOne = testOne;
module.exports.testTwo = testTwo;
and to call
var test = require('path_to_file').testOne:
testOne();
I know you are using Datepicker, but for some people who are just using HTML5 input date like me, there is an example how you can do the same: JSFiddle Link
$('#start_date').change(function(){
var start_date = $(this).val();
$('#end_date').prop({
min: start_date
});
});
/* prop() method works since jquery 1.6, if you are using a previus version, you can use attr() method.*/
One that I use often:
Integer.parseInt("1234");
Point is, there are plenty of ways to do this, all equally valid. As to which is most optimum/efficient, you'd have to ask someone else.
while doing performance testing, the measure i go by is RPS, that is how many requests per second can the server serve within acceptable latency.
theoretically one server can only run as many requests concurrently as number of cores on it..
It doesn't look like the problem is ASP.net's threading model, since it can potentially serve thousands of rps. It seems like the problem might be your application. Are you using any synchronization primitives ?
also whats the latency on your web services, are they very quick to respond (within microseconds), if not then you might want to consider asynchronous calls, so you dont end up blocking
If this doesnt yeild something, then you might want to profile your code using visual studio or redgate profiler
Another solution that resolved this same error for me, though this one might only be if you are accessing mongo (locally) via a SSH connection via a virtual machine (at least that's my setup), and may be a linux specific environment variable issue:
export LC_ALL=C
Also, I have had more success running mongo as a daemon service then with sudo service start, my understanding is this uses command line arguments rather then the config file so it likely is an issue with my config file:
mongod --fork --logpath /var/log/mongodb.log --auth --port 27017 --dbpath /var/lib/mongodb/admin
My problem was the same, but the solution had to do with changing a firewall setting. It turned out that node was set to block incoming traffic. I knew something was up because I used to be able to get to my localhost server from my phone.
Go to System Preferences -> Security & Privacy -> Firewall -> Firewall Options, and then scroll down until you find node and make sure node's setting is set to Allow incoming connections.
After changing the setting, I could reach the localhost server (port 3000) running on my Mac by going to http://192.168.1.11:3000
First of all you need to remove the data-toggle attribute. We will use some JQuery, so make sure you include it.
<ul class='nav nav-tabs'>
<li class='active'><a href='#home'>Home</a></li>
<li><a href='#menu1'>Menu 1</a></li>
<li><a href='#menu2'>Menu 2</a></li>
<li><a href='#menu3'>Menu 3</a></li>
</ul>
<div class='tab-content'>
<div id='home' class='tab-pane fade in active'>
<h3>HOME</h3>
<div id='menu1' class='tab-pane fade'>
<h3>Menu 1</h3>
</div>
<div id='menu2' class='tab-pane fade'>
<h3>Menu 2</h3>
</div>
<div id='menu3' class='tab-pane fade'>
<h3>Menu 3</h3>
</div>
</div>
</div>
<script>
$(document).ready(function(){
// Handling data-toggle manually
$('.nav-tabs a').click(function(){
$(this).tab('show');
});
// The on tab shown event
$('.nav-tabs a').on('shown.bs.tab', function (e) {
alert('Hello from the other siiiiiide!');
var current_tab = e.target;
var previous_tab = e.relatedTarget;
});
});
</script>
Disclosure: I wrote the code that Trello uses; the code below is the actual source code Trello uses to accomplish the clipboard trick.
We don't actually "access the user's clipboard", instead we help the user out a bit by selecting something useful when they press Ctrl+C.
Sounds like you've figured it out; we take advantage of the fact that when you want to hit Ctrl+C, you have to hit the Ctrl key first. When the Ctrl key is pressed, we pop in a textarea that contains the text we want to end up on the clipboard, and select all the text in it, so the selection is all set when the C key is hit. (Then we hide the textarea when the Ctrl key comes up.)
Specifically, Trello does this:
TrelloClipboard = new class
constructor: ->
@value = ""
$(document).keydown (e) =>
# Only do this if there's something to be put on the clipboard, and it
# looks like they're starting a copy shortcut
if !@value || !(e.ctrlKey || e.metaKey)
return
if $(e.target).is("input:visible,textarea:visible")
return
# Abort if it looks like they've selected some text (maybe they're trying
# to copy out a bit of the description or something)
if window.getSelection?()?.toString()
return
if document.selection?.createRange().text
return
_.defer =>
$clipboardContainer = $("#clipboard-container")
$clipboardContainer.empty().show()
$("<textarea id='clipboard'></textarea>")
.val(@value)
.appendTo($clipboardContainer)
.focus()
.select()
$(document).keyup (e) ->
if $(e.target).is("#clipboard")
$("#clipboard-container").empty().hide()
set: (@value) ->
In the DOM we've got:
<div id="clipboard-container"><textarea id="clipboard"></textarea></div>
CSS for the clipboard stuff:
#clipboard-container {
position: fixed;
left: 0px;
top: 0px;
width: 0px;
height: 0px;
z-index: 100;
display: none;
opacity: 0;
}
#clipboard {
width: 1px;
height: 1px;
padding: 0px;
}
... and the CSS makes it so you can't actually see the textarea when it pops in ... but it's "visible" enough to copy from.
When you hover over a card, it calls
TrelloClipboard.set(cardUrl)
... so then the clipboard helper knows what to select when the Ctrl key is pressed.
To use the default android drawable resource, no need copy anything.. you can just import it first with..
import android.R;
but i will make your own resources will have an error if you want to use it. The error will be something like:
R. cannot be resolved
So, I prefer not to import android.R
but import *my.own.package*.R;
then when I can normally use my own resource with R.drawable.*something*
without error,
and put android.R.*something_default*
to use the default android resources.
You Can Follow These Steps.
pip install jupyterthemes
or pip install --upgrade jupyterthemes
to upgrade to latest version of theme.jt -l
jt-t <themename>
for example jt -t solarizedl
Here, I wrote something similar to what u need:
inputBoxNumberEt.setText(". ");
inputBoxNumberEt.setSelection(inputBoxNumberEt.getText().length());
inputBoxNumberEt.addTextChangedListener(new TextWatcher() {
boolean ignoreChange = false;
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (!ignoreChange) {
String string = s.toString();
string = string.replace(".", "");
string = string.replace(" ", "");
if (string.length() == 0)
string = ". ";
else if (string.length() == 1)
string = ". " + string;
else if (string.length() == 2)
string = "." + string;
else if (string.length() > 2)
string = string.substring(0, string.length() - 2) + "." + string.substring(string.length() - 2, string.length());
ignoreChange = true;
inputBoxNumberEt.setText(string);
inputBoxNumberEt.setSelection(inputBoxNumberEt.getText().length());
ignoreChange = false;
}
}
});
Use
git apply patchfile
if possible.
patch -p1 < patchfile
has potential side-effect.
git apply
also handles file adds, deletes, and renames if they're described in the git diff
format, which patch
won't do. Finally, git apply
is an "apply all or abort all" model where either everything is applied or nothing is, whereas patch can partially apply patch files, leaving your working directory in a weird state.
Just for those who want to get $setPristine
without having to upgrade to v1.1.x, here is the function I used to simulate the $setPristine
function. I was reluctant to use the v1.1.5 because one of the AngularUI components I used is no compatible.
var setPristine = function(form) {
if (form.$setPristine) {//only supported from v1.1.x
form.$setPristine();
} else {
/*
*Underscore looping form properties, you can use for loop too like:
*for(var i in form){
* var input = form[i]; ...
*/
_.each(form, function (input) {
if (input.$dirty) {
input.$dirty = false;
}
});
}
};
Note that it ONLY makes $dirty
fields clean and help changing the 'show error' condition like $scope.myForm.myField.$dirty && $scope.myForm.myField.$invalid
.
Other parts of the form object (like the css classes) still need to consider, but this solve my problem: hide error messages.
Use the onclick
as an attribute of your a
, not part of the href
<a onclick='window.open("lead_data.php?leadid=1", myWin, scrollbars=yes, width=400, height=650);'>1</a>
Fiddle: http://jsfiddle.net/Wt5La/
This is old I know, but just a pointer to anyone using this ass a reference. I have just tried this and if you are using Oracle, JOIN does not work in DELETE statements. You get a the following message:
ORA-00933: SQL command not properly ended.
type NumberArray = Array<{id: number, text: string}>;
const arr: NumberArray = [
{id: 0, text: 'Number 0'},
{id: 1, text: 'Number 1'},
{id: 2, text: 'Number 2'},
{id: 3, text: 'Number 3 '},
{id: 4, text: 'Number 4 '},
{id: 5, text: 'Number 5 '},
];
The error seems to be thrown when you try and load they keystore from "C:/jakarta-tomcat/webapps/PlanB/Certs/my_pkcs12.p12" here:
ks.load( new FileInputStream(_privateKeyPath), _keyPass.toCharArray() );
Have you tried replaceing "/" with "\\" in your file path? If that doesn't help it probably has to do with Java's Unlimited Strength Jurisdiction Policy Files. You could check this by writing a little program that does AES encryption. Try encrypting with a 128 bit key, then if that works, try with a 256 bit key and see if it fails.
Code that does AES encyrption:
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Test
{
final String ALGORITHM = "AES"; //symmetric algorithm for data encryption
final String PADDING_MODE = "/CBC/PKCS5Padding"; //Padding for symmetric algorithm
final String CHAR_ENCODING = "UTF-8"; //character encoding
//final String CRYPTO_PROVIDER = "SunMSCAPI"; //provider for the crypto
int AES_KEY_SIZE = 256; //symmetric key size (128, 192, 256) if using 256 you must have the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files installed
private String doCrypto(String plainText) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException
{
byte[] dataToEncrypt = plainText.getBytes(CHAR_ENCODING);
//get the symmetric key generator
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
keyGen.init(AES_KEY_SIZE); //set the key size
//generate the key
SecretKey skey = keyGen.generateKey();
//convert to binary
byte[] rawAesKey = skey.getEncoded();
//initialize the secret key with the appropriate algorithm
SecretKeySpec skeySpec = new SecretKeySpec(rawAesKey, ALGORITHM);
//get an instance of the symmetric cipher
Cipher aesCipher = Cipher.getInstance(ALGORITHM + PADDING_MODE);
//set it to encrypt mode, with the generated key
aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
//get the initialization vector being used (to be returned)
byte[] aesIV = aesCipher.getIV();
//encrypt the data
byte[] encryptedData = aesCipher.doFinal(dataToEncrypt);
//initialize the secret key with the appropriate algorithm
SecretKeySpec skeySpecDec = new SecretKeySpec(rawAesKey, ALGORITHM);
//get an instance of the symmetric cipher
Cipher aesCipherDec = Cipher.getInstance(ALGORITHM +PADDING_MODE);
//set it to decrypt mode with the AES key, and IV
aesCipherDec.init(Cipher.DECRYPT_MODE, skeySpecDec, new IvParameterSpec(aesIV));
//decrypt and return the data
byte[] decryptedData = aesCipherDec.doFinal(encryptedData);
return new String(decryptedData, CHAR_ENCODING);
}
public static void main(String[] args)
{
String text = "Lets encrypt me";
Test test = new Test();
try {
System.out.println(test.doCrypto(text));
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Does this code work for you?
You might also want to try specifying your bouncy castle provider in this line:
Cipher.getInstance(ALGORITHM +PADDING_MODE, "YOUR PROVIDER");
And see if it could be an error associated with bouncy castle.
If you can't find the build path error, sometimes menu Project ? Clean... works like a charm.
First day of week (Monday):
SELECT TO_DATE(to_char(sysdate,'YYYY')||'0101','YYYYMMDD') + 7 * to_number(to_char(sysdate,'WW')-1)-1 first_day_week FROM dual;
Last day of week (Sunday):
SELECT TO_DATE(to_char(sysdate,'YYYY')||'0101','YYYYMMDD') + 7 * to_number(to_char(sysdate,'WW')-1)+5 last_day_week FROM dual;
Substituting your date or date field in these formulas will work for you!
I dont do it like this. I find it easier to overload the constructor of the asychtask class ..
public class calc_stanica extends AsyncTask>
String String mWhateveryouwantToPass;
public calc_stanica( String whateveryouwantToPass)
{
this.String mWhateveryouwantToPass = String whateveryouwantToPass;
}
/*Now you can use whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/ ... ...
A good, concise article by Pankaj Malhotra discusses how to do this with NGINX and is available here.
The basic NGINX configuration is reproduced below:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream appserver {
server 192.168.100.10:9222; # appserver_ip:ws_port
}
server {
listen 8888; // client_wss_port
ssl on;
ssl_certificate /path/to/crt;
ssl_certificate_key /path/to/key;
location / {
proxy_pass http://appserver;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
The difference is in the scope of the variables declared with each.
In practice, there are a number of useful consequences of the difference in scope:
let
variables are only visible in their nearest enclosing block ({ ... }
).let
variables are only usable in lines of code that occur after the variable is declared (even though they are hoisted!).let
variables may not be redeclared by a subsequent var
or let
.let
variables are not added to the global window
object.let
variables are easy to use with closures (they do not cause race conditions).The restrictions imposed by let
reduce the visibility of the variables and increase the likelihood that unexpected name collisions will be found early. This makes it easier to track and reason about variables, including their reachability(helping with reclaiming unused memory).
Consequently, let
variables are less likely to cause problems when used in large programs or when independently-developed frameworks are combined in new and unexpected ways.
var
may still be useful if you are sure you want the single-binding effect when using a closure in a loop (#5) or for declaring externally-visible global variables in your code (#4). Use of var
for exports may be supplanted if export
migrates out of transpiler space and into the core language.
1. No use outside nearest enclosing block:
This block of code will throw a reference error because the second use of x
occurs outside of the block where it is declared with let
:
{
let x = 1;
}
console.log(`x is ${x}`); // ReferenceError during parsing: "x is not defined".
In contrast, the same example with var
works.
2. No use before declaration:
This block of code will throw a ReferenceError
before the code can be run because x
is used before it is declared:
{
x = x + 1; // ReferenceError during parsing: "x is not defined".
let x;
console.log(`x is ${x}`); // Never runs.
}
In contrast, the same example with var
parses and runs without throwing any exceptions.
3. No redeclaration:
The following code demonstrates that a variable declared with let
may not be redeclared later:
let x = 1;
let x = 2; // SyntaxError: Identifier 'x' has already been declared
4. Globals not attached to window
:
var button = "I cause accidents because my name is too common.";
let link = "Though my name is common, I am harder to access from other JS files.";
console.log(link); // OK
console.log(window.link); // undefined (GOOD!)
console.log(window.button); // OK
5. Easy use with closures:
Variables declared with var
do not work well with closures inside loops. Here is a simple loop that outputs the sequence of values that the variable i
has at different points in time:
for (let i = 0; i < 5; i++) {
console.log(`i is ${i}`), 125/*ms*/);
}
Specifically, this outputs:
i is 0
i is 1
i is 2
i is 3
i is 4
In JavaScript we often use variables at a significantly later time than when they are created. When we demonstrate this by delaying the output with a closure passed to setTimeout
:
for (let i = 0; i < 5; i++) {
setTimeout(_ => console.log(`i is ${i}`), 125/*ms*/);
}
... the output remains unchanged as long as we stick with let
. In contrast, if we had used var i
instead:
for (var i = 0; i < 5; i++) {
setTimeout(_ => console.log(`i is ${i}`), 125/*ms*/);
}
... the loop unexpectedly outputs "i is 5" five times:
i is 5
i is 5
i is 5
i is 5
i is 5
select t.OtherID,x.Kod
from testData t
cross apply (select Code from dbo.Split(t.Data,',') ) x
Apple's implementation of @synchronized is open source and it can be found here. Mike ash wrote two really interesting post about this subject:
In a nutshell it has a table that maps object pointers (using their memory addresses as keys) to pthread_mutex_t
locks, which are locked and unlocked as needed.
Use repr()[1:-1]. In this case, the double quotes don't need to be escaped. The [-1:1] slice is to remove the single quote from the beginning and the end.
>>> x = raw_input()
I'm "stuck" :\
>>> print x
I'm "stuck" :\
>>> print repr(x)[1:-1]
I\'m "stuck" :\\
Or maybe you just want to escape a phrase to paste into your program? If so, do this:
>>> raw_input()
I'm "stuck" :\
'I\'m "stuck" :\\'
I have found this answer and I edit that in more reliable way
def download_photo(self, img_url, filename):
try:
image_on_web = urllib.urlopen(img_url)
if image_on_web.headers.maintype == 'image':
buf = image_on_web.read()
path = os.getcwd() + DOWNLOADED_IMAGE_PATH
file_path = "%s%s" % (path, filename)
downloaded_image = file(file_path, "wb")
downloaded_image.write(buf)
downloaded_image.close()
image_on_web.close()
else:
return False
except:
return False
return True
From this you never get any other resources or exceptions while downloading.
If you want to select the type of console, you can write this in the file "keybinding.json" (this file can be found in the following path "File-> Preferences-> Keyboard Shortcuts") `
//with this you can select what type of console you want
{
"key": "ctrl+shift+t",
"command": "shellLauncher.launch"
},
//and this will help you quickly change console
{
"key": "ctrl+shift+j",
"command": "workbench.action.terminal.focusNext"
},
{
"key": "ctrl+shift+k",
"command": "workbench.action.terminal.focusPrevious"
}`
based from the answer of @SW4, you could also add a little animation at the end.
body > div{_x000D_
border:1px solid grey;_x000D_
}_x000D_
html, body, #container {_x000D_
height:100%;_x000D_
width:100%;_x000D_
margin:0;_x000D_
padding:0;_x000D_
}_x000D_
#container {_x000D_
overflow:hidden;_x000D_
position:relative;_x000D_
}_x000D_
#hideMe {_x000D_
-webkit-animation: cssAnimation 5s forwards; _x000D_
animation: cssAnimation 5s forwards;_x000D_
}_x000D_
@keyframes cssAnimation {_x000D_
0% {opacity: 1;}_x000D_
90% {opacity: 1;}_x000D_
100% {opacity: 0;}_x000D_
}_x000D_
@-webkit-keyframes cssAnimation {_x000D_
0% {opacity: 1;}_x000D_
90% {opacity: 1;}_x000D_
100% {opacity: 0;}_x000D_
}
_x000D_
<div>_x000D_
<div id='container'>_x000D_
<div id='hideMe'>Wait for it...</div>_x000D_
</div>_x000D_
</div>
_x000D_
Making the remaining 0.5 seconds to animate the opacity attribute. Just make sure to do the math if you're changing the length, in this case, 90% of 5 seconds leaves us 0.5 seconds to animate the opacity.
sending tag <img src="c:\images\mypic.jpg">
would cause user browser to access image from his filesystem.
if you have to store images in folder located in c:\images
i would suggest to create an servlet like images.jsp, that as a parameter takes name of a file, then sets servlet response content to an image/jpg and then loads bytes of image from server location and put it to a response.
But what you use to create your application? is it pure servlet? Spring? JSF?
Here you can find some info about, how to do it.
Use the @Url.Action method. This will work and determines the correct route regardless of what IIS server you deploy to.
Example- window.location.href="@Url.Action("Action", "Controller")";
so in the case of the Index action on the Home controller - window.location.href="@Url.Action("Index", "Home")";
var student = [];
var obj = {
'first_name': name,
'last_name': name,
'age': age,
}
student.push(obj);
The following succeeded with asp.net core 2.1. It may apply elsewhere. The dictionary ControllerBase.ControllerContext.RouteData.Values is directly accessible and writable from within the action method. Perhaps this is the ultimate destination of the data in the other solutions. It also shows where the default routing data comes from.
[Route("/to/{email?}")]
public IActionResult ToAction(string email)
{
return View("To", email);
}
[Route("/from")]
public IActionResult FromAction()
{
ControllerContext.RouteData.Values.Add("email", "[email protected]");
return RedirectToAction(nameof(ToAction));
// will redirect to /to/[email protected]
}
[Route("/FromAnother/{email?}")]`
public IActionResult FromAnotherAction(string email)
{
return RedirectToAction(nameof(ToAction));
// will redirect to /to/<whatever the email param says>
// no need to specify the route part explicitly
}
I've used JMeter. Besides testing the web server you can also test your database backend, messaging services and email servers.
In my case, i installed node with NVM and after installing z Shell, node and nvm command didn't worked. So what worked for me was installing nvm again with this command :
wget https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash
sudo zsh install.sh
Above commands installed nvm again, since node was already installed, it added the node path automatically in .zshrc file and everything worked.
Try this in your forth column
=COUNTIF(B:B; ">" & B2) + 1
Replace B2 with B3 for next row and so on.
What this does is it counts how many records have more points then current one and then this adds current record position (+1 part).
I often just open the console and look for the solution in the objects methods. Quite often it's already there:
>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello s'
Short answer: Use string.replace()
.
function findIndexByKeyValue(_array, key, value) {
for (var i = 0; i < _array.length; i++) {
if (_array[i][key] == value) {
return i;
}
}
return -1;
}
var a = [
{prop1:"abc",prop2:"qwe"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}];
var index = findIndexByKeyValue(a, 'prop2', 'yutu');
console.log(index);
For Python 3:
>>> import re
>>> re.sub(r'\s+', '', 'strip my \n\t\r ASCII and \u00A0 \u2003 Unicode spaces')
'stripmyASCIIandUnicodespaces'
>>> # Or, depending on the situation:
>>> re.sub(r'(\s|\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF)+', '', \
... '\uFEFF\t\t\t strip all \u000A kinds of \u200B whitespace \n')
'stripallkindsofwhitespace'
...handles any whitespace characters that you're not thinking of - and believe us, there are plenty.
\s
on its own always covers the ASCII whitespace:
Additionally:
re.UNICODE
enabled,...\s
also covers the Unicode whitespace characters, for example:
...etc. See the full list here, under "Unicode characters with White_Space property".
However \s
DOES NOT cover characters not classified as whitespace, which are de facto whitespace, such as among others:
...etc. See the full list here, under "Related Unicode characters without White_Space property".
So these 6 characters are covered by the list in the second regex, \u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF
.
Sources:
I would advice to check the logic of ListActivity
according to what is needed could be the best way not to lose much time
A war file is just a zip file with a specific directory structure. So you can use unzip or the jar tool for unzipping.
But you probably don't want to do that. If you add the war file into the webapps directory of Tomcat the Tomcat will take care of extracting/installing the war file.
I added this to my pom.xml below the project description and it worked:
<properties>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
</properties>
Strangely enough, I wrote some code to do this back when 1.1 came out (what was that, seven years ago?) and tweaked it a little when 2.0 came out. I haven't looked at it in years as we no longer manage our servers.
It's not foolproof, but I'm posting it anyway because I find it humorous; in that it's easier to do in .NET and easier still in power shell.
bool GetFileVersion(LPCTSTR filename,WORD *majorPart,WORD *minorPart,WORD *buildPart,WORD *privatePart)
{
DWORD dwHandle;
DWORD dwLen = GetFileVersionInfoSize(filename,&dwHandle);
if (dwLen) {
LPBYTE lpData = new BYTE[dwLen];
if (lpData) {
if (GetFileVersionInfo(filename,0,dwLen,lpData)) {
UINT uLen;
VS_FIXEDFILEINFO *lpBuffer;
VerQueryValue(lpData,_T("\\"),(LPVOID*)&lpBuffer,&uLen);
*majorPart = HIWORD(lpBuffer->dwFileVersionMS);
*minorPart = LOWORD(lpBuffer->dwFileVersionMS);
*buildPart = HIWORD(lpBuffer->dwFileVersionLS);
*privatePart = LOWORD(lpBuffer->dwFileVersionLS);
delete[] lpData;
return true;
}
}
}
return false;
}
int _tmain(int argc,_TCHAR* argv[])
{
_TCHAR filename[MAX_PATH];
_TCHAR frameworkroot[MAX_PATH];
if (!GetEnvironmentVariable(_T("systemroot"),frameworkroot,MAX_PATH))
return 1;
_tcscat_s(frameworkroot,_T("\\Microsoft.NET\\Framework\\*"));
WIN32_FIND_DATA FindFileData;
HANDLE hFind = FindFirstFile(frameworkroot,&FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
return 2;
do {
if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
_tcslen(FindFileData.cAlternateFileName) != 0) {
_tcsncpy_s(filename,frameworkroot,_tcslen(frameworkroot)-1);
filename[_tcslen(frameworkroot)] = 0;
_tcscat_s(filename,FindFileData.cFileName);
_tcscat_s(filename,_T("\\mscorlib.dll"));
WORD majorPart,minorPart,buildPart,privatePart;
if (GetFileVersion(filename,&majorPart,&minorPart,&buildPart,&privatePart )) {
_tprintf(_T("%d.%d.%d.%d\r\n"),majorPart,minorPart,buildPart,privatePart);
}
}
} while (FindNextFile(hFind,&FindFileData) != 0);
FindClose(hFind);
return 0;
}
Try this:
hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)
If you don't like the 0x
in the beginning, replace the last line with
print hex(new_int)[2:]
For angular 5+
version. Putting version helps as angular makes lot of changes.
ngOnInit() {
this.myForm = formBuilder.group({
firstName: 'Thomas',
lastName: 'Mann'
})
this.formControlValueChanged() // Note if you are doing an edit/fetching data from an observer this must be called only after your form is properly initialized otherwise you will get error.
}
formControlValueChanged(): void {
this.myForm.valueChanges.subscribe(value => {
console.log('value changed', value)
})
}
Basically, you get connections in the Sleep state when :
So, you generally end up with many processes in a Sleep state when you have a lot of PHP processes that stay connected, without actually doing anything on the database-side.
A basic idea, so : make sure you don't have PHP processes that run for too long -- or force them to disconnect as soon as they don't need to access the database anymore.
Another thing, that I often see when there is some load on the server :
A solution that can help is to reduce the time your queries take -- optimizing the longest ones.
function getMonthDays(MonthYear) {
var months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
var Value=MonthYear.split(" ");
var month = (months.indexOf(Value[0]) + 1);
return new Date(Value[1], month, 0).getDate();
}
console.log(getMonthDays("March 2011"));
Iv'd found 2 solutions to the problem, which its implied that you detect touch with modernizr or something else and set a touch class on the html element.
This is good but not supported very well:
html.touch *:hover {
all:unset!important;
}
But this has a very good support:
html.touch *:hover {
pointer-events: none !important;
}
Works flawless for me, it makes all the hover effects be like when you have a touch on a button it will light up but not end up buggy as the initial hover effect for mouse events.
Detecting touch from no-touch devices i think modernizr has done the best job:
https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touchevents.js
EDIT
I found a better and simpler solution to this issue
What I would suggest is not converting the non-static class to a static class because in that case, your inner class can't access the non-static members of outer class.
Example :
class Outer
{
class Inner
{
//...
}
}
So, in such case, you can do something like:
Outer o = new Outer();
Outer.Inner obj = o.new Inner();
Are you sure you cloned it using the ssh url?
The url for origin says url = https://[email protected]/Nicolas_Raoul/therepo.git
so if it is using https it will ask for password irrespective of your ssh keys.
So what you want to do is the following:
open your config file in your current repo ..
vim .git/config
and change the line with the url from
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = https://[email protected]/Nicolas_Raoul/therepo.git
to
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = [email protected]:Nicolas_Raoul/therepo.git
What about using something like:
<?php
$page_title = "Your page tile";
include("navigation.php"); // if required
echo("<title>$page_title</title>");
?>
Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.
The URL http://fakedomain.com/smilemachine/html.css
in your <link>
Tag is wrong. File not Found.
There is a hasClass function
if($('#popup p').hasClass('filled-text'))
Using Java, using Apache Commons String Utils:
public boolean isPalindrome(String phrase) {
phrase = phrase.toLowerCase().replaceAll("[^a-z]", "");
return StringUtils.reverse(phrase).equals(phrase);
}
To get the occurrences of the object from the list directly:
int noOfOccurs = Collections.frequency(animals, "bat");
To get the occurrence of the Object collection inside list, override the equals method in the Object class as:
@Override
public boolean equals(Object o){
Animals e;
if(!(o instanceof Animals)){
return false;
}else{
e=(Animals)o;
if(this.type==e.type()){
return true;
}
}
return false;
}
Animals(int type){
this.type = type;
}
Call the Collections.frequency as:
int noOfOccurs = Collections.frequency(animals, new Animals(1));
>>> l = raw_input()
1 2 3 4 5 6 7 8 9 10
>>> l = l.split()
>>> l.pop(0)
'1'
>>> sum(map(int, l)) #or simply sum(int(x) for x in l) , you've to convert the elements to integer first, before applying sum()
54
It's even simpler than that. Just did this (on Windows, but it should work on other OS):
Git just sees you added a directory and renamed a bunch of files. No biggie.
I would use FMOD to do this for your game. It has the ability to play any file mostly for sounds and is pretty simple to implement in C++. using FMOD and Dir3ect X together can be powerful and not that difficult. If you are familiar with Singleton classes I would create a Singleton class of a sound manager in your win main cpp and then have access to it whenever to load or play new music or sound effects. here's an audio manager example
#pragma once
#ifndef H_AUDIOMANAGER
#define H_AUDIOMANAGER
#include <string>
#include <Windows.h>
#include "fmod.h"
#include "fmod.hpp"
#include "fmod_codec.h"
#include "fmod_dsp.h"
#include "fmod_errors.h"
#include "fmod_memoryinfo.h"
#include "fmod_output.h"
class AudioManager
{
public:
// Destructor
~AudioManager(void);
void Initialize(void); // Initialize sound components
void Shutdown(void); // Shutdown sound components
// Singleton instance manip methods
static AudioManager* GetInstance(void);
static void DestroyInstance(void);
// Accessors
FMOD::System* GetSystem(void)
{return soundSystem;}
// Sound playing
void Play(FMOD::Sound* sound); // Play a sound/music with default channel
void PlaySFX(FMOD::Sound* sound); // Play a sound effect with custom channel
void PlayBGM(FMOD::Sound* sound); // Play background music with custom channel
// Volume adjustment methods
void SetBGMVolume(float volume);
void SetSFXVolume(float volume);
private:
static AudioManager* instance; // Singleton instance
AudioManager(void); // Constructor
FMOD::System* soundSystem; // Sound system object
FMOD_RESULT result;
FMOD::Channel* bgmChannel; // Channel for background music
static const int numSfxChannels = 4;
FMOD::Channel* sfxChannels[numSfxChannels]; // Channel for sound effects
};
#endif
There is no float: center; in css. Use margin: 0 auto; instead. So like this:
.mydivclass {
margin: 0 auto;
}
Are you looking for the syntax to open them:
Dim wkbk As Workbook
Set wkbk = Workbooks.Open("C:\MyDirectory\mysheet.xlsx")
Then, you can use wkbk.Sheets(1).Range("3:3")
(or whatever you need)
You can use df.loc[i]
, where the row with index i
will be what you specify it to be in the dataframe.
>>> import pandas as pd
>>> from numpy.random import randint
>>> df = pd.DataFrame(columns=['lib', 'qty1', 'qty2'])
>>> for i in range(5):
>>> df.loc[i] = ['name' + str(i)] + list(randint(10, size=2))
>>> df
lib qty1 qty2
0 name0 3 3
1 name1 2 4
2 name2 2 8
3 name3 2 1
4 name4 9 6
For me it was using {{ }} instead of {% %}:
href="{{ static 'bootstrap.min.css' }}" # wrong
href="{% static 'bootstrap.min.css' %}" # right
Create custom alert layout custom_aler_update.xml
Then Copy this code to Activity :
AlertDialog basic_reg;
AlertDialog.Builder builder ;
builder = new AlertDialog.Builder(ct, R.style.AppCompatAlertDialogStyle);
LayoutInflater inflater = ((Activity) ct).getLayoutInflater();
View v = inflater.inflate(R.layout.custom_aler_update, null);
builder.setView(v);
builder.setCancelable(false);
builder.create();
basic_reg = builder.show();
Copy this code to style :
<style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="colorAccent">@color/colorAccent</item>
<item name="android:textColorPrimary">@color/primaryTextColor</item>
<item name="android:background">@color/white</item>
</style>
It is for optimization reasons.
range() will create a list of values from start to end (0 .. 20 in your example). This will become an expensive operation on very large ranges.
xrange() on the other hand is much more optimised. it will only compute the next value when needed (via an xrange sequence object) and does not create a list of all values like range() does.
This will definitely work for you...
ArrayList<String> list = new ArrayList<String>();
list.add(textview.getText().toString());
list.add("B");
list.add("C");
Based on the answer of Stephen Cagle I added support for nested test modules.
import fnmatch
import os
import unittest
def all_test_modules(root_dir, pattern):
test_file_names = all_files_in(root_dir, pattern)
return [path_to_module(str) for str in test_file_names]
def all_files_in(root_dir, pattern):
matches = []
for root, dirnames, filenames in os.walk(root_dir):
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename))
return matches
def path_to_module(py_file):
return strip_leading_dots( \
replace_slash_by_dot( \
strip_extension(py_file)))
def strip_extension(py_file):
return py_file[0:len(py_file) - len('.py')]
def replace_slash_by_dot(str):
return str.replace('\\', '.').replace('/', '.')
def strip_leading_dots(str):
while str.startswith('.'):
str = str[1:len(str)]
return str
module_names = all_test_modules('.', '*Tests.py')
suites = [unittest.defaultTestLoader.loadTestsFromName(mname) for mname
in module_names]
testSuite = unittest.TestSuite(suites)
runner = unittest.TextTestRunner(verbosity=1)
runner.run(testSuite)
The code searches all subdirectories of .
for *Tests.py
files which are then loaded. It expects each *Tests.py
to contain a single class *Tests(unittest.TestCase)
which is loaded in turn and executed one after another.
This works with arbitrary deep nesting of directories/modules, but each directory in between needs to contain an empty __init__.py
file at least. This allows the test to load the nested modules by replacing slashes (or backslashes) by dots (see replace_slash_by_dot
).
You can check if index exist or not exist, in order to append +1 to it.
this way you don't need a zeros filled array.
EXAMPLE:
var current_year = new Date().getFullYear();
var ages_array = new Array();
for (var i in data) {
if(data[i]['BirthDate'] != null && data[i]['BirthDate'] != '0000-00-00'){
var birth = new Date(data[i]['BirthDate']);
var birth_year = birth.getFullYear();
var age = current_year - birth_year;
if(ages_array[age] == null){
ages_array[age] = 1;
}else{
ages_array[age] += 1;
}
}
}
console.log(ages_array);
For convenience, you can create a wrapper class around ResultSet that returns null values when ResultSet
ordinarily would not.
public final class ResultSetWrapper {
private final ResultSet rs;
public ResultSetWrapper(ResultSet rs) {
this.rs = rs;
}
public ResultSet getResultSet() {
return rs;
}
public Boolean getBoolean(String label) throws SQLException {
final boolean b = rs.getBoolean(label);
if (rs.wasNull()) {
return null;
}
return b;
}
public Byte getByte(String label) throws SQLException {
final byte b = rs.getByte(label);
if (rs.wasNull()) {
return null;
}
return b;
}
// ...
}
If you already have it checked out locally then you can cd
to where it is checked out, then use this syntax:
$ svn up -rXXXX
ref: Checkout a specific revision from subversion from command line
Let take a string like :
XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
Note: Underscore ( _ ) is not considered a special character in this case.
/\bX\b/g
Should begin and end with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/\bX/g
Should begin with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/X\b/g
Should end with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/\BX\B/g
XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/\BX/g
Should not begin with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/X\B/g
Should not end with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/\bX\B/g
Should begin and not end with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
/\BX\b/g
Should not begin and should end with a special character or white SpaceXIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-
As Kris mentions, you can use the $resource
service to interact with the server, but I get the impression you are beginning your journey with Angular - I was there last week - so I recommend to start experimenting directly with the $http
service. In this case you can call its get
method.
If you have the following JSON
[{ "text":"learn angular", "done":true },
{ "text":"build an angular app", "done":false},
{ "text":"something", "done":false },
{ "text":"another todo", "done":true }]
You can load it like this
var App = angular.module('App', []);
App.controller('TodoCtrl', function($scope, $http) {
$http.get('todos.json')
.then(function(res){
$scope.todos = res.data;
});
});
The get
method returns a promise object which
first argument is a success callback and the second an error
callback.
When you add $http
as a parameter of a function Angular does it magic
and injects the $http
resource into your controller.
I've put some examples here
UPDATE: The following explanation is for one Android Studio project, with one Firebase Project and different Firebase Apps inside that project. If the aim is to have different JSON files for different Firebase Apps in different Firebase Projects inside the same Android Studio project, (or if you don't know what's the difference) look here..
You need one Firebase App per Android Application ID (usually package name). Is common to have one Application ID per Gradle build variant (This is gonna be likely if you use Gradle build types and Gradle build flavours)
As of Google Services 3.0 and using Firebase it's not necessary to create different files for different flavours. Creating different files for different flavours can be not clear or straightforward in case you have productFlavours and Build types which compose with each other.
In the same file you'll have the all the configurations you need for all your build types and flavours.
In the Firebase console you need to add one app per package name. Imagine that you have 2 flavours (dev and live) and 2 build types (debug and release). Depending on your config but it's likely that you have 4 different package names like:
You need 4 different Android Apps in the Firebase Console. (On each one you need to add the SHA-1 for debug and live for each computer you are using)
When you download the google-services.json file, actually it doesn't really matter from what app you download it, all of them contain the same info related to all your apps.
Now you need to locate this file in app level (app/).
If you open that file you'll see that if contains all the information for all your package names.
A pain point use to be the plugin. In order to get it working you need to locate the plugin at the bottom of your file. So this line..
apply plugin: 'com.google.gms.google-services'
...needs to be on the bottom of your app build.gradle file.
For most of the said here, it applies to previous versions as well. I've never had different files for different configs, but now with the Firebase console is easier because they provide one single file with everything you need for all you configs.
From the jquery docs for POST (3rd example):
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
<script>
$(document).ready(function () {
var msg = '@ViewBag.ErrorMessage'
if (msg.length > 0)
OnFailure('Register', msg);
});
function OnSuccess(header,Message) {
$("#Message_Header").text(header);
$("#Message_Text").text(Message);
$('#MessageDialog').modal('show');
}
function OnFailure(header,error)
{
$("#Message_Header").text(header);
$("#Message_Text").text(error);
$('#MessageDialog').modal('show');
}
</script>
As I saw that in Android Studio 0.5.1, you have to close your project by doing simply File -> Close Project then move your mouse over the project which you want to delete then keep your mouse on the same project and press delete then click on "OK" button that would delete your project from Android Studio.
The documentation says that the date
method returns a new date set to the current date and time regardless of the language used.
The issue probably sits somewhere where you present the date using NSDateFormatter
. NSDate
is just a point on a time line. There is no time zones when talking about NSDate
. I made a test.
print(NSDate())
Output: 2014-07-23 17:56:45 +0000
NSLog(@"%@", [NSDate date]);
Output: 2014-07-23 17:58:15 +0000
Result - No difference.
I had the same problem but none of all those solutions worked for me. After further investigation, I found out that an undesired import was in one of my component.
I use setTimeout
function in app.component but for any reason Visual Studio added import { setTimeout } from 'timer';
where it was not needed. Removing this line fixed the issue.
So remember to check your imports before going further. Hope it may help someone.
This is simple program showing append('t') to the list.
n=['f','g','h','i','k']
for i in range(1):
temp=[]
temp.append(n[-2:])
temp.append('t')
print(temp)
Output: [['i', 'k'], 't']
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here
After validation and before INSERT check if username already exists, using mysqli(procedural). This works:
//check if username already exists
include 'phpscript/connect.php'; //connect to your database
$sql = "SELECT username FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$usernameErr = "username already taken"; //takes'em back to form
} else { // go on to INSERT new record
You need to give the WebClient object the credentials. Something like this...
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
There are only two ways to find a web page: through a link or by listing the directory.
Usually, web servers disable directory listing, so if there is really no link to the page, then it cannot be found.
BUT: information about the page may get out in ways you don't expect. For example, if a user with Google Toolbar visits your page, then Google may know about the page, and it can appear in its index. That will be a link to your page.
In my case, I was using ExpandableListView and I had set android:transcriptMode="normal"
. This was causing few children in expandable group to disappear and I used to get NULL exception when ever I used scroll the list.
CREATE TABLE #t
Creates a table that is only visible on and during that CONNECTION the same user who creates another connection will not be able to see table #t from the other connection.
CREATE TABLE ##t
Creates a temporary table visible to other connections. But the table is dropped when the creating connection is ended.
Download the ZIP file from this URL and extract it to get the Jar. Add the Jar to your build path. To check the available classes in this Jar use this URL.
To Add this Jar to your build path Right click the Project > Build Path > Configure build path> Select Libraries tab > Click Add External Libraries > Select the Jar file Download
I hope this will solve your problem
The present solution produces the same flow as your OP. It does not use Labels, but this was not a requirement of the OP. You only asked for "a simple conditional loop that will go to the next iteration if a condition is true", and since this is cleaner to read, it is likely a better option than that using a Label.
What you want inside your for
loop follows the pattern
If (your condition) Then
'Do something
End If
In this case, your condition is Not(Return = 0 And Level = 0)
, so you would use
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If (Not(Return = 0 And Level = 0)) Then
'Do something
End If
Next i
PS: the condition is equivalent to (Return <> 0 Or Level <> 0)
It's because $bar is a public property.
$foo->bar = 'test';
There is no need to call the magic method when running the above.
Deleting public $bar;
from your class should correct this.
You can use the HTMLOptionsCollection.namedItem() That means that you have to define your select options to have a name attribute and have the value of the displayed text. e.g California
In your angular.json folder structure should be like this
"assets": [
"src/assets",
"src/favicon.ico"
],
not this
"assets": [
"src/favicon.ico",
"src/assets",
],
This solved my problem.
Well you could either add <a></a>
tags and place the div inside it, adding an href if you want the div to act as a link. Or else just use Javascript and define an 'OnClick' function. But from the limited information provided, it's a bit hard to determine what the context of your problem is.
x & 1
is equivalent to x % 2
.
x >> 1
is equivalent to x / 2
So, these things are basically the result and remainder of divide by two.
I resolved this problem, searching the dll's file in C:\Windows\assembly\GAC_MSIL\ and copied to bin directory of the proyect deployed. That work for me.
try this code
input[type="checkbox"] {
-moz-appearance: checkbox;
-webkit-appearance: checkbox;
margin-left:3px;
border:0;
vertical-align: middle;
top: -1px;
bottom: 1px;
*overflow: hidden;
box-sizing: border-box; /* 1 */
*height: 13px; /* Removes excess padding in IE 7 */
*width: 13px;
background: #fff;
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>teste4</groupId>
<artifactId>teste4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>bootstrap</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.7.Final</version>
</dependency>
</dependencies>
</project>
I wanted a pure html approach as I wanted to collapse and expand html that was added on the fly via a template! I came up with this...
https://jsfiddle.net/3mguht2y/1/
var noJavascript = ":)";
Which might be of use to someone :)
You may wonder, why the syntax is valid (but not working as expected):
var func = p => { foo: "bar" }
It's because of JavaScript's label syntax:
So if you transpile the above code to ES5, it should look like:
var func = function (p) {
foo:
"bar"; //obviously no return here!
}
REST is very abstract. It helps to have some good, simple, real-world examples.
Take for example all major social media apps -- Tumblr, Instagram, Facebook, and Twitter. They all have a forever-scrolling view where the farther you scroll down, the more content you see, further and further back in time. However, we've all experienced that moment where you lose where you were scrolled to, and the app resets you back to the top. Like if you quit the app, then when you reopen it, you're back at the top again.
The reason why, is because the server did not store your session state. Sadly, your scroll position was just stored in RAM on the client.
Fortunately you don't have to log back in when you reconnect, but that's only because your client-side also stored login certificate has not expired. Delete and reinstall the app, and you're going to have to log back in, because the server did not associate your IP address with your session.
You don't have a login session on the server, because they abide by REST.
Now the above examples don't involve a web browser at all, but on the back end, the apps are communicating via HTTPS with their host servers. My point is that REST does not have to involve cookies and browsers etc. There are various means of storing client-side session state.
But lets talk about web browsers for a second, because that brings up another major advantage of REST that nobody here is talking about.
If the server tried to store session state, how is it supposed to identify each individual client?
It could not use their IP address, because many people could be using that same address on a shared router. So how, then?
It can't use MAC address for many reasons, not the least of which because you can be logged into multiple different Facebook accounts simultaneously on different browsers plus the app. One browser can easily pretend to be another one, and MAC addresses are just as easy to spoof.
If the server has to store some client-side state to identify you, it has to store it in RAM longer than just the time it takes to process your requests, or else it has to cache that data. Servers have limited amounts of RAM and cache, not to mention processor speed. Server-side state adds to all three, exponentially. Plus if the server is going to store any state about your sessions then it has to store it separately for each browser and app you're currently logged in with, and also for each different device you use.
So... I hope that you see now why REST is so important for scalability. I hope you can start to see why server-side session state is to server scalability what welded-on anvils are to car acceleration.
Where people get confused is by thinking that "state" refers to, like, information stored in a database. No, it refers to any information that needs to be in the RAM of the server when you're using it.
What actually worked for me was setting ResponseCache on my Main class:
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) { }
and
connection.setUseCaches(true);
when downloading bitmap.
http://practicaldroid.blogspot.com/2013/01/utilizing-http-response-cache.html
Simply, the "Real Time" priority class is higher than "High" priority class. I don't think there's much more to it than that. Oh yeah - you have to have the SeIncreaseBasePriorityPrivilege
to put a thread into the Real Time class.
Windows will sometimes boost the priority of a thread for various reasons, but it won't boost the priority of a thread into another priority class. It also won't boost the priority of threads in the real-time priority class. So a High priority thread won't get any automatic temporary boost into the Real Time priority class.
Russinovich's "Inside Windows" chapter on how Windows handles priorities is a great resource for learning how this works:
Note that there's absolutely no problem with a thread having a Real-time priority on a normal Windows system - they aren't necessarily for special processes running on dedicatd machines. I imagine that multimedia drivers and/or processes might need threads with a real-time priority. However, such a thread should not require much CPU - it should be blocking most of the time in order for normal system events to get processing.
What is the basic problem in your code?
Your code needs to be separated out in to interfaces(.h) and Implementations(.cpp).
The compiler needs to see the composition of a type when you write something like
ClassTwo obj;
This is because the compiler needs to reserve enough memory for object of type ClassTwo
to do so it needs to see the definition of ClassTwo
. The most common way to do this in C++ is to split your code in to header files and source files.
The class definitions go in the header file while the implementation of the class goes in to source files. This way one can easily include header files in to other source files which need to see the definition of class who's object they create.
Why can't I simply put all code in cpp files and include them in other files?
You cannot simple put all the code in source file and then include that source file in other files.C++ standard mandates that you can declare a entity as many times as you need but you can define it only once(One Definition Rule(ODR)). Including the source file would violate the ODR because a copy of the entity is created in every translation unit where the file is included.
How to solve this particular problem?
Your code should be organized as follows:
//File1.h
Define ClassOne
//File2.h
#include <iostream>
#include <string>
class ClassTwo
{
private:
string myType;
public:
void setType(string);
std::string getType();
};
//File1.cpp
#include"File1.h"
Implementation of ClassOne
//File2.cpp
#include"File2.h"
void ClassTwo::setType(std::string sType)
{
myType = sType;
}
void ClassTwo::getType(float fVal)
{
return myType;
}
//main.cpp
#include <iostream>
#include <string>
#include "file1.h"
#include "file2.h"
using namespace std;
int main()
{
ClassOne cone;
ClassTwo ctwo;
//some codes
}
Is there any alternative means rather than including header files?
If your code only needs to create pointers and not actual objects you might as well use Forward Declarations but note that using forward declarations adds some restrictions on how that type can be used because compiler sees that type as an Incomplete type.
Pay attention, there is a bug with Jquery 1.8.0, $(window).height() returns the all document height !
HTML:
<input type="text" name="name" placeholder="enter your text" id="myInput" />
jQuery:
$('#myInput').focus(function(){
$(this).attr('placeholder','');
});
$('#myInput').focusout(function(){
$(this).attr('placeholder','enter your text');
});
target="_blank"
attribute will do the job.
Just don't forget to add rel="noopener noreferrer"
to solve the potential vulnerability. More on that here: https://dev.to/ben/the-targetblank-vulnerability-by-example
<a href="https://www.google.com/" target="_blank" rel="noopener noreferrer">Searcher</a>
Do it the jQuery way (and fix the errors):
$('#stop').click(function() {
$('#next').click(stopMoving);
// ^-- missing #
}); // <-- missing );
If the element already has a click
handler attached via the onclick
attribute, you have to remove it:
$('#next').attr('onclick', '');
Update: As @Drackir pointed out, you might also have to call $('#next').unbind('click');
in order to remove other click handlers attached via jQuery.
But this is guessing here. As always: More information => better answers.
Are you after something like this:
<html>
<head>
<title>Z Test</title>
</head>
<body>
<div id="img_home"></div>
<button onclick="addimage()" type="button">Add an image</button>
<script>
function addimage() {
var img = new Image();
img.src = "https://www.google.com/images/srpr/logo4w.png"
img_home.appendChild(img);
}
</script>
</body>
Another approach for your review with reduce func:
function mergeDistinct(arResult, candidate){
if (-1 == arResult.indexOf(candidate)) {
arResult.push(candidate);
}
return arResult;
}
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
var arMerge = [];
arMerge = array1.reduce(mergeDistinct, arMerge);
arMerge = array2.reduce(mergeDistinct, arMerge);//["Vijendra","Singh","Shakya"];
It's hard to answer you without the HTML, but in general you can put:
style="width: 50%;"
On either the table cell, or place a div inside the table cell, and put the style on that.
But one problem is "50% of what?" It's 50% of the parent element which may not be what you want.
Post a copy of your HTML and maybe you'll get a better answer.
Not really, no.
Java doesn't have pointers. If you really wanted you could try to emulate them by building around something like reflection, but it would have all of the complexity of pointers with none of the benefits.
Java doesn't have pointers because it doesn't need them. What kind of answers were you hoping for from this question, i.e. deep down did you hope you could use them for something or was this just curiousity?
size_t should be defined in your standard library's headers. In my experience, it usually is simply a typedef to unsigned int. The point, though, is that it doesn't have to be. Types like size_t allow the standard library vendor the freedom to change its underlying data types if appropriate for the platform. If you assume size_t is always unsigned int (via casting, etc), you could run into problems in the future if your vendor changes size_t to be e.g. a 64-bit type. It is dangerous to assume anything about this or any other library type for this reason.
if you have GNU date and i understood you correctly
$ date +%Y:%m:%d -d "yesterday"
2009:11:09
or
$ date +%Y:%m:%d -d "1 day ago"
2009:11:09
I got the same trouble since nearly release, seem must use KUBECONFIG explicit
sudo cp /etc/kubernetes/admin.conf $HOME/
sudo chown $(id -u):$(id -g) $HOME/admin.conf
export KUBECONFIG=$HOME/admin.conf
After several hours of test and research over the Internet, I've finally found how to start my PowerShell script with task scheduler, thanks to the video Scheduling a PowerShell Script using Windows Task Scheduler by Jack Fruh @sharepointjack.
Program/script -> put full path through powershell.exe
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe
Add arguments -> Full path to the script, and the script, without any " ".
Start in (optional) -> The directory where your script resides, without any " ".
Git — The version control tool that GitHub is built on top of.
GitHub — Our company and the name of our software. We build software and websites to help you interact with Git repositories in a nice way.
GitHub.com — The website you log into to view repositories online.
GitHub Desktop — An application that you can install on your computer to help you synchronize local code with GitHub.com.
source: https://guides.github.com/introduction/getting-your-project-on-github/
With pure JavaScript you can do this (such as SQL) and anything you need, basically:
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
<input type='button' value='F3' class="c2" id="btn_1">_x000D_
<input type='button' value='F3' class="c3" id="btn_2">_x000D_
<input type='button' value='F1' class="c2" id="btn_3">_x000D_
_x000D_
<input type='submit' value='F2' class="c1" id="btn_4">_x000D_
<input type='submit' value='F1' class="c3" id="btn_5">_x000D_
<input type='submit' value='F2' class="c1" id="btn_6">_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<script>_x000D_
function myFunction() _x000D_
{_x000D_
var arrFiltered = document.querySelectorAll('input[value=F2][type=submit][class=c1]');_x000D_
_x000D_
arrFiltered.forEach(function (el)_x000D_
{ _x000D_
var node = document.createElement("p");_x000D_
_x000D_
node.innerHTML = el.getAttribute('id');_x000D_
_x000D_
window.document.body.appendChild(node);_x000D_
});_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
If you want to use the reset_index
method and also preserve your existing index you should use:
df.reset_index().set_index('index', drop=False)
or to change it in place:
df.reset_index(inplace=True)
df.set_index('index', drop=False, inplace=True)
For example:
print(df)
gi ptt_loc
0 384444683 593
4 384444684 594
9 384444686 596
print(df.reset_index())
index gi ptt_loc
0 0 384444683 593
1 4 384444684 594
2 9 384444686 596
print(df.reset_index().set_index('index', drop=False))
index gi ptt_loc
index
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
And if you want to get rid of the index label you can do:
df2 = df.reset_index().set_index('index', drop=False)
df2.index.name = None
print(df2)
index gi ptt_loc
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.
The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.
With an appropriate predicate in hand, problem 1 simplifies to:
low_primes = {x for x in range(1, 100) if is_prime(x)}
And problem 2 simplifies to:
low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}
Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."
P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.
function update() {
$("#notice_div").html('Loading..');
$.ajax({
type: 'GET',
url: 'jbede.php',
timeout: 2000,
success: function(data) {
$("#some_div").html(data);
$("#notice_div").html('');
window.setTimeout(update, 10000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
});
}
$(document).ready(function() {
update();
});
This is Better Code
Test for ':' first, then take test string up to ':' or end, depending on if it was found
Dim strResult As String
' Position of :
intPos = InStr(1, strTest, ":")
If intPos > 0 Then
' : found, so take up to :
strResult = Left(strTest, intPos - 1)
Else
' : not found, so take whole string
strResult = strTest
End If
For total columns information use below syntax : Use "DBName" go Exec SP_Columns "TableName"
For total table information use below syntax : Use "DBName" go Exec SP_help "Table Name"
If you downloaded mySQL using a DMG (easiest way to download found here http://dev.mysql.com/downloads/mysql/) in Terminal try: cd /usr/local/
When you type ls
you should see mysql-YOUR-VERSION. You will also see mysql which is the installation directory.
Say you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath while compiling you need to do
$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java
To run do
$java -cp .:a.jar:b.jar:c.jar HelloWorld
Just want to share what worked on my end, in case it would be able to help someone else too. Alternatively based on Paty Lustosa's answer above, please allow me to add another approach derived from this site where he used an ajax approach for the source method
http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3
The kicker is the resulting "string" or json format from your php script (listing.php below) that derives the result set to be shown in the autocomplete field should follow something like this:
{"list":[
{"value": 1, "label": "abc"},
{"value": 2, "label": "def"},
{"value": 3, "label": "ghi"}
]}
Then on the source portion of the autocomplete method:
source: function(request, response) {
$.getJSON("listing.php", {
term: request.term
}, function(data) {
var array = data.error ? [] : $.map(data.list, function(m) {
return {
label: m.label,
value: m.value
};
});
response(array);
});
},
select: function (event, ui) {
$("#autocomplete_field").val(ui.item.label); // display the selected text
$("#field_id").val(ui.item.value); // save selected id to hidden input
return false;
}
Hope this helps... all the best!
If INSERTS
are rare, I would avoid doing a NOT EXISTS (...)
since it emits a SELECT
on all updates. Instead, take a look at wildpeaks answer: https://dba.stackexchange.com/questions/5815/how-can-i-insert-if-key-not-exist-with-postgresql
CREATE OR REPLACE FUNCTION upsert_tableName(arg1 type, arg2 type) RETURNS VOID AS $$
DECLARE
BEGIN
UPDATE tableName SET col1 = value WHERE colX = arg1 and colY = arg2;
IF NOT FOUND THEN
INSERT INTO tableName values (value, arg1, arg2);
END IF;
END;
$$ LANGUAGE 'plpgsql';
This way Postgres will initially try to do a UPDATE
. If no rows was affected, it will fall back to emitting an INSERT
.
You have to create your own log4j.properties
in the classpath folder.
"set -e
" is probably the easiest way to do this. Just put that before any commands in your program.
I suggest
if (checkbox.IsChecked == true)
{
//do something
}
Hope it's helpful ^^
Just a thought, but you may check the influence of a ulimit -v
option.
That is not an actual solution since it would limit address space available for all process, but that would allow you to check the behavior of your application with a limited virtual memory.
@Gumbo adding extra answer - user.email.replace(/foo/gi,"bar");
/foo/g - Refers to the all string to replace matching the case sensitive
/foo/gi - Refers to the without case sensitive and replace all For Eg: (Foo, foo, FoO, fOO)
Since you ask for other better ways to handle the problem, here's another way using data.table
:
require(data.table) ## 1.9.2+
setDT(df)
df[a %in% c(0,1,3,4) | c == 4, g := 3L]
df[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
Note the order of conditional statements is reversed to get g
correctly. There's no copy of g
made, even during the second assignment - it's replaced in-place.
On larger data this would have better performance than using nested if-else
, as it can evaluate both 'yes' and 'no' cases, and nesting can get harder to read/maintain IMHO.
Here's a benchmark on relatively bigger data:
# R version 3.1.0
require(data.table) ## 1.9.2
require(dplyr)
DT <- setDT(lapply(1:6, function(x) sample(7, 1e7, TRUE)))
setnames(DT, letters[1:6])
# > dim(DT)
# [1] 10000000 6
DF <- as.data.frame(DT)
DT_fun <- function(DT) {
DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}
DPLYR_fun <- function(DF) {
mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L,
ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}
BASE_fun <- function(DF) { # R v3.1.0
transform(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L,
ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}
system.time(ans1 <- DT_fun(DT))
# user system elapsed
# 2.659 0.420 3.107
system.time(ans2 <- DPLYR_fun(DF))
# user system elapsed
# 11.822 1.075 12.976
system.time(ans3 <- BASE_fun(DF))
# user system elapsed
# 11.676 1.530 13.319
identical(as.data.frame(ans1), as.data.frame(ans2))
# [1] TRUE
identical(as.data.frame(ans1), as.data.frame(ans3))
# [1] TRUE
Not sure if this is an alternative you'd asked for, but I hope it helps.
Change 2 to 1 as the first parameter in the splice call when removing the element:
var tmp = playlist.splice(1, 1);
playlist.splice(2, 0, tmp[0]);
If you are using a map()
operator on your response,you could maybe chain a toArray()
operator to it...then you should be able to iterate through newly created array...at least that worked for me :)
It's probably easiest to create your query object directly as:
Test.find({
$and: [
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
]
}, function (err, results) {
...
}
But you can also use the Query#and
helper that's available in recent 3.x Mongoose releases:
Test.find()
.and([
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
])
.exec(function (err, results) {
...
});
I think you should not consider any specific parser implementation. Java API for XML Processing lets you use any conforming parser implementation in a standard way. The code should be much more portable, and when you realise that a specific parser has grown too old, you can replace it with another without changing a line of your code (if you do it correctly).
Basically there are three ways of handling XML in a standard way:
Forget about proprietary APIs such as JDOM or Apache ones (i.e. Apache Xerces XMLSerializer) because will tie you to a specific implementation that can evolve in time or lose backwards compatibility, which will make you change your code in the future when you want to upgrade to a new version of JDOM or whatever parser you use. If you stick to Java standard API (using factories and interfaces) your code will be much more modular and maintainable.
There is no need to say that all (I haven't checked all, but I'm almost sure) of the parsers proposed comply with a JAXP implementation so technically you can use all, no matter which.
SQL JOIN
?SQL JOIN
is a method to retrieve data from two or more database tables.
SQL JOIN
s ?There are a total of five JOIN
s. They are :
1. JOIN or INNER JOIN
2. OUTER JOIN
2.1 LEFT OUTER JOIN or LEFT JOIN
2.2 RIGHT OUTER JOIN or RIGHT JOIN
2.3 FULL OUTER JOIN or FULL JOIN
3. NATURAL JOIN
4. CROSS JOIN
5. SELF JOIN
In this kind of a JOIN
, we get all records that match the condition in both tables, and records in both tables that do not match are not reported.
In other words, INNER JOIN
is based on the single fact that: ONLY the matching entries in BOTH the tables SHOULD be listed.
Note that a JOIN
without any other JOIN
keywords (like INNER
, OUTER
, LEFT
, etc) is an INNER JOIN
. In other words, JOIN
is
a Syntactic sugar for INNER JOIN
(see: Difference between JOIN and INNER JOIN).
OUTER JOIN
retrieves
Either, the matched rows from one table and all rows in the other table Or, all rows in all tables (it doesn't matter whether or not there is a match).
There are three kinds of Outer Join :
2.1 LEFT OUTER JOIN or LEFT JOIN
This join returns all the rows from the left table in conjunction with the matching rows from the
right table. If there are no columns matching in the right table, it returns NULL
values.
2.2 RIGHT OUTER JOIN or RIGHT JOIN
This JOIN
returns all the rows from the right table in conjunction with the matching rows from the
left table. If there are no columns matching in the left table, it returns NULL
values.
2.3 FULL OUTER JOIN or FULL JOIN
This JOIN
combines LEFT OUTER JOIN
and RIGHT OUTER JOIN
. It returns rows from either table when the conditions are met and returns NULL
value when there is no match.
In other words, OUTER JOIN
is based on the fact that: ONLY the matching entries in ONE OF the tables (RIGHT or LEFT) or BOTH of the tables(FULL) SHOULD be listed.
Note that `OUTER JOIN` is a loosened form of `INNER JOIN`.
It is based on the two conditions :
JOIN
is made on all the columns with the same name for equality.This seems to be more of theoretical in nature and as a result (probably) most DBMS don't even bother supporting this.
It is the Cartesian product of the two tables involved. The result of a CROSS JOIN
will not make sense
in most of the situations. Moreover, we won't need this at all (or needs the least, to be precise).
It is not a different form of JOIN
, rather it is a JOIN
(INNER
, OUTER
, etc) of a table to itself.
Depending on the operator used for a JOIN
clause, there can be two types of JOIN
s. They are
For whatever JOIN
type (INNER
, OUTER
, etc), if we use ONLY the equality operator (=), then we say that
the JOIN
is an EQUI JOIN
.
This is same as EQUI JOIN
but it allows all other operators like >, <, >= etc.
Many consider both
EQUI JOIN
and ThetaJOIN
similar toINNER
,OUTER
etcJOIN
s. But I strongly believe that its a mistake and makes the ideas vague. BecauseINNER JOIN
,OUTER JOIN
etc are all connected with the tables and their data whereasEQUI JOIN
andTHETA JOIN
are only connected with the operators we use in the former.Again, there are many who consider
NATURAL JOIN
as some sort of "peculiar"EQUI JOIN
. In fact, it is true, because of the first condition I mentioned forNATURAL JOIN
. However, we don't have to restrict that simply toNATURAL JOIN
s alone.INNER JOIN
s,OUTER JOIN
s etc could be anEQUI JOIN
too.
Simply use Object.keys()
:
var driversCounter = {_x000D_
"one": 1,_x000D_
"two": 2,_x000D_
"three": 3,_x000D_
"four": 4,_x000D_
"five": 5_x000D_
}_x000D_
console.log(Object.keys(driversCounter));
_x000D_
This is now IsEnabled
takePicturebutton.IsEnabled = false; // true
This website has a concise tutorial on how to use SQL Server Management Studio. As you will see you can open a "Query Window", paste your script and run it. It does not allow you to execute scripts by using the file path. However, you can do this easily by using the command line (cmd.exe):
sqlcmd -S .\SQLExpress -i SqlScript.sql
Where SqlScript.sql
is the script file name located at the current directory. See this Microsoft page for more examples
Simply pass latitude, longitude and your Google API Key to the following query string, you will get a json array, fetch your city from there.
https://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&key=YOUR_API_KEY
Note: Ensure that no space exists between the latitude and longitude values when passed in the latlng parameter.
Try Java Web Launcher, rather than Java Web Start Launcher. It worked for me.
Did you try using double-quotes? Regardless, no one in 2011 should be limited by the native VB6 shell command. Here's a function that uses ShellExecuteEx, much more versatile.
Option Explicit
Private Const SEE_MASK_DEFAULT = &H0
Public Enum EShellShowConstants
essSW_HIDE = 0
essSW_SHOWNORMAL = 1
essSW_SHOWMINIMIZED = 2
essSW_MAXIMIZE = 3
essSW_SHOWMAXIMIZED = 3
essSW_SHOWNOACTIVATE = 4
essSW_SHOW = 5
essSW_MINIMIZE = 6
essSW_SHOWMINNOACTIVE = 7
essSW_SHOWNA = 8
essSW_RESTORE = 9
essSW_SHOWDEFAULT = 10
End Enum
Private Type SHELLEXECUTEINFO
cbSize As Long
fMask As Long
hwnd As Long
lpVerb As String
lpFile As String
lpParameters As String
lpDirectory As String
nShow As Long
hInstApp As Long
lpIDList As Long 'Optional
lpClass As String 'Optional
hkeyClass As Long 'Optional
dwHotKey As Long 'Optional
hIcon As Long 'Optional
hProcess As Long 'Optional
End Type
Private Declare Function ShellExecuteEx Lib "shell32.dll" Alias "ShellExecuteExA" (lpSEI As SHELLEXECUTEINFO) As Long
Public Function ExecuteProcess(ByVal FilePath As String, ByVal hWndOwner As Long, ShellShowType As EShellShowConstants, Optional EXEParameters As String = "", Optional LaunchElevated As Boolean = False) As Boolean
Dim SEI As SHELLEXECUTEINFO
On Error GoTo Err
'Fill the SEI structure
With SEI
.cbSize = Len(SEI) ' Bytes of the structure
.fMask = SEE_MASK_DEFAULT ' Check MSDN for more info on Mask
.lpFile = FilePath ' Program Path
.nShow = ShellShowType ' How the program will be displayed
.lpDirectory = PathGetFolder(FilePath)
.lpParameters = EXEParameters ' Each parameter must be separated by space. If the lpFile member specifies a document file, lpParameters should be NULL.
.hwnd = hWndOwner ' Owner window handle
' Determine launch type (would recommend checking for Vista or greater here also)
If LaunchElevated = True Then ' And m_OpSys.IsVistaOrGreater = True
.lpVerb = "runas"
Else
.lpVerb = "Open"
End If
End With
ExecuteProcess = ShellExecuteEx(SEI) ' Execute the program, return success or failure
Exit Function
Err:
' TODO: Log Error
ExecuteProcess = False
End Function
Private Function PathGetFolder(psPath As String) As String
On Error Resume Next
Dim lPos As Long
lPos = InStrRev(psPath, "\")
PathGetFolder = Left$(psPath, lPos - 1)
End Function
When you get a connection to PostgreSQL
it is always to a particular database. To access a different database, you must get a new connection.
Using \c
in psql closes the old connection and acquires a new one, using the specified database and/or credentials. You get a whole new back-end process and everything.
The existing answers explain the problem well but if including your script files using or before requireJS is not an easy option due to legacy code a slightly hacky workaround is to remove require from the window scope before your script tag and then reinstate it afterwords. In our project this is wrapped behind a server-side function call but effectively the browser sees the following:
<script>
window.__define = window.define;
window.__require = window.require;
window.define = undefined;
window.require = undefined;
</script>
<script src="your-script-file.js"></script>
<script>
window.define = window.__define;
window.require = window.__require;
window.__define = undefined;
window.__require = undefined;
</script>
Not the neatest but seems to work and has saved a lot of refractoring.
Async means asynchronous and you should use that most of the time. You should never call sync on main thread cause it will lock up your UI until the task is completed. You Here is a better way to do this in Swift:
runThisInMainThread { () -> Void in
// Run your code like this:
self.doStuff()
}
func runThisInMainThread(block: dispatch_block_t) {
dispatch_async(dispatch_get_main_queue(), block)
}
Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions
If you just need to search for one string within another, use the index
function (or rindex
if you want to start scanning from the end of the string):
if (index($string, $substring) != -1) {
print "'$string' contains '$substring'\n";
}
To search a string for a pattern match, use the match operator m//
:
if ($string =~ m/pattern/) {
print "'$string' matches the pattern\n";
}