Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
In the first case you are declaring "int a" as a local variable(as declared inside a method) and local varible do not get default value.
But instance variable are given default value both for static and non-static.
Default value for instance variable:
int = 0
float,double = 0.0
reference variable = null
char = 0 (space character)
boolean = false
What you're doing here is simply reading and writing to memory that used to be the address of a
. Now that you're outside of foo
, it's just a pointer to some random memory area. It just so happens that in your example, that memory area does exist and nothing else is using it at the moment. You don't break anything by continuing to use it, and nothing else has overwritten it yet. Therefore, the 5
is still there. In a real program, that memory would be re-used almost immediately and you'd break something by doing this (though the symptoms may not appear until much later!)
When you return from foo
, you tell the OS that you're no longer using that memory and it can be reassigned to something else. If you're lucky and it never does get reassigned, and the OS doesn't catch you using it again, then you'll get away with the lie. Chances are though you'll end up writing over whatever else ends up with that address.
Now if you're wondering why the compiler doesn't complain, it's probably because foo
got eliminated by optimization. It usually will warn you about this sort of thing. C assumes you know what you're doing though, and technically you haven't violated scope here (there's no reference to a
itself outside of foo
), only memory access rules, which only triggers a warning rather than an error.
In short: this won't usually work, but sometimes will by chance.
Easier still: return a pointer to a string that's been malloc'd with strdup.
#include <ncurses.h>
char * getStr(int length)
{
char word[length];
for (int i = 0; i < length; i++)
{
word[i] = getch();
}
word[i] = '\0';
return strdup(&word[0]);
}
int main()
{
char wordd[10];
initscr();
*wordd = getStr(10);
printw("The string is:\n");
printw("%s\n",*wordd);
getch();
endwin();
return 0;
}
What's going wrong with what you have? What error do you get, or what result do or don't you get that doesn't match your expectations?
I can see the following issues with that SP, which may or may not relate to your problem:
)
after @BrandName
in your SELECT
(at the end)@CategoryID
or @BrandName
to anything anywhere (they're local variables, but you don't assign values to them)Edit Responding to your comment: The error is telling you that you haven't declared any parameters for the SP (and you haven't), but you called it with parameters. Based on your reply about @CategoryID
, I'm guessing you wanted it to be a parameter rather than a local variable. Try this:
CREATE PROCEDURE AddBrand
@BrandName nvarchar(50),
@CategoryID int
AS
BEGIN
DECLARE @BrandID int
SELECT @BrandID = BrandID FROM tblBrand WHERE BrandName = @BrandName
INSERT INTO tblBrandinCategory (CategoryID, BrandID) VALUES (@CategoryID, @BrandID)
END
You would then call this like this:
EXEC AddBrand 'Gucci', 23
...assuming the brand name was 'Gucci' and category ID was 23.
Scope in python follows this order:
Search the local scope
Search the scope of any enclosing functions
Search the global scope
Search the built-ins
(source)
Notice that if
and other looping/branching constructs are not listed - only classes, functions, and modules provide scope in Python, so anything declared in an if
block has the same scope as anything decleared outside the block. Variables aren't checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown.
def hi():
bye = 5
return bye
print hi()
This doesn't directly answer the question but can be very useful, especially if you want something like all the numeric columns except for your id column and dependent variable.
numeric_cols <- sapply(dataframe, is.numeric) %>% which %>%
names %>% setdiff(., c("id_variable", "dep_var"))
dataframe %<>% dplyr::mutate_at(numeric_cols, function(x) your_function(x))
The "directory where postgresql will keep all databases" (and configuration) is called "data directory" and corresponds to what PostgreSQL calls (a little confusingly) a "database cluster", which is not related to distributed computing, it just means a group of databases and related objects managed by a PostgreSQL server.
The location of the data directory depends on the distribution. If you install from source, the default is /usr/local/pgsql/data
:
In file system terms, a database cluster will be a single directory under which all data will be stored. We call this the data directory or data area. It is completely up to you where you choose to store your data. There is no default, although locations such as /usr/local/pgsql/data or /var/lib/pgsql/data are popular. (ref)
Besides, an instance of a running PostgreSQL server is associated to one cluster; the location of its data directory can be passed to the server daemon ("postmaster" or "postgres") in the -D
command line option, or by the PGDATA
environment variable (usually in the scope of the running user, typically postgres
). You can usually see the running server with something like this:
[root@server1 ~]# ps auxw | grep postgres | grep -- -D
postgres 1535 0.0 0.1 39768 1584 ? S May17 0:23 /usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data
Note that it is possible, though not very frequent, to run two instances of the same PostgreSQL server (same binaries, different processes) that serve different "clusters" (data directories). Of course, each instance would listen on its own TCP/IP port.
You can first find the position of the string in this case ":"
'position = InStr(StringToSearch, StringToFind)
position = InStr(StringToSearch, ":")
Then use Left(StringToCut, NumberOfCharacterToCut)
Result = Left(StringToSearch, position -1)
Just pass in the current Context to the Adapter constructor and store it as a field. Then inside the onClick you can use that context to call startActivity().
pseudo-code
public class MyAdapter extends Adapter {
private Context context;
public MyAdapter(Context context) {
this.context = context;
}
public View getView(...){
View v;
v.setOnClickListener(new OnClickListener() {
void onClick() {
context.startActivity(...);
}
});
}
}
Create a new class MyView, Which extends View
. Override the onDraw(Canvas canvas)
method to draw rectangle on Canvas
.
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
Paint paint;
Path path;
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawRect(30, 50, 200, 350, paint);
canvas.drawRect(100, 100, 300, 400, paint);
//drawRect(left, top, right, bottom, paint)
}
}
Then Move your Java activity to setContentView()
using our custom View, MyView.Call this way.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
For more details you can visit here
http://developer.android.com/reference/android/graphics/Canvas.html
Some of my dynamic SOAP requests have been getting out of control recently. With the uncompressed SOAP being about 14MB and compressed 3MB.
I noticed that in Fiddler when I compressed my request under Transformer
it came to about 470KB instead of the 3MB - so I figured there must be some way to get better compression.
Eventually found this very informative blog post
http://weblogs.asp.net/owscott/iis-7-compression-good-bad-how-much
I went ahead and ran this commnd (followed by iisreset):
C:\Windows\System32\Inetsrv\Appcmd.exe set config -section:httpCompression -[name='gzip'].staticCompressionLevel:9 -[name='gzip'].dynamicCompressionLevel:9
Changed dynamic level up to 9 and now my compressed soap matches what Fiddler gave me - and it about 1/7th the size of the existing compressed file.
Milage will vary, but for SOAP this is a massive massive improvement.
Swift 5/iOS 13
To change color of title in controller:
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
Not currently. It will be available in CSS 3, but it will take some time until it's implemented in most browsers.
The problem I had was related to SOAP version. The asmx
service was configured to accept both versions, 1.1 and 1.2, so, I think that when you are consuming the service, the client or the server doesn't know what version resolve.
To fix that, is necessary add:
using (wsWebService yourService = new wsWebService())
{
yourService.Url = "https://myUrlService.com/wsWebService.asmx?op=someOption";
yourService.UseDefaultCredentials = true; // this line depends on your authentication type
yourService.SoapVersion = SoapProtocolVersion.Soap11; // asign the version of SOAP
var result = yourService.SomeMethod("Parameter");
}
Where wsWebService
is the name of the class generated as a reference.
I just had this problem and I first switched to another directory and then switched back and the problem was fixed.
Just a little note - this approach:
Task<Customer> task = GetCustomers();
task.Wait()
works for WinRT.
Let me explain:
private void TestMethod()
{
Task<Customer> task = GetCustomers(); // call async method as sync and get task as result
task.Wait(); // wait executing the method
var customer = task.Result; // get's result.
Debug.WriteLine(customer.Name); //print customer name
}
public class Customer
{
public Customer()
{
new ManualResetEvent(false).WaitOne(TimeSpan.FromSeconds(5));//wait 5 second (long term operation)
}
public string Name { get; set; }
}
private Task<Customer> GetCustomers()
{
return Task.Run(() => new Customer
{
Name = "MyName"
});
}
Moreover this approach works for Windows Store solutions only!
Note: This way isn't thread safe if you call your method inside of other async method (according to comments of @Servy)
I followed the steps at https://www.w3schools.com/php/php_file_upload.asp and http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html to produce this solution:
In my view (I am using the MVC paradigm, but it could be your .html
or .php
file, or the technology that you use for your front-end):
<form action="../../photos/upload.php" method="post" enctype="multipart/form-data">
<label for="quantity">Width:</label>
<input type="number" id="picture_width" name="picture_width" min="10" max="800" step="1" value="500">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
My upload.php
:
<?php
/* Get original image x y*/
list($w, $h) = getimagesize($_FILES['fileToUpload']['tmp_name']);
$new_height=$h*$_POST['picture_width']/$w;
/* calculate new image size with ratio */
$ratio = max($_POST['picture_width']/$w, $new_height/$h);
$h = ceil($new_height / $ratio);
$x = ($w - $_POST['picture_width'] / $ratio) / 2;
$w = ceil($_POST['picture_width'] / $ratio);
/* new file name */
//$path = 'uploads/'.$_POST['picture_width'].'x'.$new_height.'_'.basename($_FILES['fileToUpload']['name']);
$path = 'uploads/'.basename($_FILES['fileToUpload']['name']);
/* read binary data from image file */
$imgString = file_get_contents($_FILES['fileToUpload']['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($_POST['picture_width'], $new_height);
imagecopyresampled($tmp, $image,
0, 0,
$x, 0,
$_POST['picture_width'], $new_height,
$w, $h);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($path,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
//echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($path)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
/* Save image */
switch ($_FILES['fileToUpload']['type']) {
case 'image/jpeg':
imagejpeg($tmp, $path, 100);
break;
case 'image/png':
imagepng($tmp, $path, 0);
break;
case 'image/gif':
imagegif($tmp, $path);
break;
default:
exit;
break;
}
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
/* cleanup memory */
imagedestroy($image);
imagedestroy($tmp);
}
?>
The name of the folder where pictures are stored is called 'uploads/'. You need to have that folder previously created and that is where you will see your pictures. It works great for me.
NOTE: This is my form:
The code is uploading and resizing pictures properly. I used this link as a guide: http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html. I modified it because in that code they specify both width and height of resized pictures. In my case, I only wanted to specify width. The height I automatically calculated it proportionally, just keeping proper picture proportions. Everything works perfectly. I hope this helps.
I'd be cautious as dismissing something as a bad idea because it is slow. If it is a part of the code that does not take much time to execute then the slowness is irrelevant. I just used the following code:
for (ic in 1:(dim(centroid)[2]))
{
cluster[[ic]]=matrix(,nrow=2,ncol=0)
}
# code to identify cluster=pindex[ip] to which to add the point
if(pdist[ip]>-1)
{
cluster[[pindex[ip]]]=cbind(cluster[[pindex[ip]]],points[,ip])
}
for a problem that ran in less than 1 second.
PROBLEM SOLVED !!!!!!!
Turns out the storage
function DID NOT run even once.
because i had to include app.use(upload)
as upload = multer({storage}).single('file');
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './storage')
},
filename: function (req, file, cb) {
console.log(file) // this didn't print anything out so i assumed it was never excuted
cb(null, file.fieldname + '-' + Date.now())
}
});
const upload = multer({storage}).single('file');
I needed to exclude names that started with an underscore from a query, so I ended up with this:
WHERE b.[name] not like '\_%' escape '\' -- use \ as the escape character
The reason the code is crashing is because the Bitmap
is attempting to be created on the Main Thread
which is not allowed since it may cause Android Not Responding (ANR) errors.
toBitmap()
is a Kotlin extension function requiring that library to be added to the app dependencies.Bitmap
in a different thread then the Main Thread
.In this sample using Kotlin Coroutines the function is being executed in the Dispatchers.IO
thread which is meant for CPU based operations. The function is prefixed with suspend
which is a Coroutine syntax.
Bonus - After the Bitmap
is created it is also compressed into an ByteArray
so it can be passed via an Intent
later outlined in this full sample.
Repository.kt
suspend fun bitmapToByteArray(url: String) = withContext(Dispatchers.IO) {
MutableLiveData<Lce<ContentResult.ContentBitmap>>().apply {
postValue(Lce.Loading())
postValue(Lce.Content(ContentResult.ContentBitmap(
ByteArrayOutputStream().apply {
try {
BitmapFactory.decodeStream(URL(url).openConnection().apply {
doInput = true
connect()
}.getInputStream())
} catch (e: IOException) {
postValue(Lce.Error(ContentResult.ContentBitmap(ByteArray(0), "bitmapToByteArray error or null - ${e.localizedMessage}")))
null
}?.compress(CompressFormat.JPEG, BITMAP_COMPRESSION_QUALITY, this)
}.toByteArray(), "")))
}
}
ViewModel.kt
//Calls bitmapToByteArray from the Repository
private fun bitmapToByteArray(url: String) = liveData {
emitSource(switchMap(repository.bitmapToByteArray(url)) { lce ->
when (lce) {
is Lce.Loading -> liveData {}
is Lce.Content -> liveData {
emit(Event(ContentResult.ContentBitmap(lce.packet.image, lce.packet.errorMessage)))
}
is Lce.Error -> liveData {
Crashlytics.log(Log.WARN, LOG_TAG,
"bitmapToByteArray error or null - ${lce.packet.errorMessage}")
}
}
})
}
ByteArray
back to Bitmap
.Utils.kt
fun ByteArray.byteArrayToBitmap(context: Context) =
run {
BitmapFactory.decodeByteArray(this, BITMAP_OFFSET, size).run {
if (this != null) this
// In case the Bitmap loaded was empty or there is an error I have a default Bitmap to return.
else AppCompatResources.getDrawable(context, ic_coinverse_48dp)?.toBitmap()
}
}
You could do it like this :
bool areFieldEmpty = YES;
//Label to leave the loops
outer_loop;
//For each input (except of submit) in your form
$('form input[type!=submit]').each(function(){
//If the field's empty
if($(this).val() != '')
{
//Mark it
areFieldEmpty = NO;
//Then leave all the loops
break outer_loop;
}
});
//Then test your bool
In Python, you can use urllib2
(http://docs.python.org/2/library/urllib2.html) to do all of that work for you.
Simply enough:
import urllib2
f = urllib2.urlopen(url)
print f.read()
Will print the received HTTP response.
To pass GET/POST parameters the urllib.urlencode()
function can be used. For more information, you can refer to the Official Urllib2 Tutorial
I had the same problem... I had to run it as a user.
00 * * * * root /usr/bin/php /var/virtual/hostname.nz/public_html/cronjob.php
There is a workaround using Web Server for Chrome.
Here are the steps:
Now easily access your local file:
function run(){
// 8887 is the port number you have launched your serve
var URL = "http://127.0.0.1:8887/002.jpg";
window.open(URL, null);
}
run();
PS: You might need to select the CORS Header option from advanced setting incase you face any cross origin access error.
I increased my memory following the next Google documentation:
http://tools.android.com/tech-docs/configuration
By default Android Studio is assigned a max of 750Mb, I changed to 2048Mb.
I tried what google described but for me the only thing that it worked was to use an environment variable. I will describe what I did:
First I created a directory that I called .AndroidStudioSettings,
mkdir .AndroidStudioSettings
Then I created a file called studio.vmoptions , and I put in that file the following content:
-Xms256m
-Xmx2048m
-XX:MaxPermSize=512m
-XX:ReservedCodeCacheSize=128m
-XX:+UseCompressedOops
Then I added the STUDIO_VM_OPTIONS environment variables in my .profile file:
export STUDIO_VM_OPTIONS=/Users/youruser/.AndroidStudioSettings/studio.vmoptions
Then I reload my .profile:
source ~/.profile
And finally I open Android Studio:
open /Applications/Android\ Studio.app
And now as you can see using the status bar , I have more than 2000 MB available for Android Studio:
You can customize your values according to your need in my case 2048Mb is enough.
UPDATE : Android Studio 2.0 let's you modify this file by accessing "Edit Custom VM Options" from the Help menu, just copy and paste the variables you might want to keep in order to increase it for everversion you might have on your box.
There are some good answers here but also some misunderstandings. I support the following settings for modern browsers when styling for dimensions in web pages:
html {
height: 100%; /* fallback for IE and older browsers */
height: 100vh;
}
body {
height: auto; /* required to allow content to expand vertically without overflow */
width: auto;
min-height: 100%; /* fallback for IE and older browsers */
min-height: 100vh;
margin: 0;
padding: 0;
}
For starters, the new viewport units ("vh") are redundant and not necessary as long as you have set html
to a height of 100%
. The reason is the body
derives its values from the html
parent. You can still use "vh" units in body
to bypass the parent and get its property dimensions directly from the viewport. But its optional if html
has 100%
height.
Notice I've set body
to height:auto
. You do NOT want to set body
height
and width
to 100%
, or specific values as that limits content to the viewport's dimensions and there will be overflow. height:auto
is your best friend in CSS! Using overflow:auto
properties are not needed if you set height:auto
on the body
. That tells the page to let content expand height to any dimension necessary, even that beyond the viewport's height, if it needs to. It will not break out of the body
dimensions. And it does allow scrolling as needed. auto
also allows you to have margins and still support pages that fill the viewport using min-height
. I believe height:auto
is the default on body in most UA browser style sheets, anyway.
Adding min-height:100%
then gives you the default height you want body
to have and then allows the page dimensions to fill the viewport without content breaking out of the body. This works only because html
has derived its height:100%
based on the viewport.
The two CRITICAL pieces here are not the units, like %
or vh
, but making sure the root element, or html
, is set to 100% of the viewport height. Second, its important that body have a min-height:100%
or min-height:100vh
so it starts out filling the viewport height, whatever that may be. Nothing else beyond that is needed. Notice I have added "fallback" properties for min-height, as many browsers post-2010 do not support "vh" units. Its fun to pretend everyone in the web world uses the latest and greatest but the reality is many legacy browsers are still around today in big corporate networks still use antiquated browsers that do not understand those new units.
STYLING HEIGHT FOR LEGACY BROWSERS
One of the things we forget is many very old browsers do not know how to fill the the viewport height correctly. Sadly, those legacy browsers simply had to have height:100%
on both the html
element and the body
. If you did not do that, browser background colors and other weird visuals would flow up under content that did not fill the viewport. We solved that by delivering these 100% values only to older user-agents. If you are testing on a legacy browser, keep that in mind.
html {
height:100%;
}
body {
height:100%;
width:auto;
margin:0;
padding:0;
}
Assuming such a query would return a single row, you could use either
select @EmpId = Id from dbo.Employee
Or
set @EmpId = (select Id from dbo.Employee)
This topic really helped me, so I'd like to share my improvements. All credits go to the nixda, this is based on his answer.
For those who need to convert multiple csv's in a folder, just modify the directory. Outputfilenames will be identical to input, just with another extension.
Take care of the cleanup in the end, if you like to keep the original csv's you might not want to remove these.
Can be easily modifed to save the xlsx in another directory.
$workingdir = "C:\data\*.csv"
$csv = dir -path $workingdir
foreach($inputCSV in $csv){
$outputXLSX = $inputCSV.DirectoryName + "\" + $inputCSV.Basename + ".xlsx"
### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application
$excel.DisplayAlerts = $False
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
### Set the delimiter (, or ;) according to your regional settings
### $Excel.Application.International(3) = ,
### $Excel.Application.International(5) = ;
$query.TextFileOtherDelimiter = $Excel.Application.International(5)
### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
### Execute & delete the import query
$query.Refresh()
$query.Delete()
### Save & close the Workbook as XLSX. Change the output extension for Excel 2003
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()
}
## To exclude an item, use the '-exclude' parameter (wildcards if needed)
remove-item -path $workingdir -exclude *Crab4dq.csv
The DataTable.Clone()
method works great when you want to create a completely new DataTable, but there might be cases where you would want to add the schema columns from one DataTable to another existing DataTable.
For example, if you've derived a new subclass from DataTable, and want to import schema information into it, you couldn't use Clone().
E.g.:
public class CoolNewTable : DataTable {
public void FillFromReader(DbDataReader reader) {
// We want to get the schema information (i.e. columns) from the
// DbDataReader and
// import it into *this* DataTable, NOT a new one.
DataTable schema = reader.GetSchemaTable();
//GetSchemaTable() returns a DataTable with the columns we want.
ImportSchema(this, schema); // <--- how do we do this?
}
}
The answer is just to create new DataColumns in the existing DataTable using the schema table's columns as templates.
I.e. the code for ImportSchema would be something like this:
void ImportSchema(DataTable dest, DataTable source) {
foreach(var c in source.Columns)
dest.Columns.Add(c);
}
or, if you're using Linq:
void ImportSchema(DataTable dest, DataTable source) {
var cols = source.Columns.Cast<DataColumn>().ToArray();
dest.Columns.AddRange(cols);
}
This was just one example of a situation where you might want to copy schema/columns from one DataTable into another one without using Clone() to create a completely new DataTable. I'm sure I've come across several others as well.
this is the source code about wraps:
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Update a wrapper function to look like the wrapped function
wrapper is the function to be updated
wrapped is the original function
assigned is a tuple naming the attributes assigned directly
from the wrapped function to the wrapper function (defaults to
functools.WRAPPER_ASSIGNMENTS)
updated is a tuple naming the attributes of the wrapper that
are updated with the corresponding attribute from the wrapped
function (defaults to functools.WRAPPER_UPDATES)
"""
for attr in assigned:
setattr(wrapper, attr, getattr(wrapped, attr))
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
# Return the wrapper so this can be used as a decorator via partial()
return wrapper
def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)
I got the exact same error using AngularJS 1.3.9 when I, in my custom sort-filter invoked Array.reverse()
After I removed it, it wa sall good.
The default scope is package-private. All classes in the same package can access the method/field/class. Package-private is stricter than protected and public scopes, but more permissive than private scope.
More information:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://mindprod.com/jgloss/scope.html
Button cancelBTN = new Button();
cancelBTN.Size = new Size(0, 0);
cancelBTN.TabStop = false;
this.Controls.Add(cancelBTN);
this.CancelButton = cancelBTN;
Bootstrap 4 - Update 2020
The Affix plugin no longer exists in Bootstrap 4, but now most browsers support position:sticky
which can be used to create a sticky after scoll Navbar. Bootstrap 4 includes the sticky-top
class for this...
https://codeply.com/go/oY2CyNiA7A
Bootstrap 3 - Original Answer
Here's a Bootstrap 3 example that doesn't require extra jQuery.. it uses the Affix
plugin included in Bootstrap 3, but the navbar markup has changed since BS2...
<!-- Content Above Nav -->
<header class="masthead">
</header>
<!-- Begin Navbar -->
<div id="nav">
<div class="navbar navbar-default navbar-static">
<div class="container">
<!-- .btn-navbar is used as the toggle for collapsed navbar content -->
<a class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="glyphicon glyphicon-bar"></span>
<span class="glyphicon glyphicon-bar"></span>
<span class="glyphicon glyphicon-bar"></span>
</a>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li class="divider"></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
<ul class="nav pull-right navbar-nav">
<li>
..
</li>
<li>
..
</li>
</ul>
</div>
</div>
</div><!-- /.navbar -->
</div>
Working demo/template: http://bootply.com/69848
i solved this problem by removing space between quotes and command value inside of array ,this is happened because container exited after started and no executable command present which to be run inside of container.
['sh', '-c', 'echo Hello Kubernetes! && sleep 3600']
try,
str_list = " ".join([str(ele) for ele in numlist])
this statement will give you each element of your list in string
format
print("The list now looks like [{0}]".format(str_list))
and,
change print(numlist.pop(2)+" has been removed")
to
print("{0} has been removed".format(numlist.pop(2)))
as well.
Using inputStream.available()
It is always acceptable for System.in.available() to return 0.
I've found the opposite - it always returns the best value for the number of bytes available. Javadoc for InputStream.available()
:
Returns an estimate of the number of bytes that can be read (or skipped over)
from this input stream without blocking by the next invocation of a method for
this input stream.
An estimate is unavoidable due to timing/staleness. The figure can be a one-off underestimate because new data are constantly arriving. However it always "catches up" on the next call - it should account for all arrived data, bar that arriving just at the moment of the new call. Permanently returning 0 when there are data fails the condition above.
First Caveat: Concrete subclasses of InputStream are responsible for available()
InputStream
is an abstract class. It has no data source. It's meaningless for it to have available data. Hence, javadoc for available()
also states:
The available method for class InputStream always returns 0.
This method should be overridden by subclasses.
And indeed, the concrete input stream classes do override available(), providing meaningful values, not constant 0s.
Second Caveat: Ensure you use carriage-return when typing input in Windows.
If using System.in
, your program only receives input when your command shell hands it over. If you're using file redirection/pipes (e.g. somefile > java myJavaApp or somecommand | java myJavaApp ), then input data are usually handed over immediately. However, if you manually type input, then data handover can be delayed. E.g. With windows cmd.exe shell, the data are buffered within cmd.exe shell. Data are only passed to the executing java program following carriage-return (control-m or <enter>
). That's a limitation of the execution environment. Of course, InputStream.available() will return 0 for as long as the shell buffers the data - that's correct behaviour; there are no available data at that point. As soon as the data are available from the shell, the method returns a value > 0. NB: Cygwin uses cmd.exe too.
Just use this:
byte[] inputData = new byte[1024];
int result = is.read(inputData, 0, is.available());
// result will indicate number of bytes read; -1 for EOF with no data read.
OR equivalently,
BufferedReader br = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1")),1024);
// ...
// inside some iteration / processing logic:
if (br.ready()) {
int readCount = br.read(inputData, bufferOffset, inputData.length-bufferOffset);
}
Declare this:
public static int readInputStreamWithTimeout(InputStream is, byte[] b, int timeoutMillis)
throws IOException {
int bufferOffset = 0;
long maxTimeMillis = System.currentTimeMillis() + timeoutMillis;
while (System.currentTimeMillis() < maxTimeMillis && bufferOffset < b.length) {
int readLength = java.lang.Math.min(is.available(),b.length-bufferOffset);
// can alternatively use bufferedReader, guarded by isReady():
int readResult = is.read(b, bufferOffset, readLength);
if (readResult == -1) break;
bufferOffset += readResult;
}
return bufferOffset;
}
Then use this:
byte[] inputData = new byte[1024];
int readCount = readInputStreamWithTimeout(System.in, inputData, 6000); // 6 second timeout
// readCount will indicate number of bytes read; -1 for EOF with no data read.
When most people talk about binary trees, they're more often than not thinking about binary search trees, so I'll cover that first.
A non-balanced binary search tree is actually useful for little more than educating students about data structures. That's because, unless the data is coming in in a relatively random order, the tree can easily degenerate into its worst-case form, which is a linked list, since simple binary trees are not balanced.
A good case in point: I once had to fix some software which loaded its data into a binary tree for manipulation and searching. It wrote the data out in sorted form:
Alice
Bob
Chloe
David
Edwina
Frank
so that, when reading it back in, ended up with the following tree:
Alice
/ \
= Bob
/ \
= Chloe
/ \
= David
/ \
= Edwina
/ \
= Frank
/ \
= =
which is the degenerate form. If you go looking for Frank in that tree, you'll have to search all six nodes before you find him.
Binary trees become truly useful for searching when you balance them. This involves rotating sub-trees through their root node so that the height difference between any two sub-trees is less than or equal to 1. Adding those names above one at a time into a balanced tree would give you the following sequence:
1. Alice
/ \
= =
2. Alice
/ \
= Bob
/ \
= =
3. Bob
_/ \_
Alice Chloe
/ \ / \
= = = =
4. Bob
_/ \_
Alice Chloe
/ \ / \
= = = David
/ \
= =
5. Bob
____/ \____
Alice David
/ \ / \
= = Chloe Edwina
/ \ / \
= = = =
6. Chloe
___/ \___
Bob Edwina
/ \ / \
Alice = David Frank
/ \ / \ / \
= = = = = =
You can actually see whole sub-trees rotating to the left (in steps 3 and 6) as the entries are added and this gives you a balanced binary tree in which the worst case lookup is O(log N)
rather than the O(N
) that the degenerate form gives. At no point does the highest NULL (=
) differ from the lowest by more than one level. And, in the final tree above, you can find Frank by only looking at three nodes (Chloe
, Edwina
and, finally, Frank
).
Of course, they can become even more useful when you make them balanced multi-way trees rather than binary trees. That means that each node holds more than one item (technically, they hold N items and N+1 pointers, a binary tree being a special case of a 1-way multi-way tree, with 1 item and 2 pointers).
With a three-way tree, you end up with:
Alice Bob Chloe
/ | | \
= = = David Edwina Frank
/ | | \
= = = =
This is typically used in maintaining keys for an index of items. I've written database software optimised for the hardware where a node is exactly the size of a disk block (say, 512 bytes) and you put as many keys as you can into a single node. The pointers in this case were actually record numbers into a fixed-length-record direct-access file separate from the index file (so record number X
could be found by just seeking to X * record_length
).
For example, if the pointers are 4 bytes and the key size is 10, the number of keys in a 512-byte node is 36. That's 36 keys (360 bytes) and 37 pointers (148 bytes) for a total of 508 bytes with 4 bytes wasted per node.
The use of multi-way keys introduces the complexity of a two-phase search (multi-way search to find the correct node combined with a small sequential (or linear binary) search to find the correct key in the node) but the advantage in doing less disk I/O more than makes up for this.
I see no reason to do this for an in-memory structure, you'd be better off sticking with a balanced binary tree and keeping your code simple.
Also keep in mind that the advantages of O(log N)
over O(N)
don't really appear when your data sets are small. If you're using a multi-way tree to store the fifteen people in your address book, it's probably overkill. The advantages come when you're storing something like every order from your hundred thousand customers over the last ten years.
The whole point of big-O notation is to indicate what happens as the N
approaches infinity. Some people may disagree but it's even okay to use bubble sort if you're sure the data sets will stay below a certain size, as long as nothing else is readily available :-)
As to other uses for binary trees, there are a great many, such as:
Given how much explanation I generated for the search trees, I'm reticent to go into a lot of detail on the others, but that should be enough to research them, should you desire.
Try this backgroundColor: '#00000000'
it will set background color to transparent, it follows #rrggbbaa hex codes
To write it in one line
this.setState({ someProperty: { ...this.state.someProperty, flag: false} });
webDriver.findElement(By.xpath("//a[@href='/docs/configuration']")).click();
The above line works fine. Please remove the space after href.
Is that element is visible in the page, if the element is not visible please scroll down the page then perform click action.
Or you can do it that manner:
for key in my_dict:
print key, my_dict[key]
Try using Git Bash to push your code/make changes instead of uploading files directly on GitHub (it is less prone to errors and is quite comfortable at times - takes less time as well!), for doing so, you may follow the below-given steps:
You can use lamba function:
index = df.index[lambda x : for x in df.index() ]
print(index)
Press i
or a
to get into insert mode, and type the message of choice
Press ESC
several times to get out of insert mode, or any other mode you might have run into by accident
to save, :wq
, :x
or ZZ
to exit without saving, :q!
or ZQ
To reload a file and undo all changes you have made...:
Press several times ESC
and then enter :e!
.
for specific requirement the following will work for search:
select * from table_name where (column_name1='%var1%' or column_name2='var2' or column_name='%var3%') and column_name='var';
if you want to query for searching data from the database this will work perfectly.
I use this to find files and then have PowerShell display the entire path of the results:
dir -Path C:\FolderName -Filter FileName.fileExtension -Recurse | %{$_.FullName}
You can always use the wildcard *
in the FolderName
and/or FileName.fileExtension
. For example:
dir -Path C:\Folder* -Filter File*.file* -Recurse | %{$_.FullName}
The above example will search any folder in the C:\
drive beginning with the word Folder
. So if you have a folder named FolderFoo
and FolderBar
PowerShell will show results from both of those folders.
The same goes for the file name and file extension. If you want to search for a file with a certain extension, but don't know the name of the file, you can use:
dir -Path C:\FolderName -Filter *.fileExtension -Recurse | %{$_.FullName}
Or vice versa:
dir -Path C:\FolderName -Filter FileName.* -Recurse | %{$_.FullName}
Alex mentioned memory efficiency, and Roberto mentions convenience, and these are both good points. For a few more ideas, I'll mention speed and functionality.
Functionality: You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc. And really, who can live without FFTs?
Speed: Here's a test on doing a sum over a list and a NumPy array, showing that the sum on the NumPy array is 10x faster (in this test -- mileage may vary).
from numpy import arange
from timeit import Timer
Nelements = 10000
Ntimeits = 10000
x = arange(Nelements)
y = range(Nelements)
t_numpy = Timer("x.sum()", "from __main__ import x")
t_list = Timer("sum(y)", "from __main__ import y")
print("numpy: %.3e" % (t_numpy.timeit(Ntimeits)/Ntimeits,))
print("list: %.3e" % (t_list.timeit(Ntimeits)/Ntimeits,))
which on my systems (while I'm running a backup) gives:
numpy: 3.004e-05
list: 5.363e-04
You can use the upper() function in your query, and to increase performance you can use a function-base index
CREATE INDEX upper_index_name ON table(upper(name))
Can you use:
[self.navigationController pushViewController:controller animated:YES];
Going back (I think):
[self.navigationController popToRootViewControllerAnimated:YES];
Since static methods can not be inherited . So no use placing it in the interface. Interface is basically a contract which all its subscribers have to follow . Placing a static method in interface will force the subscribers to implement it . which now becomes contradictory to the fact that static methods can not be inherited .
You cannot have spaces around the =
sign.
When you write:
STR = "foo"
bash tries to run a command named STR
with 2 arguments (the strings =
and foo
)
When you write:
STR =foo
bash tries to run a command named STR
with 1 argument (the string =foo
)
When you write:
STR= foo
bash tries to run the command foo
with STR set to the empty string in its environment.
I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:
STR "=" "foo"
,STR "=foo"
,STR="" foo
.The relevant section of the sh language spec, section 2.9.1 states:
A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.
In that context, a word
is the command that bash is going to run. Any string containing =
(in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the =
is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In STR = "foo"
, STR
is not a variable assignment.
The file hello.py is not an executable file. You need to specify a file like python.exe
try following:
import sys
subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm'])
additionally to @franc's answer you can use this from sql interface:
select
prosrc
from pg_trigger, pg_proc
where
pg_proc.oid=pg_trigger.tgfoid
and pg_trigger.tgname like '<name>'
(taken from here: http://www.postgresql.org/message-id/Pine.BSF.4.10.10009140858080.28013-100000@megazone23.bigpanda.com)
Don't get confused with the concepts of Angular and RxJS
We have pipes concept in Angular and pipe()
function in RxJS.
1) Pipes in Angular: A pipe takes in data as input and transforms it to the desired output
https://angular.io/guide/pipes
2) pipe()
function in RxJS: You can use pipes to link operators together. Pipes let you combine multiple functions into a single function.
The pipe()
function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
https://angular.io/guide/rx-library (search for pipes in this URL, you can find the same)
So according to your question, you are referring pipe()
function in RxJS
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
For those trouble shooting, it is important to know that ng-include requires the url path to be from the app root directory and not from the same directory where the partial.html lives. (whereas partial.html is the view file that the inline ng-include markup tag can be found).
For example:
Correct: div ng-include src=" '/views/partials/tabSlides/add-more.html' ">
Incorrect: div ng-include src=" 'add-more.html' ">
If you look at the code for the component you can see that it uses the className
prop passed to it to combine with the row
class to get the resulting set of classes (<Row className="aaa bbb"...
works).Also, if you provide the id
prop like <Row id="444" ...
it will actually set the id attribute for the element.
DO $$
DECLARE tableId integer;
BEGIN
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id INTO tableId;
INSERT INTO Table2 (val) VALUES (tableId);
END $$;
Tested with psql (10.3, server 9.6.8)
I got this error because I was using a wrong CSS selector with the Selenium WebDriver Node.js function By.css()
.
You can check if your selector is correct by using it in the web console of your web browser (Ctrl+Shift+K shortcut), with the JavaScript function document.querySelectorAll()
.
A great source of information I came across while trying to install everything Android SDK related from the command line, was this Dockerfile. Inside the Dockerfile you can see that the author executes a single command to install platform tools
and build tools
without any other interaction. In the case the OP has put forth, the command would be adapted to:
echo y | $ANDROID_HOME/tools/android update sdk --all --filter build-tools-21.1.0 --no-ui
I just faced this issue, and decided to make everything work with as less variables as i can, to keep workspace clean. Here is example of my code
<input type="checkbox" (change)="changeModel($event, modelArr, option.value)" [checked]="modelArr.includes(option.value)" />
Method, which called on change is pushing value in model, or removing it.
public changeModel(ev, list, val) {
if (ev.target.checked) {
list.push(val);
} else {
let i = list.indexOf(val);
list.splice(i, 1);
}
}
For me I had to put the whole interval in single quotes not just the value of the interval.
select id,
title,
created_at + interval '1 day' * claim_window as deadline from projects
Instead of
select id,
title,
created_at + interval '1' day * claim_window as deadline from projects
A bit late, and not a complete solution either, but for everyone who gets hit by this error without any obvious reason (having all the references defined, etc.) This thread put me on the correct track though. The issue seems to originate from some caching related bug in MS Office VBA Editor.
After making some changes to a project including about 40 forms with code modules plus 40 classes and some global modules in MS Access 2016 the compilation failed.
Commenting out code was obviously not an option, nor did exporting and re-importing all the 80+ files seem reasonable. Concentrating on what had recently been changed, my suspicions focused on removal of one class module.
Having no better ideas I re-cereated an empty class module with the same name that had previously been removed. And voliá the error was gone! It was even possible to remove the unused class module again without the error reappearing, until any changes were saved to a form module which previously had contained a WithEvents declaration involving the now removed class.
Not completely sure if WithEvents declaration really is what triggers the error even after the declaration has been removed. And no clues how to actually find out (without having information about the development history) which Form might be the culprit...
But what finally solved the issue was:
What about something like this?
>>> bin(int('ff', base=16))
'0b11111111'
This will convert the hexadecimal string you have to an integer and that integer to a string in which each byte is set to 0/1 depending on the bit-value of the integer.
As pointed out by a comment, if you need to get rid of the 0b
prefix, you can do it this way:
>>> bin(int('ff', base=16)).lstrip('0b')
'11111111'
or this way:
>>> bin(int('ff', base=16))[2:]
'11111111'
In my case, along with Mekanik's suggestions, I was receiving this error in Windows Server 2012 and I had to tick "HTTP Activation" in "Add Role Services".
Just set display:none;
as an attribute in your stylesheet ;)
It's way better than loading pictures for nothing.
body::-webkit-scrollbar {
width: 9px;
height: 9px;
}
body::-webkit-scrollbar-button:start:decrement,
body::-webkit-scrollbar-button:end:increment {
display: block;
height: 0;
background-color: transparent;
}
body::-webkit-scrollbar-track-piece {
background-color: #ffffff;
opacity: 0.2;
/* Here */
display: none;
-webkit-border-radius: 0;
-webkit-border-bottom-right-radius: 14px;
-webkit-border-bottom-left-radius: 14px;
}
body::-webkit-scrollbar-thumb:vertical {
height: 50px;
background-color: #333333;
-webkit-border-radius: 8px;
}
For anything with requests to URLs you might want to check out requests. For JSON in particular:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
As you are reading a book about NLTK it would be interesting you read about MaxEnt Classifier Module http://www.nltk.org/api/nltk.classify.html#module-nltk.classify.maxent
For text mining classification the steps could be: pre-processing (tokenization, steaming, feature selection with Information Gain ...), transformation to numeric (frequency or TF-IDF) (I think that this is the key step to understand when using text as input to a algorithm that only accept numeric) and then classify with MaxEnt, sure this is just an example.
Angular expressions do not support the ternary operator before 1.1.5, but it can be emulated like this:
condition && (answer if true) || (answer if false)
So in example, something like this would work:
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div>{{isExists(item) && 'available' || 'oh no, you don't have it'}}</div>
</div>
UPDATE: Angular 1.1.5 added support for ternary operators:
{{myVar === "two" ? "it's true" : "it's false"}}
String ordinal(int num)
{
String[] suffix = {"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"};
int m = num % 100;
return String.valueOf(num) + suffix[(m > 3 && m < 21) ? 0 : (m % 10)];
}
All I'm really interested in is the ownership and permissions information for the first level subdirectories.
I found a easy solution while playing my fish, which fits your need perfectly.
ll `ls`
or
ls -l $(ls)
mod means the reaminder when divided by. So 2 divided by 4 is 0 with 2 remaining. Therefore 2 mod 4 is 2.
<script type="text/javascript">_x000D_
$(window).bind("load", function() { _x000D_
_x000D_
// your javascript event_x000D_
_x000D_
)};_x000D_
</script>
_x000D_
Model1.belongsTo(Model2, { as: 'alias' })
Model1.findAll({include: [{model: Model2 , as: 'alias' }]},{raw: true}).success(onSuccess).error(onError);
UPDATE ANDROID STUDIO 3.4
Perhaps use tikz.
I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.
For that, there is the TransformToAncestor method:
Point relativePoint = myVisual.TransformToAncestor(rootVisual)
.Transform(new Point(0, 0));
Where myVisual
is the element that was just double-clicked, and rootVisual
is Application.Current.MainWindow or whatever you want the position relative to.
I would recommend using the commons-dbcp library. There are numerous examples listed on how to use it, here is the link to the move simple one. The usage is very simple:
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("oracle.jdbc.driver.OracleDriver")
ds.setUsername("scott");
ds.setPassword("tiger");
ds.setUrl(connectURI);
...
Connection conn = ds.getConnection();
You only need to create the data source once, so make sure you read the documentation if you do not know how to do that. If you are not aware of how to properly write JDBC statements so you do not leak resources, you also might want to read this Wikipedia page.
Hashing is a one way function (well, a mapping). It's irreversible, you apply the secure hash algorithm and you cannot get the original string back. The most you can do is to generate what's called "a collision", that is, finding a different string that provides the same hash. Cryptographically secure hash algorithms are designed to prevent the occurrence of collisions. You can attack a secure hash by the use of a rainbow table, which you can counteract by applying a salt to the hash before storing it.
Encrypting is a proper (two way) function. It's reversible, you can decrypt the mangled string to get original string if you have the key.
The unsafe functionality it's referring to is that if you encrypt the passwords, your application has the key stored somewhere and an attacker who gets access to your database (and/or code) can get the original passwords by getting both the key and the encrypted text, whereas with a hash it's impossible.
People usually say that if a cracker owns your database or your code he doesn't need a password, thus the difference is moot. This is naïve, because you still have the duty to protect your users' passwords, mainly because most of them do use the same password over and over again, exposing them to a greater risk by leaking their passwords.
If you must do this, you can check the user agent string in JavaScript:
var isIE10 = !!navigator.userAgent.match(/MSIE 10/);
As other people have mentioned, I'd always recommend feature detection instead.
You cannot initialize an array to '0' like that
int cipher[Array_size][Array_size]=0;
You can either initialize all the values in the array as you declare it like this:
// When using different values
int a[3] = {10,20,30};
// When using the same value for all members
int a[3] = {0};
// When using same value for all members in a 2D array
int a[Array_size][Array_size] = { { 0 } };
Or you need to initialize the values after declaration. If you want to initialize all values to 0 for example, you could do something like:
for (int i = 0; i < Array_size; i++ ) {
a[i] = 0;
}
http://www.manning.com/hethmon/ -- "Illustrated Guide to HTTP by Paul S. Hethmon" from Manning is a very good book to learn HTTP protocol and will be very useful to someone implementing it /extending it.
I use the ffmpeg-python
binding. You can find more information here.
import ffmpeg
(
ffmpeg
.input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)
.output('movie.mp4')
.run()
)
You can try with the following:
new_string = your_string.split(',').pop().trim();
This is how it works:
split(',')
creates an array made of the different parts of your_string
(e.g. if the string is "'SELECT___100E___7',24"
, the array would be ["'SELECT___100E___7'", "24"]
).
pop()
gets the last element of the array(in the example, it would be "24"
).
This would already be enough, but in case there might be some spaces (not in the case of the OP, but more in general), we could have:
trim()
that would remove the spaces around the string (in case it would be " 24 "
, it would become simply "24"
)It's a simple solution and surely easier than a regexp.
This worked for me perfectly in bootstrap 4.4.1 !!
.nav-pills > li > a.active{
background-color:#46b3e6 !important;
color:white !important;
}
.nav-pills > li.active > a:hover {
background-color:#46b3e6 !important;
color:white !important;
}
.nav-link-color {
color: #46b3e6;
}
For me on windows it was Ctrl+¡
, indent line. It adds a tab at the beggining of each line.
In my case, spring threw this because i forgot to make an inner class static.
When you found that it doesnt help even adding a no-arg constructor, please check your modifier.
Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.
Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.
As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:
Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.
Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:
meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)
Formula is from Chris Broadfoot's comment.
Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
What you're looking for are the scales for each zoom level. Use these:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000
As was said you need to remove the FKs before. On Mysql do it like this:
ALTER TABLE `table_name` DROP FOREIGN KEY `id_name_fk`;
ALTER TABLE `table_name` DROP INDEX `id_name_fk`;
There is actual a hack which makes it possible to add multiline placeholders in Webkit browsers, Chrome used to work but in more recent versions they removed it:
First add the first line of your placeholder to the html5 as usual
<textarea id="text1" placeholder="Line 1" rows="10"></textarea>
then add the rest of the line by css:
#text1::-webkit-input-placeholder::after {
display:block;
content:"Line 2\A Line 3";
}
If you want to keep your lines at one place you can try the following. The downside of this is that other browsers than chrome, safari, webkit-etc. don't even show the first line:
<textarea id="text2" placeholder="." rows="10"></textarea>?
then add the rest of the line by css:
#text2::-webkit-input-placeholder{
color:transparent;
}
#text2::-webkit-input-placeholder::before {
color:#666;
content:"Line 1\A Line 2\A Line 3\A";
}
It would be very great, if s.o. could get a similar demo working on Firefox.
All inputs should be replaced with custom directive that reads a single global variable to toggle readonly status.
// template
<your-input [readonly]="!childmessage"></your-input>
// component value
childmessage = false;
The second parameter of findBy
is for ORDER.
$ens = $em->getRepository('AcmeBinBundle:Marks')
->findBy(
array('type'=> 'C12'),
array('id' => 'ASC')
);
On my machine:
C:\Program Files\PostgreSQL\8.4\data\postgresql.conf
To solve this problem please follow the steps below:
In Java doc of Var-Args it is quite clear the usage of var args:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
about usage it says:
"So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called. "
Because font doesn't have color, you need a panel to make a backgound color and give the foreground color for both JLabel (if you use JLabel) and JPanel to make font color, like example below :
JLabel lblusr = new JLabel("User name : ");
lblusr.setForeground(Color.YELLOW);
JPanel usrPanel = new JPanel();
Color maroon = new Color (128, 0, 0);
usrPanel.setBackground(maroon);
usrPanel.setOpaque(true);
usrPanel.setForeground(Color.YELLOW);
usrPanel.add(lblusr);
The background color of label is maroon with yellow font color.
This is what I use:
#if DBG
#include <stdio.h>
#define DBGPRINT printf
#else
#define DBGPRINT(...) /**/
#endif
It has the nice benefit to handle printf properly, even without additional arguments. In case DBG ==0, even the dumbest compiler gets nothing to chew upon, so no code is generated.
Here's what I did based on
a) @Espo 's comments and
b) the fact that I only had Windows Task Manager to play with....
I logged onto the host machine, opened Task Manager and used the view menu to add the PID column to the Processes tab.
I wrote down (yes, with paper and a pen) the PID's for each and every instance of the vmware-wmx.exe process that was running on the box.
Using the VMWare console, I suspended the errant virtual machine.
When I resumed it, I could then identify the vmware-vmx process that corresponded to my machine and could kill it.
There doesn't seem to have been any ill effects so far.
As the others have said, there is no difference in the compiled code (IL) when you use either of the following:
var x1 = new object();
object x2 = new object;
I suppose Resharper warns you because it is [in my opinion] easier to read the first example than the second. Besides, what's the need to repeat the name of the type twice?
Consider the following and you'll get what I mean:
KeyValuePair<string, KeyValuePair<string, int>> y1 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));
It's way easier to read this instead:
var y2 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));
System.getProperties()
can be overridden by calls to System.setProperty(String key, String value)
or with command line parameters -Dfile.separator=/
File.separator
gets the separator for the default filesystem.
FileSystems.getDefault()
gets you the default filesystem.
FileSystem.getSeparator()
gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.
I use this function htmlentities($string):
$msg = "<script>alert("hello")</script> <h1> Hello World </h1>" $msg = htmlentities($msg); echo $msg;
In order to create an array of objects, the objects need a constructor that doesn't take any paramters (that creates a default form of the object, eg. with both strings empty). This is what the error message means. The compiler automatically generates a constructor which creates an empty object unless there are any other constructors.
If it makes sense for the array elements to be created empty (in which case the members acquire their default values, in this case, empty strings), you should:
-Write an empty constructor:
class name {
public:
string first;
string last;
name() { }
name(string a, string b){
first = a;
last = b;
}
};
-Or, if you don't need it, remove the existing constructor.
If an "empty" version of your class makes no sense, there is no good solution to provide initialisation paramters to all the elements of the array at compile time. You can:
init()
function which does the real initialisationvector
, and on initialisation create the objects and insert them into the vector
, either using vector::insert
or a loop, and trust that not doing it at compile time doesn't matter.std::vector<std::string> v = { "xyzzy", "plugh", "abracadabra" };
`
for API below 21, you can use theme attribute in EditText
put below code into style file
<style name="MyEditTextTheme">
<item name="colorControlNormal">#FFFFFF</item>
<item name="colorControlActivated">#FFFFFF</item>
<item name="colorControlHighlight">#FFFFFF</item>
</style>
use this style in EditText
as
<EditText
android:id="@+id/etPassword"
android:layout_width="match_parent"
android:layout_height="@dimen/user_input_field_height"
android:layout_marginTop="40dp"
android:hint="@string/password_hint"
android:theme="@style/MyEditTextTheme"
android:singleLine="true" />
You can use the following if you want to render raw html in React
<div dangerouslySetInnerHTML={{__html: `html-raw-goes-here`}} />
Example - Render
Test is a good day
objdump -T *.so
may also do the job
In order to copy a file use:
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>copy-resource-one</id>
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/destination-folder</outputDirectory>
<resources>
<resource>
<directory>/source-folder</directory>
<includes>
<include>file.jar</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
In order to copy folder with sub-folders use next configuration:
<configuration>
<outputDirectory>${basedir}/target-folder</outputDirectory>
<resources>
<resource>
<directory>/source-folder</directory>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
This is a place in which C++ has a strange rule. Before being able to compile a call to a function the compiler must know the function name, return value and all parameters.
This can be done by adding a "prototype". In your case this simply means adding before main
the following line:
int writeFile();
this tells the compiler that there exist a function named writeFile
that will be defined somewhere, that returns an int
and that accepts no parameters.
Alternatively you can define first the function writeFile
and then main
because in this case when the compiler gets to main
already knows your function.
Note that this requirement of knowing in advance the functions being called is not always applied. For example for class members defined inline it's not required...
struct Foo {
void bar() {
if (baz() != 99) {
std::cout << "Hey!";
}
}
int baz() {
return 42;
}
};
In this case the compiler has no problem analyzing the definition of bar
even if it depends on a function baz
that is declared later in the source code.
While you have a return value in checkform, it isn't being used anywhere - try using onclick="return checkform()"
instead.
You may want to considering replacing this method with onsubmit="return checkform()"
in the form tag instead, though both will work for clicking the button.
I came across this thread because I was looking to build an absolute URI for a success page. request.build_absolute_uri()
gave me a URI for my current view but to get the URI for my success view I used the following....
request.build_absolute_uri(reverse('success_view_name'))
Cleaning up Isaac's answer:
['mousemove', 'touchmove'].forEach(function(e) {
window.addEventListener(e, mouseMoveHandler);
});
EDIT
ES6 helper function:
function addMultipleEventListener(element, events, handler) {
events.forEach(e => element.addEventListener(e, handler))
}
jQuery.load() is probably the easiest way to load data asynchronously using a selector, but you can also use any of the jquery ajax methods (get, post, getJSON, ajax, etc.)
Note that load allows you to use a selector to specify what piece of the loaded script you want to load, as in
$("#mydiv").load(location.href + " #mydiv");
Note that this technically does load the whole page and jquery removes everything but what you have selected, but that's all done internally.
Emacs! Eclipse might work too.
Specifying the range through visual selection is ok but when there are very simple operations over just a couple of lines that can be selected by an operator the best would be to apply these commands as operators.
This sadly can't be done through standards vim commands. You could do a sort of workaround using the ! (filter) operator and any text object. For example, to apply the operation to a paragraph, you can do:
!ip
This has to be read as "Apply the operator ! inside a paragraph". The filter operator starts command mode and automatically insert the range of lines followed by a literal "!" that you can delete just after. If you apply this, to the following paragraph:
1
2 Repellendus qui velit vel ullam!
3 ipsam sint modi! velit ipsam sint
4 modi! Debitis dolorum distinctio
5 mollitia vel ullam! Repellendus qui
6 Debitis dolorum distinctio mollitia
7 vel ullam! ipsam
8
9 More text around here
The result after pressing "!ap" would be like:
:.,.+5
As the '.' (point) means the current line, the range between the current line and the 5 lines after will be used for the operation. Now you can add the substitute command the same way as previously.
The bad part is that this is not easier that selecting the text for latter applying the operator. The good part is that this can repeat the insertion of the range for other similar text ranges (in this case, paragraphs) with sightly different size. I.e., if you later want to select the range bigger paragraph the '.' will to it right.
Also, if you like the idea of using semantic text objects to select the range of operation, you can check my plugin EXtend.vim that can do the same but in an easier manner.
git branch -r -vv
will list all branches including remote.
There's a pretty good explanation of first level caching on the Streamline Logic blog.
Basically, first level caching happens on a per session basis where as second level caching can be shared across multiple sessions.
I am seeing starkly different runtimes when I take a for loop in g++ 4.7.0 and using
std::vector<double> x;
std::vector<double> y;
std::vector<double> prod;
for (int i = 0; i < 5000000; i++)
{
double r1 = ((double)rand() / double(RAND_MAX)) * 5;
double r2 = ((double)rand() / double(RAND_MAX)) * 5;
x.push_back(r1);
y.push_back(r2);
}
int sz = x.size();
#pragma omp parallel for
for (int i = 0; i< sz; i++)
prod[i] = x[i] * y[i];
the serial code (no openmp
) runs in 79 ms.
the "parallel for" code runs in 29 ms.
If I omit the for
and use #pragma omp parallel
, the runtime shoots up to 179ms,
which is slower than serial code. (the machine has hw concurrency of 8)
the code links to libgomp
same for Terminator
Ctrl + Shift + V
Look at your terminal key-bindings if any if that doesn't work
A Scala solution, adapted from Vasya Novikov's answer and specialized for binary trees:
/** An immutable Binary Tree. */
case class BTree[T](value: T, left: Option[BTree[T]], right: Option[BTree[T]]) {
/* Adapted from: http://stackoverflow.com/a/8948691/643684 */
def pretty: String = {
def work(tree: BTree[T], prefix: String, isTail: Boolean): String = {
val (line, bar) = if (isTail) ("+-- ", " ") else ("+-- ", "¦")
val curr = s"${prefix}${line}${tree.value}"
val rights = tree.right match {
case None => s"${prefix}${bar} +-- Ø"
case Some(r) => work(r, s"${prefix}${bar} ", false)
}
val lefts = tree.left match {
case None => s"${prefix}${bar} +-- Ø"
case Some(l) => work(l, s"${prefix}${bar} ", true)
}
s"${curr}\n${rights}\n${lefts}"
}
work(this, "", true)
}
}
If I can add my $0.02, I prefer using PascalCase as enum values in C.
In C, they are basically global, and PEER_CONNECTED gets really tiring as opposed to PeerConnected.
Breath of fresh air.
Literally, it makes me breathe easier.
In Java, it is possible to use raw enum names as long as you static import them from another class.
import static pkg.EnumClass.*;
Now, you can use the unqualified names, that you qualified in a different way already.
I am currently (thinking) about porting some C code to Java and currently 'torn' between choosing Java convention (which is more verbose, more lengthy, and more ugly) and my C style.
PeerConnected would become PeerState.CONNECTED except in switch statements, where it is CONNECTED.
Now there is much to say for the latter convention and it does look nice but certain "idiomatic phrases" such as if (s == PeerAvailable)
become like if (s == PeerState.AVAILABLE)
and nostalgically, this is a loss of meaning to me.
I think I still prefer the Java style because of clarity but I have a hard time looking at the screaming code.
Now I realize PascalCase is already widely used in Java but very confusing it would not really be, just a tad out of place.
You should put your model class before create_all()
call, like this:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
db.create_all()
db.session.commit()
admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users
If your models are declared in a separate module, import them before calling create_all()
.
Say, the User
model is in a file called models.py
,
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)
# See important note below
from models import User
db.create_all()
db.session.commit()
admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users
Important note: It is important that you import your models after initializing the db
object since, in your models.py
_you also need to import the db
object from this module.
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
get()
returns a collection of models matching the query.
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
Just use
composer require {package/packagename}
like
composer require phpmailer/phpmailer
if the package is not in the vendor folder.. composer installs it and if the package exists, composer update package to the latest version.
text align-center on parent element, display inline-block on child element. This will center all most anything. I believe its call a "block float".
<div class="outer">
<div class="inner"> some content </div>
</div><!-- end outer -->
<style>
div.outer{
width: 100%;
text-align: center;
}
div.inner{
display: inline-block;
text-align: left
}
</style>
This is also a good alternative for float's, good luck!
In wamp/alias/mySite.conf, be careful to add a slash "/" at the end of the alias' adress :
Replace :
Alias /mySite/ "D:/Work/Web/mySite/www"
By :
Alias /mySite/ "D:/Work/Web/mySite/www/"
Or the index.php is not read correctly.
nproc
is what you are looking for.
More here : http://www.cyberciti.biz/faq/linux-get-number-of-cpus-core-command/
I found that I can do some basic logic by running something like:
A=true
B=true
if ($A && $B); then
C=true
else
C=false
fi
echo $C
The bootstrap css can be generated by Less. The main purpose of map file is used to link the css source code to less source code in the chrome dev tool. As we used to do .If we inspect the element in the chrome dev tool. you can see the source code of css. But if include the map file in the page with bootstrap css file. you can see the less code which apply to the element style you want to inspect.
I think that for SQL Server Local Db you shouldn't use the Initial Catalog
property.
I suggest to use:
<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\v11.0;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\OdeToFoodDb.mdf"
providerName="System.Data.SqlClient" />
I think that local db doesn't support multiple database on the same mdf file so specify an initial catalog is not supported (or not well supported and I have some strange errors).
No need to create overload methods, just use one single method with params as shown below
// Call params method with one to four integer constant parameters.
//
int sum0 = addTwoEach();
int sum1 = addTwoEach(1);
int sum2 = addTwoEach(1, 2);
int sum3 = addTwoEach(3, 3, 3);
int sum4 = addTwoEach(2, 2, 2, 2);
I'm using GDB7.1.1, as --help
shows:
gdb [options] --args executable-file [inferior-arguments ...]
IMHO, the order is a bit unintuitive at first.
Swift 3.0 & 4.0
yourImage.draw(in: CGRect, blendMode: CGBlendMode, alpha: ImageOpacity)
No Alteration needed
Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:
Public Sub SubA()
On Error Goto ProcError
Connection.Open
Open File for Writing
SomePreciousResource.GrabIt
ProcExit:
Connection.Close
Connection = Nothing
Close File
SomePreciousResource.Release
Exit Sub
ProcError:
MsgBox Err.Description
Resume ProcExit
End Sub
OP I'm with you man. again too, there is nothing wrong with that answer with 300+ up votes, but my opinion is:
what is wrong with putting classes into their cozy warm own files individually? I mean this will make things looks much better right? (or someone just like a 1000 line file for all the models)
so then, if the first one will be achieved, we have to import import import... import just in each of the model files like man, srsly, a model file, a .d.ts file, why there are so many *s in there? it should just be simple, tidy, and that's it. Why I need imports there? why? C# got namespaces for a reason.
And by then, you are literally using "filenames.ts" as identifiers. As identifiers... Come on its 2017 now and we still do that? Ima go back to Mars and sleep for another 1000 years.
So sadly, my answer is: nop, you cannot make the "namespace" thing functional if you do not using all those imports or using those filenames as identifiers (which I think is really silly). Another option is: put all of those dependencies into a box called filenameasidentifier.ts and use
export namespace(or module) boxInBox {} .
wrap them so they wont try to access other classes with same name when they are just simply trying to get a reference from the class sit right on top of them.
In Project level build.gradle
use only this version
ext.kotlin_version = '1.3.31'
Remove other versions
This will only work with the latest version of android studio 3.4
UPDATE: Try to use the latest version of kotlin with latest Android studio to avoid an error.
-- If no parameters need to be passed to a procedure, simply:
BEGIN
MY_PACKAGE_NAME.MY_PROCEDURE_NAME
END;
You cannot.
According to the XML Schema specification, a boolean is true
or false
. True
is not valid:
3.2.2.1 Lexical representation An instance of a datatype that is defined as ·boolean· can have the following legal literals {true, false, 1, 0}. 3.2.2.2 Canonical representation The canonical representation for boolean is the set of literals {true, false}.
If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.
Each directive's compile
function is only called once, when Angular bootstraps.
Officially, this is the place to perform (source) template manipulations that do not involve scope or data binding.
Primarily, this is done for optimisation purposes; consider the following markup:
<tr ng-repeat="raw in raws">
<my-raw></my-raw>
</tr>
The <my-raw>
directive will render a particular set of DOM markup. So we can either:
ng-repeat
to duplicate the source template (<my-raw>
), and then modify the markup of each instance template (outside the compile
function).compile
function), and then allow ng-repeat
to duplicate it.If there are 1000 items in the raws
collection, the latter option may be faster than the former one.
You can also use this Chrome extension to quickly switch between using or not the cache: https://chrome.google.com/webstore/detail/cache-killer/jpfbieopdmepaolggioebjmedmclkbap
You should only set the contentSize property on the viewDidAppear, like this sample:
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
self.scrollView.contentSize=CGSizeMake(306,400.0);
}
It solve the autolayout problems, and works fine on iOS7.
Use Code::Blocks. It has everything you need and a very clean GUI.
There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:
.\mydocuments\folder\mybat.bat
.\mydocuments\folder\subfolder\file.txt
And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:
@Echo OFF
REM Do anything with ".\Subfolder\File1.txt"
PUSHD ".\Subfolder"
Type "File1.txt"
Pause&Exit
Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:
@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit
Even More straightforward:
axios.post('/addUser',{
userName: 'Fred',
userEmail: '[email protected]'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
As of NP++ V6.2.3 (nor sure about older versions) simply:
Hope this helps to achieve goal in simple and yet fast way:)
Got this from BrockAllen's answer that worked for me, it displays the keys that have errors:
var errors =
from item in ModelState
where item.Value.Errors.Count > 0
select item.Key;
var keys = errors.ToArray();
Source: https://forums.asp.net/t/1805163.aspx?Get+the+Key+value+of+the+Model+error
You can resize using style and width to resize the textbox. Here is the code for it.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div align="center">_x000D_
_x000D_
<form method="post">_x000D_
<div class="w3-row w3-section">_x000D_
<div class="w3-rest" align = "center">_x000D_
<input name="lastName" type="text" id="myInput" style="width: 50%">_x000D_
</div>_x000D_
</div>_x000D_
</form>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Use align to center the textbox.
This is a good example of the maven-ear-plugin part.
You can also check the maven archetypes that are available as an example. If you just runt mvn archetype:generate you'll get a list of available archetypes. One of them is
maven-archetype-j2ee-simple
Build.SERIAL
can be empty or sometimes return a different value (proof 1, proof 2) than what you can see in your device's settings.
If you want a more complete and robust solution, I've compiled every possible solution I could found in a single gist. Here's a simplified version of it :
public static String getSerialNumber() {
String serialNumber;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class);
serialNumber = (String) get.invoke(c, "gsm.sn1");
if (serialNumber.equals(""))
serialNumber = (String) get.invoke(c, "ril.serialnumber");
if (serialNumber.equals(""))
serialNumber = (String) get.invoke(c, "ro.serialno");
if (serialNumber.equals(""))
serialNumber = (String) get.invoke(c, "sys.serialnumber");
if (serialNumber.equals(""))
serialNumber = Build.SERIAL;
// If none of the methods above worked
if (serialNumber.equals(""))
serialNumber = null;
} catch (Exception e) {
e.printStackTrace();
serialNumber = null;
}
return serialNumber;
}
I try to update the gist regularly whenever I can test on a new device or Android version. Contributions are welcome too.
HashMap
is unordered per the second line of the documentation:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Perhaps you can do as aix suggests and use a LinkedHashMap
, or another ordered collection. This link can help you find the most appropriate collection to use.
See:
The last in particular provides detailed initialization steps that spell out when static variables are initialized, and in what order (with the caveat that final
class variables and interface fields that are compile-time constants are initialized first.)
I'm not sure what your specific question about point 3 (assuming you mean the nested one?) is. The detailed sequence states this would be a recursive initialization request so it will continue initialization.
use this
$("#tblEntAttributes tbody").append(newRowContent);
Internet Explorer 8 and earlier do not support XHTML parsing. Even if you use an XML declaration and/or an XHTML doctype, old IE still parse the document as plain HTML. And in plain HTML, the self-closing syntax is not supported. The trailing slash is just ignored, you have to use an explicit closing tag.
Even browsers with support for XHTML parsing, such as IE 9 and later, will still parse the document as HTML unless you serve the document with a XML content type. But in that case old IE will not display the document at all!
If one of the inserts fail, or any part of the command fails, does SQL server roll back the transaction?
No, it does not.
If it does not rollback, do I have to send a second command to roll it back?
Sure, you should issue ROLLBACK
instead of COMMIT
.
If you want to decide whether to commit or rollback the transaction, you should remove the COMMIT
sentence out of the statement, check the results of the inserts and then issue either COMMIT
or ROLLBACK
depending on the results of the check.
It is not at all clear what the OP meant (even after some back-and-forth in the comments), but here are two answers to possible interpretations of the question:
Use raw_input
in Python 2.x, and input
in Python 3. (These are built in, so you don't need to import anything to use them; you just have to use the right one for your version of python.)
For example:
user_input = raw_input("Some input please: ")
More details can be found here.
So, for example, you might have a script that looks like this
# First, do some work, to show -- as requested -- that
# the user input doesn't need to come first.
from __future__ import print_function
var1 = 'tok'
var2 = 'tik'+var1
print(var1, var2)
# Now ask for input
user_input = raw_input("Some input please: ") # or `input("Some...` in python 3
# Now do something with the above
print(user_input)
If you saved this in foo.py
, you could just call the script from the command line, it would print out tok tiktok
, then ask you for input. You could enter bar baz
(followed by the enter key) and it would print bar baz
. Here's what that would look like:
$ python foo.py
tok tiktok
Some input please: bar baz
bar baz
Here, $
represents the command-line prompt (so you don't actually type that), and I hit Enter
after typing bar baz
when it asked for input.
Suppose you have a script named foo.py
and want to call it with arguments bar
and baz
from the command line like
$ foo.py bar baz
(Again, $
represents the command-line prompt.) Then, you can do that with the following in your script:
import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]
Here, the variable arg1
will contain the string 'bar'
, and arg2
will contain 'baz'
. The object sys.argv
is just a list containing everything from the command line. Note that sys.argv[0]
is the name of the script. And if, for example, you just want a single list of all the arguments, you would use sys.argv[1:]
.
var start = new Date();
start.setHours(0,0,0,0);
var end = new Date();
end.setHours(23,59,59,999);
alert( start.toUTCString() + ':' + end.toUTCString() );
If you need to get the UTC time from those, you can use UTC()
.
Here is another way of doing it.
class Parameter(models.Model):
def __init__(self, *args, **kwargs):
super(Parameter, self).__init__(*args, **kwargs)
self.__original_value = self.value
def clean(self,*args,**kwargs):
if self.__original_value == self.value:
print("igual")
else:
print("distinto")
def save(self,*args,**kwargs):
self.full_clean()
return super(Parameter, self).save(*args, **kwargs)
self.__original_value = self.value
key = models.CharField(max_length=24, db_index=True, unique=True)
value = models.CharField(max_length=128)
As per documentation: validating objects
"The second step full_clean() performs is to call Model.clean(). This method should be overridden to perform custom validation on your model. This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field:"
If you want to test against all nil/empty objects (like empty strings or empty arrays/sets) you can use the following:
static inline BOOL IsEmpty(id object) {
return object == nil
|| ([object respondsToSelector:@selector(length)]
&& [(NSData *) object length] == 0)
|| ([object respondsToSelector:@selector(count)]
&& [(NSArray *) object count] == 0);
}
This should work:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
Below query is appropriate for the last 30 days records
Here, I have used a review table and review_date
is a column from the review table
SELECT * FROM reviews WHERE DATE(review_date) >= DATE(NOW()) - INTERVAL 30 DAY
Use This Within button on Click option or your needs:
final ProgressDialog progressDialog;
progressDialog = new ProgressDialog(getApplicationContext());
progressDialog.setMessage("Loading..."); // Setting Message
progressDialog.setTitle("ProgressDialog"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
The solution is very simple and worked for me.
Try this :
git pull --rebase <url>
then
git push -u origin master
declare @ids table(idx int identity(1,1), id int)
insert into @ids (id)
select 4 union
select 7 union
select 12 union
select 22 union
select 19
declare @i int
declare @cnt int
select @i = min(idx) - 1, @cnt = max(idx) from @ids
while @i < @cnt
begin
select @i = @i + 1
declare @id = select id from @ids where idx = @i
exec p_MyInnerProcedure @id
end
In order to remove all subviews Syntax :
- (void)makeObjectsPerformSelector:(SEL)aSelector;
Usage :
[self.View.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
This method is present in NSArray.h file and uses NSArray(NSExtendedArray) interface
If you want more datesource configs e.g.
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=30000
spring.datasource.validation-query=select 1
you could use below code
@Bean
public DataSource dataSource() {
DataSource dataSource = new DataSource(); // org.apache.tomcat.jdbc.pool.DataSource;
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setTestWhileIdle(testWhileIdle);
dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMills);
dataSource.setValidationQuery(validationQuery);
return dataSource;
}
refer: Spring boot jdbc Connection
import * as express from "express";
This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.
In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.
In Place of using this
MsgBox(json.SelectToken("Venue").SelectToken("ID"))
You can also use
MsgBox(json.SelectToken("Venue.ID"))
Definitely possible with any number of libraries and/or HTML5 technologies. You could possible hack something together in pure CSS by using something like the border-bottom property, but it would probably be horribly hacky.
If you're serious about this, you should take a look at a JS library for canvas drawing or SVG. For example, something like http://www.graphjs.org/ or http://jsdraw2dx.jsfiction.com/
Do not use floats to store fixed-point, accuracy-required data. This example shows how to convert a float to NVARCHAR(50) properly, while also showing why it is a bad idea to use floats for precision data.
create table #f ([Column_Name] float)
insert #f select 9072351234
insert #f select 907235123400000000000
select
cast([Column_Name] as nvarchar(50)),
--cast([Column_Name] as int), Arithmetic overflow
--cast([Column_Name] as bigint), Arithmetic overflow
CAST(LTRIM(STR([Column_Name],50)) AS NVARCHAR(50))
from #f
Output
9.07235e+009 9072351234
9.07235e+020 907235123400000010000
You may notice that the 2nd output ends with '10000' even though the data we tried to store in the table ends with '00000'. It is because float
datatype has a fixed number of significant figures supported, which doesn't extend that far.
The ConcurentLinkedQueue is a very efficient wait/lock free implementation (see the javadoc for reference), so not only you don't need to synchronize, but the queue will not lock anything, thus being virtually as fast as a non synchronized (not thread safe) one.
Unsigned integers are far more likely to catch you in a particular trap than are signed integers. The trap comes from the fact that while 1 & 3 above are correct, both types of integers can be assigned a value outside the bounds of what it can "hold" and it will be silently converted.
unsigned int ui = -1;
signed int si = -1;
if (ui < 0) {
printf("unsigned < 0\n");
}
if (si < 0) {
printf("signed < 0\n");
}
if (ui == si) {
printf("%d == %d\n", ui, si);
printf("%ud == %ud\n", ui, si);
}
When you run this, you'll get the following output even though both values were assigned to -1 and were declared differently.
signed < 0
-1 == -1
4294967295d == 4294967295d
Use the following command to clear screen in sqlplus.
SQL > clear scr
In my case, my xml had multiple namespaces and attributes. So I used this site to generate the objects - https://xmltocsharp.azurewebsites.net/
And used the below code to deserialize
XmlDocument doc = new XmlDocument();
doc.Load("PathTo.xml");
User obj;
using (TextReader textReader = new StringReader(doc.OuterXml))
{
using (XmlTextReader reader = new XmlTextReader(textReader))
{
XmlSerializer serializer = new XmlSerializer(typeof(User));
obj = (User)serializer.Deserialize(reader);
}
}
The textwrap.dedent
function allows one to start with correct indentation in the source, and then strip it from the text before use.
The trade-off, as noted by some others, is that this is an extra function call on the literal; take this into account when deciding where to place these literals in your code.
import textwrap
def frobnicate(param):
""" Frobnicate the scrognate param.
The Weebly-Ruckford algorithm is employed to frobnicate
the scrognate to within an inch of its life.
"""
prepare_the_comfy_chair(param)
log_message = textwrap.dedent("""\
Prepare to frobnicate:
Here it comes...
Any moment now.
And: Frobnicate!""")
weebly(param, log_message)
ruckford(param)
The trailing \
in the log message literal is to ensure that line break isn't in the literal; that way, the literal doesn't start with a blank line, and instead starts with the next full line.
The return value from textwrap.dedent
is the input string with all common leading whitespace indentation removed on each line of the string. So the above log_message
value will be:
Prepare to frobnicate:
Here it comes...
Any moment now.
And: Frobnicate!
queryParams
queryParams
is another input of routerLink
where they can be passed like
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>
fragment
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>
routerLinkActiveOptions
To also get routes active class set on parent routes:
[routerLinkActiveOptions]="{ exact: false }"
To pass query parameters to this.router.navigate(...)
use
let navigationExtras: NavigationExtras = {
queryParams: { 'session_id': sessionId },
fragment: 'anchor'
};
// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);
See also https://angular.io/guide/router#query-parameters-and-fragments
When you type integer numbers to JtextField1 after key release it will go to inside try , for any other character it will throw NumberFormatException. If you set empty string to jTextField1 inside the catch so the user cannot type any other keys except positive numbers because JTextField1 will be cleared for each bad attempt.
//Fields
int x;
JTextField jTextField1;
//Gui Code Here
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
try {
x = Integer.parseInt(jTextField1.getText());
} catch (NumberFormatException nfe) {
jTextField1.setText("");
}
}
Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.
To clear a canvas, use the delete method. Give it the special parameter "all"
to delete all items on the canvas (the string "all"
" is a special tag that represents all items on the canvas):
canvas.delete("all")
If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all"
, you could supply the name of a tag.
If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.
Using Confluent's REST Proxy API:
curl -X GET -H "Accept: application/vnd.kafka.v2+json" localhost:8082/topics
where localhost:8082
is Kafka Proxy address.
Sourcetree
Because you not commit your merge, then just double click on another branch (which mean checkout it) and when sourcetree ask you about discarding all changes then agree :)
Update
I see many down-votes but any commet... I will left this answer which is addressed for those who use SourceTree as git client (as I - when I looking for solution for question asked by OP)
Sorry I could not comment, so I just continue the work from tomwrong. This enhanced version will not count object more than once, thus no infinite loop. Plus, I reckon the key of an object should be also counted, roughly.
function roughSizeOfObject( value, level ) {
if(level == undefined) level = 0;
var bytes = 0;
if ( typeof value === 'boolean' ) {
bytes = 4;
}
else if ( typeof value === 'string' ) {
bytes = value.length * 2;
}
else if ( typeof value === 'number' ) {
bytes = 8;
}
else if ( typeof value === 'object' ) {
if(value['__visited__']) return 0;
value['__visited__'] = 1;
for( i in value ) {
bytes += i.length * 2;
bytes+= 8; // an assumed existence overhead
bytes+= roughSizeOfObject( value[i], 1 )
}
}
if(level == 0){
clear__visited__(value);
}
return bytes;
}
function clear__visited__(value){
if(typeof value == 'object'){
delete value['__visited__'];
for(var i in value){
clear__visited__(value[i]);
}
}
}
roughSizeOfObject(a);
Well, you essentially create a JDialog, add your text components and make it visible. It might help if you narrow down which specific bit you're having trouble with.
You have to set height as a string value when you use pixels.
document.getElementById('chartdiv').style.height = "200px"
Also try adding a DOCTYPE to your HTML for Internet Explorer.
<!DOCTYPE html>
<html> ...
Use the classes found in the java.nio
namespace, in particular, the ByteBuffer
. It can do all the work for you.
byte[] arr = { 0x00, 0x01 };
ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
short num = wrapped.getShort(); // 1
ByteBuffer dbuf = ByteBuffer.allocate(2);
dbuf.putShort(num);
byte[] bytes = dbuf.array(); // { 0, 1 }
Here is a version of the currently accepted answer (from @Trevor) with key instead of keyCode:
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
}
});
Detect OS Version:
public static string OS_Name()
{
return (string)(from x in new ManagementObjectSearcher(
"SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>()
select x.GetPropertyValue("Caption")).FirstOrDefault();
}
To select data in numerical range you can use BETWEEN
which is inclusive.
SELECT JOB FROM MYTABLE WHERE ID BETWEEN 10 AND 15;
I am not a linux guru, but I believe you want to pipe your list of output files to xargs rm -rf
. I have used something like this in the past with good results. Test on a sample directory first!
EDIT - I might have misunderstood, based on the other answers that are appearing. If you can use wildcards, great. I assumed that your original list that you displayed was generated by a program to give you your "selection", so I thought piping to xargs
would be the way to go.
for complette URL with protocol, servername and parameters:
$base_url = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'];
$url = $base_url . $_SERVER["REQUEST_URI"];
I'm going to assume you are using Web Site Projects. These automatically crawl their project directory and throw everything into source control. There's no way to stop them.
However, don't despair. Web Application Projects don't exhibit this strange and rather unexpected (imho: moronic) behavior. WAP is an addon on for VS2005 and comes direct with VS2008.
As an alternative to changing your projects to WAP, you might consider moving the Assets folder out of Source control and into a TFS Document Library. Only do this IF the project itself doesn't directly use the assets files.
Use the Attribute Equals Selector
var thevalue = 'foo';
var exists = 0 != $('#select-box option[value='+thevalue+']').length;
If the option's value was set via Javascript, that will not work. In this case we can do the following:
var exists = false;
$('#select-box option').each(function(){
if (this.value == 'bar') {
exists = true;
return false;
}
});
Using homebrew (recommended way):
To start:
brew services start mongodb-community
To stop:
brew services stop mongodb-community
On Linux:
java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'
On Mac OSX:
java -XX:+PrintFlagsFinal -version | grep -iE 'heapsize|permsize|threadstacksize'
On Windows:
C:\>java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"
Source: https://www.mkyong.com/java/find-out-your-java-heap-memory-size/
Please use the below kotlin code
webview.setWebViewClient(object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return false
}
})
For more info click here
Try this; bear in mind that JavaScript months are 0-indexed, whilst days are 1-indexed.
var date = new Date('2010-10-11T00:00:00+05:30');_x000D_
alert(((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear());
_x000D_
If you already have a struct.
import (
"bytes"
"encoding/json"
"io"
"net/http"
"os"
)
// .....
type Student struct {
Name string `json:"name"`
Address string `json:"address"`
}
// .....
body := &Student{
Name: "abc",
Address: "xyz",
}
payloadBuf := new(bytes.Buffer)
json.NewEncoder(payloadBuf).Encode(body)
req, _ := http.NewRequest("POST", url, payloadBuf)
client := &http.Client{}
res, e := client.Do(req)
if e != nil {
return e
}
defer res.Body.Close()
fmt.Println("response Status:", res.Status)
// Print the body to the stdout
io.Copy(os.Stdout, res.Body)
Full gist.
The word pure doesn't match to the word hibernate.
It's somewhat straightforward as described in above link.
EntityManager
must be joined to a Transaction
or the unwrap
method will return null
. (Not a good move at all.)// --------------------------------------------------------- EclipseLink
try {
final Connection connection = manager.unwrap(Connection.class);
if (connection != null) { // manage is not in any transaction
return function.apply(connection);
}
} catch (final PersistenceException pe) {
logger.log(FINE, pe, () -> "failed to unwrap as a connection");
}
It should be, basically, done with following codes.
// using vendor specific APIs
final Session session = (Session) manager.unwrap(Session.class);
//return session.doReturningWork<R>(function::apply);
return session.doReturningWork(new ReturningWork<R>() {
@Override public R execute(final Connection connection) {
return function.apply(connection);
}
});
Well, we (at least I) might don't want any vendor-specific dependencies. Proxy comes in rescue.
try {
// See? You shouldn't fire me, ass hole!!!
final Class<?> sessionClass
= Class.forName("org.hibernate.Session");
final Object session = manager.unwrap(sessionClass);
final Class<?> returningWorkClass
= Class.forName("org.hibernate.jdbc.ReturningWork");
final Method executeMethod
= returningWorkClass.getMethod("execute", Connection.class);
final Object workProxy = Proxy.newProxyInstance(
lookup().lookupClass().getClassLoader(),
new Class[]{returningWorkClass},
(proxy, method, args) -> {
if (method.equals(executeMethod)) {
final Connection connection = (Connection) args[0];
return function.apply(connection);
}
return null;
});
final Method doReturningWorkMethod = sessionClass.getMethod(
"doReturningWork", returningWorkClass);
return (R) doReturningWorkMethod.invoke(session, workProxy);
} catch (final ReflectiveOperationException roe) {
logger.log(Level.FINE, roe, () -> "failed to work with hibernate");
}
I'm not sure OpenJPA already serves a way using unwrap(Connection.class)
but can be done with the way described in one of above links.
It's not clear the responsibility of closing the connection. The document (one of above links) seems saying clearly but I'm not good at English.
try {
final Class<?> k = Class.forName(
"org.apache.openjpa.persistence.OpenJPAEntityManager");
if (k.isInstance(manager)) {
final Method m = k.getMethod("getConnection");
try {
try (Connection c = (Connection) m.invoke(manager)) {
return function.apply(c);
}
} catch (final SQLException sqle) {
logger.log(FINE, sqle, () -> "failed to work with openjpa");
}
}
} catch (final ReflectiveOperationException roe) {
logger.log(Level.FINE, roe, () -> "failed to work with openjpa");
}
The steps are very simple and it'll take just few mins. 1.Go to your C drive and in that go to the 'USER' section. 2.Under 'USER' section go to your 'name(e.g-'user1') and then find ".eclipse" folder and delete that folder 3.Along with that folder also delete "eclipse" folder and you can find that you're work has been done completely.
In C++03, aggregate initialization only applies with syntax similar as below, which must be a separate statement and doesn't fit in a ctor initializer.
T var = {...};
You need to set the Identity seed to that value:
CREATE TABLE orders
(
id int IDENTITY(9586,1)
)
To alter an existing table:
ALTER TABLE orders ALTER COLUMN Id INT IDENTITY (9586, 1);
More info on CREATE TABLE (Transact-SQL) IDENTITY (Property)
Going to provide a slightly different answer to those provided so far.
If you have a row for an anonymous user from localhost in your users table ''@'localhost'
then this will be treated as more specific than your user with wildcard'd host 'user'@'%'
. This is why it is necessary to also provide 'user'@'localhost'
.
You can see this explained in more detail at the bottom of this page.
dates_dict[key] = dates_dict.get(key, []).append(date)
sets dates_dict[key]
to None
as list.append
returns None
.
In [5]: l = [1,2,3]
In [6]: var = l.append(3)
In [7]: print var
None
You should use collections.defaultdict
import collections
dates_dict = collections.defaultdict(list)
Basing my answer on assumption that user just wanted to literaaly convert an int
to char
, for example
Input:
int i = 5;
Output:
char c = '5'
This has been already answered above, however if the integer value i > 10
, then need to use char array
.
char[] c = String.valueOf(i).toCharArray();