Solution steps:
Complete and clear example project http://www.codeproject.com/Articles/786085/ASP-NET-MVC-List-Editor-with-Bootstrap-Modals It displays create, edit and delete entity operation modals with bootstrap and also includes code to handle result returned from those entity operations (c#, JSON, javascript)
I found a solution to the problem.
There is an issue reported about gradle build problems, it is not the same, but the solution seems to solve the mergeResourceDebug issues too. (issue here https://code.google.com/p/android/issues/detail?id=56158). In the comments it is stated that the solution is solved in Gradle 0.4.3.
To use Gradle 0.4.3, the build.gradle file needs to be updated manually. (Updating Android Studio does not change the build file)
Here is what I changed In build.gradle:
dependencies {
classpath 'com.android.tools.build:gradle:0.4.3'
}
Since changing this, I have not seen any more mergeDebugResource issues when running my project. Hope this helps!
Edit: to stay up to date with Gradle you can change the version number to 0.4.+
Use an extension method. They're the answer to everything, you know! ;)
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
return dt.AddDays(-1 * diff).Date;
}
}
Which can be used as follows:
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
From Laravel 6, Now It's working with the following command:
composer create-project --prefer-dist laravel/laravel:^7.0 blog
In Java, you just throw the exception you caught, so throw e
rather than just throw
. Java maintains the stack trace.
I searched for a the same solution with a variable instead of the String.
I hope i can help someone with my solution :)
var numb = "3";
$(`#myid[data-tab-id=${numb}]`);
For CentOS, RHEL, Amazon Linux: sudo yum install jq
You can get first and last day of previous month (with timestamp) in SQL Server by executing
--select dateadd(dd,-datepart(dd,getdate())+1,dateadd(mm,-1,getdate())) --first day of previous month
--select dateadd(dd,-datepart(dd,getdate()),getdate()) -- last day of previous month**
It's a new feature called Modules or "semantic import". There's more info in the WWDC 2013 videos for Session 205 and 404. It's kind of a better implementation of the pre-compiled headers. You can use modules with any of the system frameworks in iOS 7 and Mavericks. Modules are a packaging together of the framework executable and its headers and are touted as being safer and more efficient than #import
.
One of the big advantages of using @import
is that you don't need to add the framework in the project settings, it's done automatically. That means that you can skip the step where you click the plus button and search for the framework (golden toolbox), then move it to the "Frameworks" group. It will save many developers from the cryptic "Linker error" messages.
You don't actually need to use the @import
keyword. If you opt-in to using modules, all #import
and #include
directives are mapped to use @import
automatically. That means that you don't have to change your source code (or the source code of libraries that you download from elsewhere). Supposedly using modules improves the build performance too, especially if you haven't been using PCHs well or if your project has many small source files.
Modules are pre-built for most Apple frameworks (UIKit, MapKit, GameKit, etc). You can use them with frameworks you create yourself: they are created automatically if you create a Swift framework in Xcode, and you can manually create a ".modulemap" file yourself for any Apple or 3rd-party library.
You can use code-completion to see the list of available frameworks:
Modules are enabled by default in new projects in Xcode 5. To enable them in an older project, go into your project build settings, search for "Modules" and set "Enable Modules" to "YES". The "Link Frameworks" should be "YES" too:
You have to be using Xcode 5 and the iOS 7 or Mavericks SDK, but you can still release for older OSs (say iOS 4.3 or whatever). Modules don't change how your code is built or any of the source code.
From the WWDC slides:
- Imports complete semantic description of a framework
- Doesn't need to parse the headers
- Better way to import a framework’s interface
- Loads binary representation
- More flexible than precompiled headers
- Immune to effects of local macro definitions (e.g.
#define readonly 0x01
)- Enabled for new projects by default
To explicitly use modules:
Replace #import <Cocoa/Cocoa.h>
with @import Cocoa;
You can also import just one header with this notation:
@import iAd.ADBannerView;
The submodules autocomplete for you in Xcode.
You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.
Here's how you could do it with vanilla JavaScript:
<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>
Keycode 13 is the enter key.
Here's how you could do it with jQuery like as Stackoverflow does:
<textarea class="commentarea"></textarea>
with
$(document).ready(function() {
$('.commentarea').keydown(function(event) {
if (event.which == 13) {
this.form.submit();
event.preventDefault();
}
});
});
$(document).ready(function() {
$('#id').focus();
});
Another option for the same result with ConstraintSet animation:
1) Put all the animated views in one ConstraintLayout
2) Animate it from code like this (if you want some more effects its up to you..this is only example)
menuItem1 and menuItem2 is the first and second FABs in menu, descriptionItem1 and descriptionItem2 is the description to the left of menu, parentConstraintLayout is the root ConstraintLayout wich contains all the animated views, isMenuOpened is some function to change open/closed flag in the state
I put animation code in extension file but its not necessary.
fun FloatingActionButton.expandMenu(
menuItem1: View,
menuItem2: View,
descriptionItem1: TextView,
descriptionItem2: TextView,
parentConstraintLayout: ConstraintLayout,
isMenuOpened: (Boolean)-> Unit
) {
val constraintSet = ConstraintSet()
constraintSet.clone(parentConstraintLayout)
constraintSet.setVisibility(descriptionItem1.id, View.VISIBLE)
constraintSet.clear(menuItem1.id, ConstraintSet.TOP)
constraintSet.connect(menuItem1.id, ConstraintSet.BOTTOM, this.id, ConstraintSet.TOP, 0)
constraintSet.connect(menuItem1.id, ConstraintSet.START, this.id, ConstraintSet.START, 0)
constraintSet.connect(menuItem1.id, ConstraintSet.END, this.id, ConstraintSet.END, 0)
constraintSet.setVisibility(descriptionItem2.id, View.VISIBLE)
constraintSet.clear(menuItem2.id, ConstraintSet.TOP)
constraintSet.connect(menuItem2.id, ConstraintSet.BOTTOM, menuItem1.id, ConstraintSet.TOP, 0)
constraintSet.connect(menuItem2.id, ConstraintSet.START, this.id, ConstraintSet.START, 0)
constraintSet.connect(menuItem2.id, ConstraintSet.END, this.id, ConstraintSet.END, 0)
val transition = AutoTransition()
transition.duration = 150
transition.interpolator = AccelerateInterpolator()
transition.addListener(object: Transition.TransitionListener {
override fun onTransitionEnd(p0: Transition) {
isMenuOpened(true)
}
override fun onTransitionResume(p0: Transition) {}
override fun onTransitionPause(p0: Transition) {}
override fun onTransitionCancel(p0: Transition) {}
override fun onTransitionStart(p0: Transition) {}
})
TransitionManager.beginDelayedTransition(parentConstraintLayout, transition)
constraintSet.applyTo(parentConstraintLayout)
}
You can use an anonymous function to pass the matches to your function:
$result = preg_replace_callback(
"/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
$result
);
Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e
would convert a double quote "
into \"
.
I dont think you should use the tag on the news item summary (lines 67, 80, 93). You could use section or just have the enclosing div.
An article needs to be able to stand on its own & still make sense or be complete. As its incomplete or just an extract it cannot be an article, its more a section.
When you click 'read more' the subsequent page can
Try to remove the .idea
folder and .gradle
folder, then click Sync Project with Gradle Files
, when the process finished, try to run app again.
Hope it works.
Well, not always. Using cookies, you are good. But the "can I safely rely on the id being present" urged me to extend the discussion with an important point (mostly for reference, as the visitor count of this page seems quite high).
PHP can be configured to maintain sessions by URL-rewriting, instead of cookies. (How it's good or bad (<-- see e.g. the topmost comment there) is a separate question, let's now stick to the current one, with just one side-note: the most prominent issue with URL-based sessions -- the blatant visibility of the naked session ID -- is not an issue with internal Ajax calls; but then, if it's turned on for Ajax, it's turned on for the rest of the site, too, so there...)
In case of URL-rewriting (cookieless) sessions, Ajax calls must take care of it themselves that their request URLs are properly crafted. (Or you can roll your own custom solution. You can even resort to maintaining sessions on the client side, in less demanding cases.) The point is the explicit care needed for session continuity, if not using cookies:
If the Ajax calls just extract URLs verbatim from the HTML (as received from PHP), that should be OK, as they are already cooked (umm, cookified).
If they need to assemble request URIs themselves, the session ID needs to be added to the URL manually. (Check here, or the page sources generated by PHP (with URL-rewriting on) to see how to do it.)
From OWASP.org:
Effectively, the web application can use both mechanisms, cookies or URL parameters, or even switch from one to the other (automatic URL rewriting) if certain conditions are met (for example, the existence of web clients without cookies support or when cookies are not accepted due to user privacy concerns).
From a Ruby-forum post:
When using php with cookies, the session ID will automatically be sent in the request headers even for Ajax XMLHttpRequests. If you use or allow URL-based php sessions, you'll have to add the session id to every Ajax request url.
There is no guarantee that a GUID contains alpha characters. FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF
is a valid GUID so is 00000000-0000-0000-0000-000000000000
and anything in between.
If you are using .NET 4.0, you can use the answer above for the Guid.Parse and Guid.TryParse. Otherwise, you can do something like this:
public static bool TryParseGuid(string guidString, out Guid guid)
{
if (guidString == null) throw new ArgumentNullException("guidString");
try
{
guid = new Guid(guidString);
return true;
}
catch (FormatException)
{
guid = default(Guid);
return false;
}
}
Use PHP's strip_tags() function.
For example:
$businessDesc = strip_tags($row_get_Business['business_description']);
$businessDesc = substr($businessDesc, 0, 110);
print($businessDesc);
Try this out. Hope this helps
<div id="single" dir="rtl">
<div class="common">Single</div>
</div>
<div id="both" dir="ltr">
<div class="common">Both</div>
</div>
#single, #both{
width: 100px;
height: 100px;
overflow: auto;
margin: 0 auto;
border: 1px solid gray;
}
.common{
height: 150px;
width: 150px;
}
If you wish to have a relatively pain-free experience you can also have a look at the Apache Commons IO package, more specifically the FileUtils
class.
Never forget to check third-party libraries. Joda-Time for date manipulation, Apache Commons Lang StringUtils
for common string operations and such can make your code more readable.
Java is a great language, but the standard library is sometimes a bit low-level. Powerful, but low-level nonetheless.
Something like this would work
/^\d{2}$/
Little js-hacky but works: e[String(e.hello)]
In a situation where you have this:
enum fruit {
apple,
orange,
grape,
banana,
// etc.
};
I like to put this in the header file where the enum is defined:
static inline char *stringFromFruit(enum fruit f)
{
static const char *strings[] = { "apple", "orange", "grape", "banana", /* continue for rest of values */ };
return strings[f];
}
For "100% of the browser window", if you mean this literally, you should use fixed positioning. The top, bottom, right, and left properties are then used to offset the divs edges from the respective edges of the viewport:
#nav, #content{position:fixed;top:0px;bottom:0px;}
#nav{left:0px;right:235px;}
#content{left:235px;right:0px}
This will set up a screen with the left 235 pixels devoted to the nav, and the right rest of the screen to content.
Note, however, you won't be able to scroll the whole screen at once. Though you can set it to scroll either pane individually, by applying overflow:auto
to either div.
Note also: fixed positioning is not supported in IE6 or earlier.
It's pretty user friendly. Just work with NSFileManager's defaultManager singleton and then use the fileExistsAtPath()
method, which simply takes a string as an argument, and returns a Bool, allowing it to be placed directly in the if statement.
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentDirectory = paths[0] as! String
let myFilePath = documentDirectory.stringByAppendingPathComponent("nameOfMyFile")
let manager = NSFileManager.defaultManager()
if (manager.fileExistsAtPath(myFilePath)) {
// it's here!!
}
Note that the downcast to String isn't necessary in Swift 2.
I was looking around for an answer on bulk inserting Objects.
The answer by Ragnar123 led me to making this function:
function bulkInsert(connection, table, objectArray, callback) {
let keys = Object.keys(objectArray[0]);
let values = objectArray.map( obj => keys.map( key => obj[key]));
let sql = 'INSERT INTO ' + table + ' (' + keys.join(',') + ') VALUES ?';
connection.query(sql, [values], function (error, results, fields) {
if (error) callback(error);
callback(null, results);
});
}
bulkInsert(connection, 'my_table_of_objects', objectArray, (error, response) => {
if (error) res.send(error);
res.json(response);
});
Hope it helps!
Setting the HttpWebRequest.KeepAlive
to false
didn't work for me.
Since I was accessing a HTTPS page I had to set the Service Point Security Protocol to Tls12.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Notice that there are other SecurityProtocolTypes
: SecurityProtocolType.Ssl3
, SecurityProtocolType.Tls
, SecurityProtocolType.Tls11
So if the Tls12 doesn't work for you, try the three remaining options.
Also notice that you can set multiple protocols. This is preferable on most cases.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
Edit: Since this is a choice of security standards it's obviously best to go with the latest (TLS 1.2 as of writing this), and not just doing what works. In fact, SSL3 has been officially prohibited from use since 2015 and TLS 1.0 and TLS 1.1 will likely be prohibited soon as well. source: @aske-b
On a Windows 8.1 machine I got Send-MailMessage to send an email with an attachment through Gmail using the following script:
$EmFrom = "[email protected]"
$username = "[email protected]"
$pwd = "YOURPASSWORD"
$EmTo = "[email protected]"
$Server = "smtp.gmail.com"
$port = 587
$Subj = "Test"
$Bod = "Test 123"
$Att = "c:\Filename.FileType"
$securepwd = ConvertTo-SecureString $pwd -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $securepwd
Send-MailMessage -To $EmTo -From $EmFrom -Body $Bod -Subject $Subj -Attachments $Att -SmtpServer $Server -port $port -UseSsl -Credential $cred
Assuming you did not commit the file, or add it to the index, then:
git checkout -- filename
Assuming you added it to the index, but did not commit it, then:
git reset HEAD filename
git checkout -- filename
Assuming you did commit it, then:
git checkout origin/master filename
Assuming you want to blow away all commits from your branch (VERY DESTRUCTIVE):
git reset --hard origin/master
in the spotlight, search for Activity Monitor. You can force fully remove any application from here.
No extensions are needed, just use these two functions for simple profiling.
// Call this at each point of interest, passing a descriptive string
function prof_flag($str)
{
global $prof_timing, $prof_names;
$prof_timing[] = microtime(true);
$prof_names[] = $str;
}
// Call this when you're done and want to see the results
function prof_print()
{
global $prof_timing, $prof_names;
$size = count($prof_timing);
for($i=0;$i<$size - 1; $i++)
{
echo "<b>{$prof_names[$i]}</b><br>";
echo sprintf(" %f<br>", $prof_timing[$i+1]-$prof_timing[$i]);
}
echo "<b>{$prof_names[$size-1]}</b><br>";
}
Here is an example, calling prof_flag() with a description at each checkpoint, and prof_print() at the end:
prof_flag("Start");
include '../lib/database.php';
include '../lib/helper_func.php';
prof_flag("Connect to DB");
connect_to_db();
prof_flag("Perform query");
// Get all the data
$select_query = "SELECT * FROM data_table";
$result = mysql_query($select_query);
prof_flag("Retrieve data");
$rows = array();
$found_data=false;
while($r = mysql_fetch_assoc($result))
{
$found_data=true;
$rows[] = $r;
}
prof_flag("Close DB");
mysql_close(); //close database connection
prof_flag("Done");
prof_print();
Output looks like this:
Start
0.004303
Connect to DB
0.003518
Perform query
0.000308
Retrieve data
0.000009
Close DB
0.000049
Done
In case you want to find other node besides "Alpha", the query should be something like this:
select Roles from MyTable where Roles.exist('(/*:root/*:role[contains(.,"Beta")])') = 1
Alternatively to German Attanasio Ruiz's answer, you can eliminate the 2nd loop by using Array.reduce() instead of Array.map();
var Data = [
{ name: 'hypno7oad' }
]
var indexOfTarget = Data.reduce(function (indexOfTarget, element, currentIndex) {
return (element.name === 'hypno7oad') ? currentIndex : indexOfTarget;
}, -1);
I would suggest using a StreamingResponseBody since with it the application can write directly to the response (OutputStream) without holding up the Servlet container thread. It is a good approach if you are downloading a file very large.
@GetMapping("download")
public StreamingResponseBody downloadFile(HttpServletResponse response, @PathVariable Long fileId) {
FileInfo fileInfo = fileService.findFileInfo(fileId);
response.setContentType(fileInfo.getContentType());
response.setHeader(
HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + fileInfo.getFilename() + "\"");
return outputStream -> {
int bytesRead;
byte[] buffer = new byte[BUFFER_SIZE];
InputStream inputStream = fileInfo.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
};
}
Ps.: When using StreamingResponseBody, it is highly recommended to configure TaskExecutor used in Spring MVC for executing asynchronous requests. TaskExecutor is an interface that abstracts the execution of a Runnable.
More info: https://medium.com/swlh/streaming-data-with-spring-boot-restful-web-service-87522511c071
For me the problem was solved by stocking my datas into an object (here "datas").
NgApp.controller('MyController', function($scope) {_x000D_
_x000D_
$scope.my_title = ""; // This don't work in ng-click function called_x000D_
_x000D_
$scope.datas = {_x000D_
'my_title' : "",_x000D_
};_x000D_
_x000D_
$scope.doAction = function() {_x000D_
console.log($scope.my_title); // bad value_x000D_
console.log($scope.datas.my_title); // Good Value binded by'ng-model'_x000D_
}_x000D_
_x000D_
_x000D_
});
_x000D_
I Hop it will help
Always open in binary mode, in this case
file = open("Fruits.obj",'rb')
Nobody has explained the difference between ExceptionDispatchInfo.Capture( ex ).Throw()
and a plain throw
, so here it is. However, some people have noticed the problem with throw
.
The complete way to rethrow a caught exception is to use ExceptionDispatchInfo.Capture( ex ).Throw()
(only available from .Net 4.5).
Below there are the cases necessary to test this:
1.
void CallingMethod()
{
//try
{
throw new Exception( "TEST" );
}
//catch
{
// throw;
}
}
2.
void CallingMethod()
{
try
{
throw new Exception( "TEST" );
}
catch( Exception ex )
{
ExceptionDispatchInfo.Capture( ex ).Throw();
throw; // So the compiler doesn't complain about methods which don't either return or throw.
}
}
3.
void CallingMethod()
{
try
{
throw new Exception( "TEST" );
}
catch
{
throw;
}
}
4.
void CallingMethod()
{
try
{
throw new Exception( "TEST" );
}
catch( Exception ex )
{
throw new Exception( "RETHROW", ex );
}
}
Case 1 and case 2 will give you a stack trace where the source code line number for the CallingMethod
method is the line number of the throw new Exception( "TEST" )
line.
However, case 3 will give you a stack trace where the source code line number for the CallingMethod
method is the line number of the throw
call. This means that if the throw new Exception( "TEST" )
line is surrounded by other operations, you have no idea at which line number the exception was actually thrown.
Case 4 is similar with case 2 because the line number of the original exception is preserved, but is not a real rethrow because it changes the type of the original exception.
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Hello world" />
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gud bye" />
In ipython
you can type "import
Tab".
In the standard Python interpreter, you can type "help('modules')
".
At the command-line, you can use pydoc
modules
.
In a script, call pkgutil.iter_modules()
.
I've had issues with using SELECT last_insert_rowid()
in a multithreaded environment. If another thread inserts into another table that has an autoinc, last_insert_rowid will return the autoinc value from the new table.
Here's where they state that in the doco:
If a separate thread performs a new INSERT on the same database connection while the sqlite3_last_insert_rowid() function is running and thus changes the last insert rowid, then the value returned by sqlite3_last_insert_rowid() is unpredictable and might not equal either the old or the new last insert rowid.
That's from sqlite.org doco
I realize it is a bit late, but I couldn't find a good answer that worked with ASP.NET AJAX, so I fixed the code above:
function ToUpper() {
// So that things work both on FF and IE
var evt = arguments[0] || event;
var char = String.fromCharCode(evt.which || evt.keyCode);
// Is it a lowercase character?
if (/[a-z]/.test(char)) {
// convert to uppercase version
if (evt.which) {
evt.which = char.toUpperCase().charCodeAt(0);
}
else {
evt.keyCode = char.toUpperCase().charCodeAt(0);
}
}
return true;
}
Used like so:
<asp:TextBox ID="txtAddManager" onKeyPress="ToUpper()" runat="server"
Width="84px" Font-Names="Courier New"></asp:TextBox>
I think one error in the original code might have been that it had:
$message = echo getRequestURI();
instead of:
$message = getRequestURI();
(The code has since been edited though.)
Alt + Shift + F10 will show the menu associated with the smart tag.
While you are in it, I suggest to remember some key facts about compareTo() methods
CompareTo must be in consistent with equals method e.g. if two objects are equal via equals() , there compareTo() must return zero otherwise if those objects are stored in SortedSet or SortedMap they will not behave properly.
CompareTo() must throw NullPointerException if current object get compared to null object as opposed to equals() which return false on such scenario.
Read more: http://javarevisited.blogspot.com/2011/11/how-to-override-compareto-method-in.html#ixzz4B4EMGha3
It is rule of thumb that the first layer in your network should be the same shape as your data. For example our data is 28x28 images, and 28 layers of 28 neurons would be infeasible, so it makes more sense to 'flatten' that 28,28 into a 784x1. Instead of wriitng all the code to handle that ourselves, we add the Flatten() layer at the begining, and when the arrays are loaded into the model later, they'll automatically be flattened for us.
You can use jasper report.
iReport is a very effective tool to develop jasper reports.
It supports almost all the facilities provided by crystal report like formatting, grouping, creation of charts etc.
Refer the link for tutorial:
Two issues:
You're passing the jQuery wrapper of the element into parseInt
, which isn't what you want, as parseInt
will call toString
on it and get back "[object Object]"
. You need to use val
or text
or something (depending on what the element is) to get the string you want.
You're not telling parseInt
what radix (number base) it should use, which puts you at risk of odd input giving you odd results when parseInt
guesses which radix to use.
Fix if the element is a form field:
// vvvvv-- use val to get the value
var test = parseInt($("#testid").val(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
Fix if the element is something else and you want to use the text within it:
// vvvvvv-- use text to get the text
var test = parseInt($("#testid").text(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
Google recently changed the terms of use of its Google Maps APIs; if you were already using them on a website (different from localhost) prior to June 22nd, 2016, nothing will change for you; otherwise, you will get the aforementioned issue and need an API key in order to fix your error. The free API key is valid up to 25,000 map loads per day.
In this article you will find everything you may need to know regarding the topic, including a tutorial to fix your error:
Google Maps API error: MissingKeyMapError [SOLVED]
Also, remember to replace YOUR_API_KEY with your actual API key!
I wanted to add an import path, for another project elsewhere in my workspace. MacOS Catalina 10.15.5 PyCharm Community 2020.1.1
PyCharm - Preferences - Project interpreter - Cog symbol - Show All
At the bottom of that dialog, it shows 5 buttons: Plus, Minus, Pencil, Funnel, and Directory tree.
Click Directory tree. You can now use the Plus button in the new dialog to add your 'external library' search path.
If successful, you should now see the directory name in the "External Libraries" pane in the Project panel.
Python's sets (and dictionaries) will iterate and print out in some order, but exactly what that order will be is arbitrary, and not guaranteed to remain the same after additions and removals.
Here's an example of a set changing order after a lot of values are added and then removed:
>>> s = set([1,6,8])
>>> print(s)
{8, 1, 6}
>>> s.update(range(10,100000))
>>> for v in range(10, 100000):
s.remove(v)
>>> print(s)
{1, 6, 8}
This is implementation dependent though, and so you should not rely upon it.
It's either through system property
-Dorg.slf4j.simpleLogger.defaultLogLevel=debug
or simplelogger.properties
file on the classpath
see http://www.slf4j.org/api/org/slf4j/impl/SimpleLogger.html for details
You have to catch the SIGINT signal (we are talking POSIX right?)
See @Gab Royer´s answer for sigaction.
Example:
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
void my_handler(sig_t s){
printf("Caught signal %d\n",s);
exit(1);
}
int main(int argc,char** argv)
{
signal (SIGINT,my_handler);
while(1);
return 0;
}
well these are specified by the w3c what is an attribute and what is a property http://www.w3.org/TR/SVGTiny12/attributeTable.html
but currently attr and prop are not so different and there are almost the same
but they prefer prop for some things
Summary of Preferred Usage
The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.
well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)
This should work
return RedirectToAction("actionName", "controllerName", null);
Use "&
" instead of "&".
Late reading this, but.. The way I read your question, you only need to change two lines of code:
Accept user input, function writes back on screen.
<input type="text" id="userInput"=> give me input</input>
<button onclick="test()">Submit</button>
<!-- add this line for function to write into -->
<p id="demo"></p>
<script type="text/javascript">
function test(){
var userInput = document.getElementById("userInput").value;
document.getElementById("demo").innerHTML = userInput;
}
</script>
I tried it by recursively appending each script
Note If your scripts are dependent one after other, then position will need to be in sync.
Major Dependency should be in last in array so that initial scripts can use it
const scripts = ['https://www.gstatic.com/firebasejs/6.2.0/firebase-storage.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js']_x000D_
let count = 0_x000D_
_x000D_
_x000D_
const recursivelyAddScript = (script, cb) => {_x000D_
const el = document.createElement('script')_x000D_
el.src = script_x000D_
if(count < scripts.length) {_x000D_
count ++_x000D_
el.onload = recursivelyAddScript(scripts[count])_x000D_
document.body.appendChild(el)_x000D_
} else {_x000D_
console.log('All script loaded')_x000D_
return_x000D_
}_x000D_
}_x000D_
_x000D_
recursivelyAddScript(scripts[count])
_x000D_
The most straight-forward way I can think of is using numpy's gradient function:
x = numpy.linspace(0,10,1000)
dx = x[1]-x[0]
y = x**2 + 1
dydx = numpy.gradient(y, dx)
This way, dydx will be computed using central differences and will have the same length as y, unlike numpy.diff, which uses forward differences and will return (n-1) size vector.
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)
Using the path /inout-tracker
without a trailing /
doesn't fetch index.php
. Instead the server will issue a 302
redirect to the version with the trailing /
.
Doing a 302 will typically cause clients to convert a POST to a GET request.
This example might help you. by using simple casting you can get code behind urdu character.
string str = "?????";
char ch = ' ';
int number = 0;
for (int i = 0; i < str.Length; i++)
{
ch = str[i];
number = (int)ch;
Console.WriteLine(number);
}
I will explain it verbally first and then with an example:
A pointer object can be declared as a const pointer or a pointer to a const object (or both):
A const pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can be used to modify the object that it points to (called the "pointee").
Reference variables are thus an alternate syntax for constpointers.
A pointer to a const object, on the other hand, can be reassigned to point to another object of the same type or of a convertible type, but it cannot be used to modify any object.
A const pointer to a const object can also be declared and can neither be used to modify the pointee nor be reassigned to point to another object.
Example:
void Foo( int * ptr,
int const * ptrToConst,
int * const constPtr,
int const * const constPtrToConst )
{
*ptr = 0; // OK: modifies the "pointee" data
ptr = 0; // OK: modifies the pointer
*ptrToConst = 0; // Error! Cannot modify the "pointee" data
ptrToConst = 0; // OK: modifies the pointer
*constPtr = 0; // OK: modifies the "pointee" data
constPtr = 0; // Error! Cannot modify the pointer
*constPtrToConst = 0; // Error! Cannot modify the "pointee" data
constPtrToConst = 0; // Error! Cannot modify the pointer
}
Happy to help! Good Luck!
This worked for me (I'm using VS Code):
for:
This is just\na simple sentence
Use:
This .+ sentence
Returns an integer random number between min (included) and max (included):
function randomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Or any random number between min (included) and max (not included):
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
Useful examples (integers):
// 0 -> 10
Math.floor(Math.random() * 11);
// 1 -> 10
Math.floor(Math.random() * 10) + 1;
// 5 -> 20
Math.floor(Math.random() * 16) + 5;
// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;
** And always nice to be reminded (Mozilla):
Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.
Another way to achieve the same outcome, which I found useful for a pandas dataframe.
As suggested below by mousetail:
bool(1 - False)
bool(1 - True)
Yes you can use SQL Server 2008 itself but you need to install SQL Server Management Studio Express (if not installed ) . Just right Click on Database Diagrams and create new diagram. Select the exisiting tables and if you have specified the references in your tables properly. You will be able to see the complete diagram of selected tables. For further reference see Getting started with SQL Server database diagrams
Also, I'm using following solution:
$('a[data-toggle="tab"]').on('click', function(){
if ($(this).parent('li').hasClass('disabled')) {
return false;
};
});
Now you just adding class 'disabled' to the parent li and tab doesn't work and become gray.
Issue: Tomcat (7.0.88) is throwing below exception which leads to 400 – Bad Request.
java.lang.IllegalArgumentException: Invalid character found in the request target.
The valid characters are defined in RFC 7230 and RFC 3986.
This issue is occurring most of the tomcat versions from 7.0.88 onwards.
Solution: (Suggested by Apache team):
Tomcat increased their security and no longer allows raw square brackets in the query string. In the request we have [,] (Square brackets) so the request is not processed by the server.
Add relaxedQueryChars
attribute under tag under server.xml (%TOMCAT_HOME%/conf):
<Connector port="80"
protocol="HTTP/1.1"
maxThreads="150"
connectionTimeout="20000"
redirectPort="443"
compression="on"
compressionMinSize="2048"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml"
relaxedQueryChars="[,]"
/>
If application needs more special characters that are not supported by tomcat by default, then add those special characters in relaxedQueryChars
attribute, comma-separated as above.
just a recursive deep copy function.
def deepcopy(A):
rt = []
for elem in A:
if isinstance(elem,list):
rt.append(deepcopy(elem))
else:
rt.append(elem)
return rt
Edit: As Cfreak mentioned, this is already implemented in copy
module.
After the last Firefox update we had the same session timeout issue and the following setting helped to resolve it.
We can control it with network.http.response.timeout
parameter.
network.http.response.timeout
parameter will be displayed.network.http.response.timeout
parameter and enter the time value (it is in seconds) that you don't want your session not to timeout, in the box.I think you need to have strings as the data values. It's likely something internally within jQuery that isn't encoding/serializing correctly the To & From Objects.
Try:
var data = {
from : from.val(),
to : to.val(),
speed : speed
};
Notice also on the lines:
$(from).css(...
$(to).css(
You don't need the jQuery wrapper as To & From are already jQuery objects.
Just use the --python
(or short -p
) option when creating your virtualenv instance to specify the Python executable you want to use, e.g.:
virtualenv --python=/usr/bin/python2.6 <path/to/new/virtualenv/>
N.B. For Python 3.3 or later, refer to The Aelfinn's answer below.
The problem is you're telling Gson
you have an object of your type. You don't. You have an array of objects of your type. You can't just try and cast the result like that and expect it to magically work ;)
The User guide for Gson
Explains how to deal with this:
https://github.com/google/gson/blob/master/UserGuide.md
This will work:
ChannelSearchEnum[] enums = gson.fromJson(yourJson, ChannelSearchEnum[].class);
But this is better:
Type collectionType = new TypeToken<Collection<ChannelSearchEnum>>(){}.getType();
Collection<ChannelSearchEnum> enums = gson.fromJson(yourJson, collectionType);
As a complementary, to produce patch for only one specific commit, use:
git format-patch -1 <sha>
When the patch file is generated, make sure your other repo knows where it is when you use git am ${patch-name}
Before adding the patch, use git apply --check ${patch-name}
to make sure that there is no confict.
Update
Inspired by Daniel's code above and the fact that this is WAY! more interesting to me now then the actual work I have to do, i created a hopefully full-proof function to find the first blank row in a sheet. Improvements welcome! Otherwise, this is going to my library :) Hopefully others benefit as well.
Function firstBlankRow(ws As Worksheet) As Long
'returns the row # of the row after the last used row
'Or the first row with no data in it
Dim rngSearch As Range, cel As Range
With ws
Set rngSearch = .UsedRange.Columns(1).Find("") '-> does blank exist in the first column of usedRange
If Not rngSearch Is Nothing Then
Set rngSearch = .UsedRange.Columns(1).SpecialCells(xlCellTypeBlanks)
For Each cel In rngSearch
If Application.WorksheetFunction.CountA(cel.EntireRow) = 0 Then
firstBlankRow = cel.Row
Exit For
End If
Next
Else '-> no blanks in first column of used range
If Application.WorksheetFunction.CountA(Cells(.Rows.Count, 1).EntireRow) = 0 Then '-> is the last row of the sheet blank?
'-> yeap!, then no blank rows!
MsgBox "Whoa! All rows in sheet are used. No blank rows exist!"
Else
'-> okay, blank row exists
firstBlankRow = .UsedRange.SpecialCells(xlCellTypeBlanks).Row + 1
End If
End If
End With
End Function
Original Answer
To find the first blank in a sheet, replace this part of your code:
Cells(1, 1).Select
For Each Cell In ws.UsedRange.Cells
If Cell.Value = "" Then Cell = Num
MsgBox "Checking cell " & Cell & " for value."
Next
With this code:
With ws
Dim rngBlanks As Range, cel As Range
Set rngBlanks = Intersect(.UsedRange, .Columns(1)).Find("")
If Not rngBlanks Is Nothing Then '-> make sure blank cell exists in first column of usedrange
'-> find all blank rows in column A within the used range
Set rngBlanks = Intersect(.UsedRange, .Columns(1)).SpecialCells(xlCellTypeBlanks)
For Each cel In rngBlanks '-> loop through blanks in column A
'-> do a countA on the entire row, if it's 0, there is nothing in the row
If Application.WorksheetFunction.CountA(cel.EntireRow) = 0 Then
num = cel.Row
Exit For
End If
Next
Else
num = usedRange.SpecialCells(xlCellTypeLastCell).Offset(1).Row
End If
End With
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
I faced same issue in eclipse neon simple maven java project
But I add below details inside pom.xml file
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
After right click on project > maven > update project (checked force update)
Its resolve me to display error on project
Hope it's will helpful
Thansk
use the following rule for validating radio button group selection
myRadioGroupName : {required :true}
myRadioGroupName is the value you have given to name attribute
In CMD, type:
pip freeze
And it will show you a list of all the modules installed including the version number.
Output:
aiohttp==1.1.4
async-timeout==1.1.0
cx-Freeze==4.3.4
Django==1.9.2
django-allauth==0.24.1
django-cors-headers==1.2.2
django-crispy-forms==1.6.0
django-robots==2.0
djangorestframework==3.3.2
easygui==0.98.0
future==0.16.0
httpie==0.9.6
matplotlib==1.5.3
multidict==2.1.2
numpy==1.11.2
oauthlib==1.0.3
pandas==0.19.1
pefile==2016.3.28
pygame==1.9.2b1
Pygments==2.1.3
PyInstaller==3.2
pyparsing==2.1.10
pypiwin32==219
PyQt5==5.7
pytz==2016.7
requests==2.9.1
requests-oauthlib==0.6
six==1.10.0
sympy==1.0
virtualenv==15.0.3
xlrd==1.0.0
yarl==0.7.0
Please do not depend on casting as a solution, even though others are suggesting this as a valid option to prevent an error, it might cause another one.
Be aware: If you expect a specific form of array to be returned, this might fail you. More checks are required for that.
E.g. casting a boolean to an array
(array)bool
, will NOT result in an empty array, but an array with one element containing the boolean value as an int:[0=>0]
or[0=>1]
.
I wrote a quick test to present this problem. (Here is a backup Test in case the first test url fails.)
Included are tests for: null
, false
, true
, a class
, an array
and undefined
.
Always test your input before using it in foreach. Suggestions:
$array = is_array($var) or is_object($var) ? $var : [] ;
try{}catch(){}
blocksarray_key_exists
on a specific key, or test the depth of an array (when it is one !).ES6(ES2015)
way!we need keeping up with the times!
const old_obj = {_x000D_
k1: `111`,_x000D_
k2: `222`,_x000D_
k3: `333`_x000D_
};_x000D_
console.log(`old_obj =\n`, old_obj);_x000D_
// {k1: "111", k2: "222", k3: "333"}_x000D_
_x000D_
_x000D_
/**_x000D_
* @author xgqfrms_x000D_
* @description ES6 ...spread & Destructuring Assignment_x000D_
*/_x000D_
_x000D_
const {_x000D_
k1: kA, _x000D_
k2: kB, _x000D_
k3: kC,_x000D_
} = {...old_obj}_x000D_
_x000D_
console.log(`kA = ${kA},`, `kB = ${kB},`, `kC = ${kC}\n`);_x000D_
// kA = 111, kB = 222, kC = 333_x000D_
_x000D_
const new_obj = Object.assign(_x000D_
{},_x000D_
{_x000D_
kA,_x000D_
kB,_x000D_
kC_x000D_
}_x000D_
);_x000D_
_x000D_
console.log(`new_obj =\n`, new_obj);_x000D_
// {kA: "111", kB: "222", kC: "333"}
_x000D_
With the recent release of bootstrap 3, and the glyphicons being merged back to the main Bootstrap repo, Bootstrap CDN is now serving the complete Bootstrap 3.0 css including Glyphicons. The Bootstrap css reference is all you need to include: Glyphicons and its dependencies are on relative paths on the CDN site and are referenced in bootstrap.min.css
.
In html:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
In css:
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");
Here is a working demo.
Note that you have to use .glyphicon
classes instead of .icon
:
Example:
<span class="glyphicon glyphicon-heart"></span>
Also note that you would still need to include bootstrap.min.js
for usage of Bootstrap JavaScript components, see Bootstrap CDN for url.
If you want to use the Glyphicons separately, you can do that by directly referencing the Glyphicons css on Bootstrap CDN.
In html:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">
In css:
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css");
Since the css
file already includes all the needed Glyphicons dependencies (which are in a relative path on the Bootstrap CDN site), adding the css
file is all there is to do to start using Glyphicons.
Here is a working demo of the Glyphicons without Bootstrap.
The error means that you are providing not as much data as the table wp_posts
does contain columns. And now the DB engine does not know in which columns to put your data.
To overcome this you must provide the names of the columns you want to fill. Example:
insert into wp_posts (column_name1, column_name2)
values (1, 3)
Look up the table definition and see which columns you want to fill.
And insert
means you are inserting a new record. You are not modifying an existing one. Use update
for that.
Seems like some kind of keyboard mapping bug. I'm Portuguese, so I'm using a PT/PT keyboard. Sublime Text 3 apparently is handling / as ~.
I liked James Jenkins reply with the ISNULL check, but I think he meant IFNULL. ISNULL does not have a second parameter like his syntax, but IFNULL has the second parameter after the expression being checked to substitute if a NULL is found.
For saving the graph:
matplotlib.rcParams['savefig.dpi'] = 300
For displaying the graph when you use plt.show()
:
matplotlib.rcParams["figure.dpi"] = 100
Just add them at the top
As einpoklum mentioned in their answer, since C++17 you can also use structured binding declarations. I want to extend on that by providing a full solution for iterating over a map of maps in a comfortable way:
int main() {
std::map<std::string, std::map<std::string, std::string>> m {
{"name1", {{"value1", "data1"}, {"value2", "data2"}}},
{"name2", {{"value1", "data1"}, {"value2", "data2"}}},
{"name3", {{"value1", "data1"}, {"value2", "data2"}}}
};
for (const auto& [k1, v1] : m)
for (const auto& [k2, v2] : v1)
std::cout << "m[" << k1 << "][" << k2 << "]=" << v2 << std::endl;
return 0;
}
Note 1: For filling the map, I used an initializer list (which is a C++11 feature). This can sometimes be handy to keep fixed initializations compact.
Note 2: If you want to modify the map m
within the loops, you have to remove the const
keywords.
If you don't mind including the underscore as an allowed character, you could try simply:
result = subject.replace(/\W+/g, "");
If the underscore must be excluded also, then
result = subject.replace(/[^A-Z0-9]+/ig, "");
(Note the case insensitive flag)
Just reorder or make sure, the (DOM or HTML) is loaded before the JavaScript.
You can also invoke methods inside the created object.
You can create object instant by invoking the first constractor and then invoke the first method in the created object.
Class<?> c = Class.forName("mypackage.MyClass");
Constructor<?> ctor = c.getConstructors()[0];
Object object=ctor.newInstance(new Object[]{"ContstractorArgs"});
c.getDeclaredMethods()[0].invoke(object,Object... MethodArgs);
Just go to vmvare edit->preferences->shared vms. Click on change settings and disable sharing.click on OK.xampp will work fine.
>>> print "{:.2f}".format(1.123456)
1.12
You can change 2
in 2f
to any number of decimal points you want to show.
From Python3.6
, this translates to:
>>> print(f"{1.1234:.2f}")
1.12
I do it like Bradley Braithwaite suggests in his blog:
app
.factory('searchService', ['$q', '$http', function($q, $http) {
var service = {};
service.search = function search(query) {
// We make use of Angular's $q library to create the deferred instance
var deferred = $q.defer();
$http
.get('http://localhost/v1?=q' + query)
.success(function(data) {
// The promise is resolved once the HTTP call is successful.
deferred.resolve(data);
})
.error(function(reason) {
// The promise is rejected if there is an error with the HTTP call.
deferred.reject(reason);
});
// The promise is returned to the caller
return deferred.promise;
};
return service;
}])
.controller('SearchController', ['$scope', 'searchService', function($scope, searchService) {
// The search service returns a promise API
searchService
.search($scope.query)
.then(function(data) {
// This is set when the promise is resolved.
$scope.results = data;
})
.catch(function(reason) {
// This is set in the event of an error.
$scope.error = 'There has been an error: ' + reason;
});
}])
Key Points:
The resolve function links to the .then function in our controller i.e. all is well, so we can keep our promise and resolve it.
The reject function links to the .catch function in our controller i.e. something went wrong, so we can’t keep our promise and need to reject it.
It is quite stable and safe and if you have other conditions to reject the promise you can always filter your data in the success function and call deferred.reject(anotherReason)
with the reason of the rejection.
As Ryan Vice suggested in the comments, this may not be seen as useful unless you fiddle a bit with the response, so to speak.
Because success
and error
are deprecated since 1.4 maybe it is better to use the regular promise methods then
and catch
and transform the response within those methods and return the promise of that transformed response.
I am showing the same example with both approaches and a third in-between approach:
success
and error
approach (success
and error
return a promise of an HTTP response, so we need the help of $q
to return a promise of data):
function search(query) {
// We make use of Angular's $q library to create the deferred instance
var deferred = $q.defer();
$http.get('http://localhost/v1?=q' + query)
.success(function(data,status) {
// The promise is resolved once the HTTP call is successful.
deferred.resolve(data);
})
.error(function(reason,status) {
// The promise is rejected if there is an error with the HTTP call.
if(reason.error){
deferred.reject({text:reason.error, status:status});
}else{
//if we don't get any answers the proxy/api will probably be down
deferred.reject({text:'whatever', status:500});
}
});
// The promise is returned to the caller
return deferred.promise;
};
then
and catch
approach (this is a bit more difficult to test, because of the throw):
function search(query) {
var promise=$http.get('http://localhost/v1?=q' + query)
.then(function (response) {
// The promise is resolved once the HTTP call is successful.
return response.data;
},function(reason) {
// The promise is rejected if there is an error with the HTTP call.
if(reason.statusText){
throw reason;
}else{
//if we don't get any answers the proxy/api will probably be down
throw {statusText:'Call error', status:500};
}
});
return promise;
}
There is a halfway solution though (this way you can avoid the throw
and anyway you'll probably need to use $q
to mock the promise behavior in your tests):
function search(query) {
// We make use of Angular's $q library to create the deferred instance
var deferred = $q.defer();
$http.get('http://localhost/v1?=q' + query)
.then(function (response) {
// The promise is resolved once the HTTP call is successful.
deferred.resolve(response.data);
},function(reason) {
// The promise is rejected if there is an error with the HTTP call.
if(reason.statusText){
deferred.reject(reason);
}else{
//if we don't get any answers the proxy/api will probably be down
deferred.reject({statusText:'Call error', status:500});
}
});
// The promise is returned to the caller
return deferred.promise;
}
Any kind of comments or corrections are welcome.
Don't forget that you need to call it on the object that has the nav controller. For instance, if you have nav controller pushing on a tab bar controller with a RootViewController, calling self.navigationItem.hidesBackButton = YES
on the RootViewController will do nothing. You would actually have to call self.tabBarController.navigationItem.hidesBackButton = YES
One line that always goes in my .vimrc:
set tags=./tags;/
This will look in the current directory for "tags", and work up the tree towards root until one is found. IOW, you can be anywhere in your source tree instead of just the root of it.
The definition for DTO can be found on Martin Fowler's site. DTOs are used to transfer parameters to methods and as return types. A lot of people use those in the UI, but others inflate domain objects from them.
I believe this will solve the issue
var z = '[{"name":"1","age":"2"},{"name":"1","age":"3"}]';
z = JSON.stringify(JSON.parse(z));
$.ajax({
url: "/setTest",
data: z,
type: "POST",
dataType:"json",
contentType:'application/json'
});
Make sure your packaging strategy defined in your pom.xml is not "pom". It should be "jar" or anything else. Once you do that, update your project right clicking on it and go to Maven -> Update Project...
Everyone else has already answered it, but I think I still have something else to add.
Reasons to have that if
statement calling main()
(in no particular order):
Other languages (like C and Java) have a main()
function that is called when the program is executed. Using this if
, we can make Python behave like them, which feels more familiar for many people.
Code will be cleaner, easier to read, and better organized. (yeah, I know this is subjective)
It will be possible to import
that python code as a module without nasty side-effects.
This means it will be possible to run tests against that code.
This means we can import that code into an interactive python shell and test/debug/run it.
Variables inside def main
are local, while those outside it are global. This may introduce a few bugs and unexpected behaviors.
But, you are not required to write a main()
function and call it inside an if
statement.
I myself usually start writing small throwaway scripts without any kind of function. If the script grows big enough, or if I feel putting all that code inside a function will benefit me, then I refactor the code and do it. This also happens when I write bash
scripts.
Even if you put code inside the main function, you are not required to write it exactly like that. A neat variation could be:
import sys
def main(argv):
# My code here
pass
if __name__ == "__main__":
main(sys.argv)
This means you can call main()
from other scripts (or interactive shell) passing custom parameters. This might be useful in unit tests, or when batch-processing. But remember that the code above will require parsing of argv, thus maybe it would be better to use a different call that pass parameters already parsed.
In an object-oriented application I've written, the code looked like this:
class MyApplication(something):
# My code here
if __name__ == "__main__":
app = MyApplication()
app.run()
So, feel free to write the code that better suits you. :)
SELECT CAST(CAST(@DateField As Date) As DateTime) + CAST(CAST(@TimeField As Time) As DateTime)
SELECT YEAR(getdate()) * 10000 + MONTH(getdate()) * 100 + DAY(getdate())
Well to obtain all different values in a Dataframe
you can use distinct. As you can see in the documentation that method returns another DataFrame
. After that you can create a UDF
in order to transform each record.
For example:
val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")
// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct
// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)
// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))
You can split that string on ,
and directly get a list:
mStr = 'A,B,C,D,E'
list1 = mStr.split(',')
print(list1)
Output:
['A', 'B', 'C', 'D', 'E']
You can also convert it to an n-tuple:
print(tuple(list1))
Output:
('A', 'B', 'C', 'D', 'E')
Probably the best course of action is "do it as std lib does it". That is: All inline, all in headers.
// in the header
namespase my_namespace {
class my_standard_named_class final {
public:
static void standard_declared_defined_method () {
// even the comment is standard
}
} ;
} // namespase my_namespace
As simple as that ...
If you want to remove all lines in a file from your current line number, use dG
, it will delete all lines (shift g)
mean end of file
There is an easier way where you can just use your own HostnameVerifier to implicitly trust certain connections. The issue comes with Java 1.7 where SNI extensions have been added and your error is due to a server misconfiguration.
You can either use "-Djsse.enableSNIExtension=false" to disable SNI across the whole JVM or read my blog where I explain how to implement a custom verifier on top of a URL connection.
Yeah, this appears to be a common standard. Some coders use self, others use me. It's used as a reference back to the "real" object as opposed to the event.
It's something that took me a little while to really get, it does look odd at first.
I usually do this right at the top of my object (excuse my demo code - it's more conceptual than anything else and isn't a lesson on excellent coding technique):
function MyObject(){
var me = this;
//Events
Click = onClick; //Allows user to override onClick event with their own
//Event Handlers
onClick = function(args){
me.MyProperty = args; //Reference me, referencing this refers to onClick
...
//Do other stuff
}
}
This can give you the correct Answer
#include <stdio.h>
int main()
{
float total=100, number=50;
float percentage;
percentage=(number/total)*100;
printf("%0.2f",percentage);
return 0;
}
If You are using Gunicorn and Nginx environment then the following code template works for you.
addr_ip4 = request.remote_addr
I was able to get it to work in IE and FF with jQuery's:
$(window).bind('beforeunload', function(){
});
instead of: unload, onunload, or onbeforeunload
You could use something like the following
scp -r username_Linuxmachine@LinuxMachineAddress:Path/To/File Path/To/Local/System/Directory
This will copy the File
to the specified local directory on the system you are currently working on.
The -r
flag tells scp
to recursively copy if the remote path is indeed a directory.
This is for swift 2.3 Version. You can get the width of string.
var sizeOfString = CGSize()
if let font = UIFont(name: "Helvetica", size: 14.0)
{
let finalDate = "Your Text Here"
let fontAttributes = [NSFontAttributeName: font] // it says name, but a UIFont works
sizeOfString = (finalDate as NSString).sizeWithAttributes(fontAttributes)
}
I've been trying to get this working. Here's what works:
Example:
mod.mjs
export const STR = 'Hello World'
test.mjs
import {STR} from './mod.mjs'
console.log(STR)
Run: node test.mjs
You should see "Hello World".
It's definitely worth the effort.
There's one obvious reason that anyone who uses Vi(m)
will tell you, and two others that people never seem to mention.
Here's the obvious one:
vi
is at once ubiquitous and incredibly powerful, and by learning it once, you gain the ability to exercise that power on pretty much any computer that has a keyboard.And these are the lesser known reasons to learn Vim
:
It's not half as much effort as you think it's going to be. Run through the Vim tutor once (vimtutor
at a shell, or in Windows run it from the Vim folder in the Start Menu), and you'll already be well on your way to competence, and it's all downhill from there. I was up to the level where I could use Vim
at work without taking any noticeable productivity hit within less than a week's worth of lunchtimes.
It's fun! Editing text is like a game to me now. I actively enjoy it--which is pretty ridiculous, when you think about it.
There's also two good reasons not to learn Vim
:
It's addictive, and you'll find yourself wishing you could use Vim
commands in all your computing, and cursing whenever you can't. Fortunately, at least for some situations, there's ways to get around this.
Again, it's addictive, and although you won't lose any productivity from actually using Vim
, you will waste hours searching for good tips to make your Vim
experience even better, and reading the Vim tag on Stack Overflow.
I think you want this:
select *
from dbo.table
where DATALENGTH(column_name) = 3
I simply use
git fetch origin
to fetch the remote changes, and then I view both local and pending remote commits (and their associated changes) with the nice gitk tool involving the --all
argument like:
gitk --all
Like well explained in the link below, an identifying relation is somewhat like a weak entity type relation to its parent in the ER conceptual model. UML style CADs for data modeling do not use ER symbols or concepts, and the kind of relations are: identifying, non-identifying and non-specific.
Identifying ones are relations parent/child where the child is kind of a weak entity (even at the traditional ER model its called identifying relationship), which does not have a real primary key by its own attributes and therefore cannot be identified uniquely by its own. Every access to the child table, on the physical model, will be dependent (inclusive semantically) on the parent's primary key, which turns into part or total of the child's primary key (also being a foreign key), generally resulting in a composite key on the child side. The eventual existing keys of the child itself are only pseudo or partial-keys, not sufficient to identify any instance of that type of Entity or Entity Set, without the parent's PK.
Non-identifying relationship are the ordinary relations (partial or total), of completely independent entity sets, whose instances do not depend on each others' primary keys to be uniquely identified, although they might need foreign keys for partial or total relationships, but not as the primary key of the child. The child has its own primary key. The parent idem. Both independently. Depending on the cardinality of the relationship, the PK of one goes as a FK to the other (N side), and if partial, can be null, if total, must be not null. But, at a relationship like this, the FK will never be also the PK of the child, as when an identifying relationship is the case.
http://docwiki.embarcadero.com/ERStudioDA/XE7/en/Creating_and_Editing_Relationships
This code is working fine for me,
var a = serializer.Deserialize<List<Entity>>(json);
Same principle as other answers, just thought it was quicker than re-opening terminals :)
bash -l -c "rvm use 2.0.0"
protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), true))
{
_testData.WriteLine(TextBox1.Text); // Write the file.
}
}
Server.MapPath takes a virtual path and returns an absolute one. "~" is used to resolve to the application root.
it seems you can directly call:
g = sns.factorplot("class", "survived", "sex",
data=titanic, kind="bar",
size=6, palette="muted",
legend_out=False)
g._legend.set_bbox_to_anchor((.7, 1.1))
special_func to avoid try-except repetition:
def special_func(test_case_dict):
final_dict = {}
exception_dict = {}
def try_except_avoider(test_case_dict):
try:
for k,v in test_case_dict.items():
final_dict[k]=eval(v) #If no exception evaluate the function and add it to final_dict
except Exception as e:
exception_dict[k]=e #extract exception
test_case_dict.pop(k)
try_except_avoider(test_case_dict) #recursive function to handle remaining functions
finally: #cleanup
final_dict.update(exception_dict)
return final_dict #combine exception dict and final dict
return try_except_avoider(test_case_dict)
Run code:
def add(a,b):
return (a+b)
def sub(a,b):
return (a-b)
def mul(a,b):
return (a*b)
case = {"AddFunc":"add(8,8)","SubFunc":"sub(p,5)","MulFunc":"mul(9,6)"}
solution = special_func(case)
Output looks like:
{'AddFunc': 16, 'MulFunc': 54, 'SubFunc': NameError("name 'p' is not defined")}
To convert to variables:
locals().update(solution)
Variables would look like:
AddFunc = 16, MulFunc = 54, SubFunc = NameError("name 'p' is not defined")
You don't need case
in the where
statement, just use parentheses and or
:
Select * From Times
WHERE StartDate <= @Date AND EndDate >= @Date
AND (
(@day = 'Monday' AND Monday = 1)
OR (@day = 'Tuesday' AND Tuesday = 1)
OR Wednesday = 1
)
Additionally, your syntax is wrong for a case. It doesn't append things to the string--it returns a single value. You'd want something like this, if you were actually going to use a case
statement (which you shouldn't):
Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)
AND 1 = CASE WHEN @day = 'Monday' THEN Monday
WHEN @day = 'Tuesday' THEN Tuesday
ELSE Wednesday
END
And just for an extra umph, you can use the between
operator for your date:
where @Date between StartDate and EndDate
Making your final query:
select
*
from
Times
where
@Date between StartDate and EndDate
and (
(@day = 'Monday' and Monday = 1)
or (@day = 'Tuesday' and Tuesday = 1)
or Wednesday = 1
)
This might give the increased relevance to the head part that you want. It won't double it, but it might possibly good enough for your sake:
SELECT pages.*,
MATCH (head, body) AGAINST ('some words') AS relevance,
MATCH (head) AGAINST ('some words') AS title_relevance
FROM pages
WHERE MATCH (head, body) AGAINST ('some words')
ORDER BY title_relevance DESC, relevance DESC
-- alternatively:
ORDER BY title_relevance + relevance DESC
An alternative that you also want to investigate, if you've the flexibility to switch DB engine, is Postgres. It allows to set the weight of operators and to play around with the ranking.
For new line characters
UPDATE table_name SET field_name = TRIM(TRAILING '\n' FROM field_name);
UPDATE table_name SET field_name = TRIM(TRAILING '\r' FROM field_name);
UPDATE table_name SET field_name = TRIM(TRAILING '\r\n' FROM field_name);
For all white space characters
UPDATE table_name SET field_name = TRIM(field_name);
UPDATE table_name SET field_name = TRIM(TRAILING '\n' FROM field_name);
UPDATE table_name SET field_name = TRIM(TRAILING '\r' FROM field_name);
UPDATE table_name SET field_name = TRIM(TRAILING '\r\n' FROM field_name);
UPDATE table_name SET field_name = TRIM(TRAILING '\t' FROM field_name);
Read more: MySQL TRIM Function
I wanted the Number same as I get from database for example.
1) 00100.220000
2) 00123
3) 0000.0000100
So I modified the code as below
$objPHPExcel->getActiveSheet()
->setCellValue('A3', '00100.220000');
$objPHPExcel->getActiveSheet()
->getStyle('A3')
->getNumberFormat()
->setFormatCode('00000.000000');
$objPHPExcel->getActiveSheet()
->setCellValue('A4', '00123');
$objPHPExcel->getActiveSheet()
->getStyle('A4')
->getNumberFormat()
->setFormatCode('00000');
$objPHPExcel->getActiveSheet()
->setCellValue('A5', '0000.0000100');
$objPHPExcel->getActiveSheet()
->getStyle('A5')
->getNumberFormat()
->setFormatCode('0000.0000000');
What you are looking for are Linked Servers. You can get to them in SSMS from the following location in the tree of the Object Explorer:
Server Objects-->Linked Servers
or you can use sp_addlinkedserver.
You only have to set up one. Once you have that, you can call a table on the other server like so:
select
*
from
LocalTable,
[OtherServerName].[OtherDB].[dbo].[OtherTable]
Note that the owner isn't always dbo
, so make sure to replace it with whatever schema you use.
You could:
SELECT COALESCE(SUM(columnA), 0) FROM my_table WHERE columnB = 1
INTO res;
This happens to work, because your query has an aggregate function and consequently always returns a row, even if nothing is found in the underlying table.
Plain queries without aggregate would return no row in such a case. COALESCE
would never be called and couldn't save you. While dealing with a single column we can wrap the whole query instead:
SELECT COALESCE( (SELECT columnA FROM my_table WHERE ID = 1), 0)
INTO res;
Works for your original query as well:
SELECT COALESCE( (SELECT SUM(columnA) FROM my_table WHERE columnB = 1), 0)
INTO res;
More about COALESCE()
in the manual.
More about aggregate functions in the manual.
More alternatives in this later post:
Since the problem is the non-trivial destructor so if the destructor is removed from the std::string
, it's possible to define a constexpr
instance of that type. Like this
struct constexpr_str {
char const* str;
std::size_t size;
// can only construct from a char[] literal
template <std::size_t N>
constexpr constexpr_str(char const (&s)[N])
: str(s)
, size(N - 1) // not count the trailing nul
{}
};
int main()
{
constexpr constexpr_str s("constString");
// its .size is a constexpr
std::array<int, s.size> a;
return 0;
}
This is not like Collections.sort()
where the parameter reference gets sorted. In this case you just get a sorted stream that you need to collect and assign to another variable eventually:
List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
compareTo(o2.getItem().getValue())).
collect(Collectors.toList());
You've just missed to assign the result
It can't be stated enough that you can use console.debug(object) for this. This technique will save you literally hundreds of hours a year if you do this for a living :p
I've not used it, but SendKeys may do what you want.
Use SendKeys to send keystrokes and keystroke combinations to the active application. This class cannot be instantiated. To send a keystroke to a class and immediately continue with the flow of your program, use Send. To wait for any processes started by the keystroke, use SendWait.
System.Windows.Forms.SendKeys.Send("A");
System.Windows.Forms.SendKeys.Send("{ENTER}");
Microsoft has some more usage examples here.
Another way to do it could be by creating an alias. For example in terminal write:
alias printhello='python /home/hello_world.py'
Writing printhello
will run hello_world.py, but this is only temporary.
To make aliases permanent, you have to add them to bashrc, you can edit it by writing this in the terminal:
gedit ~/.bashrc
here See my result Swift with fully customizable button supported
Advance bonus for use this only one method implementation and you get a perfect button!!!
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let action = UIContextualAction(
style: .destructive,
title: "",
handler: { (action, view, completion) in
let alert = UIAlertController(title: "", message: "Are you sure you want to delete this incident?", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
let model = self.incedentArry[indexPath.row] as! HFIncedentModel
print(model.incent_report_id)
self.incedentArry.remove(model)
tableView.deleteRows(at: [indexPath], with: .fade)
delete_incedentreport_data(param: ["incent_report_id": model.incent_report_id])
completion(true)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction)in
tableView.reloadData()
}))
self.present(alert, animated: true, completion: {
})
})
action.image = HFAsset.ic_trash.image
action.backgroundColor = UIColor.red
let configuration = UISwipeActionsConfiguration(actions: [action])
configuration.performsFirstActionWithFullSwipe = true
return configuration
}
You could use the bootstrap grid system :
<div class="col-md-6 form-group">
<label for="textbox1">Label1</label>
<input class="form-control" id="textbox1" type="text"/>
</div>
<div class="col-md-6 form-group">
<label for="textbox2">Label2</label>
<input class="form-control" id="textbox2" type="text"/>
</div>
<span class="clearfix">
http://getbootstrap.com/css/#grid
Is that what you want to achieve?
Alternatively, you could differentiate using BuildConfig.BUILD_TYPE;
If you're running debug build
BuildConfig.BUILD_TYPE.equals("debug");
returns true. And for release build BuildConfig.BUILD_TYPE.equals("release");
returns true.
Here is a literal pure Python translation of the Welford's algorithm implementation from http://www.johndcook.com/standard_deviation.html:
https://github.com/liyanage/python-modules/blob/master/running_stats.py
import math
class RunningStats:
def __init__(self):
self.n = 0
self.old_m = 0
self.new_m = 0
self.old_s = 0
self.new_s = 0
def clear(self):
self.n = 0
def push(self, x):
self.n += 1
if self.n == 1:
self.old_m = self.new_m = x
self.old_s = 0
else:
self.new_m = self.old_m + (x - self.old_m) / self.n
self.new_s = self.old_s + (x - self.old_m) * (x - self.new_m)
self.old_m = self.new_m
self.old_s = self.new_s
def mean(self):
return self.new_m if self.n else 0.0
def variance(self):
return self.new_s / (self.n - 1) if self.n > 1 else 0.0
def standard_deviation(self):
return math.sqrt(self.variance())
Usage:
rs = RunningStats()
rs.push(17.0)
rs.push(19.0)
rs.push(24.0)
mean = rs.mean()
variance = rs.variance()
stdev = rs.standard_deviation()
print(f'Mean: {mean}, Variance: {variance}, Std. Dev.: {stdev}')
According to ahmed_khan_89's answer, you can put you "copy code" inside product flavors.
productFlavors {
staging {
applicationId = "com.demo.staging"
println "Using Staging google-service.json"
copy {
from 'src/staging/'
include '*.json'
into '.'
}
}
production {
applicationId = "com.demo.production"
println "Using Production google-service.json"
copy {
from 'src/production/'
include '*.json'
into '.'
}
}
}
Then you don't have to switch settings manually.
The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.
The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.
Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.
Below, is the most clean, comprehensible way of merging multiple dataframe if complex queries aren't involved.
Just simply merge with DATE as the index and merge using OUTER method (to get all the data).
import pandas as pd
from functools import reduce
df1 = pd.read_table('file1.csv', sep=',')
df2 = pd.read_table('file2.csv', sep=',')
df3 = pd.read_table('file3.csv', sep=',')
Now, basically load all the files you have as data frame into a list. And, then merge the files using merge
or reduce
function.
# compile the list of dataframes you want to merge
data_frames = [df1, df2, df3]
Note: you can add as many data-frames inside the above list. This is the good part about this method. No complex queries involved.
To keep the values that belong to the same date you need to merge it on the DATE
df_merged = reduce(lambda left,right: pd.merge(left,right,on=['DATE'],
how='outer'), data_frames)
# if you want to fill the values that don't exist in the lines of merged dataframe simply fill with required strings as
df_merged = reduce(lambda left,right: pd.merge(left,right,on=['DATE'],
how='outer'), data_frames).fillna('void')
Then write the merged data to the csv file if desired.
pd.DataFrame.to_csv(df_merged, 'merged.txt', sep=',', na_rep='.', index=False)
This should give you
DATE VALUE1 VALUE2 VALUE3 ....
You can use Angular $window
:
$window.location.href = '/index.html';
Example usage in a contoller:
(function () {
'use strict';
angular
.module('app')
.controller('LoginCtrl', LoginCtrl);
LoginCtrl.$inject = ['$window', 'loginSrv', 'notify'];
function LoginCtrl($window, loginSrv, notify) {
/* jshint validthis:true */
var vm = this;
vm.validateUser = function () {
loginSrv.validateLogin(vm.username, vm.password).then(function (data) {
if (data.isValidUser) {
$window.location.href = '/index.html';
}
else
alert('Login incorrect');
});
}
}
})();
Have you tried using the replaceAll method to replace any occurence of \n or \r with the empty String?
I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.
BE MINDFUL, If you use angular.equals()
on objects that have property obj.$something
(property name starts with $) those properties will get ignored in comparison.
Example:
var obj1 = {
$key0: "A",
key1: "value1",
key2: "value2",
key3: {a: "aa", b: "bb"}
}
var obj2 = {
$key0: "B"
key2: "value2",
key1: "value1",
key3: {a: "aa", b: "bb"}
}
angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)
Swift 4:
As per:
https://developer.apple.com/documentation/foundation/nserror
if you don't want to define a custom exception, you could use a standard NSError object as follows:
import Foundation
do {
throw NSError(domain: "my error domain", code: 42, userInfo: ["ui1":12, "ui2":"val2"] )
}
catch let error as NSError {
print("Caught NSError: \(error.localizedDescription), \(error.domain), \(error.code)")
let uis = error.userInfo
print("\tUser info:")
for (key,value) in uis {
print("\t\tkey=\(key), value=\(value)")
}
}
Prints:
Caught NSError: The operation could not be completed, my error domain, 42
User info:
key=ui1, value=12
key=ui2, value=val2
This allows you to provide a custom string (the error domain), plus a numeric code and a dictionary with all the additional data you need, of any type.
N.B.: this was tested on OS=Linux (Ubuntu 16.04 LTS).
You should, as a rule, leave timestamps in the database in GMT, and only convert them to/from local time on input/output, when you can convert them to the user's (not server's) local timestamp.
It would be nice if you could do the following:
SELECT DATETIME(col, 'PDT')
...to output the timestamp for a user on Pacific Daylight Time. Unfortunately, that doesn't work. According to this SQLite tutorial, however (scroll down to "Other Date and Time Commands"), you can ask for the time, and then apply an offset (in hours) at the same time. So, if you do know the user's timezone offset, you're good.
Doesn't deal with daylight saving rules, though...
I had the same error, and the problem was not in configuring the JDK, but a simple wrong path to the JKS file in application.properties
file under trust-store:
parameter, double-check if the path is correct.
You will need to create a virtual device that runs on ARM. Virtual devices running on X86 require an Intel processor. AMD support as specified by Android is only available for Linux systems. If you want a better experience when creating your Virtual Device, use "Store a snapshot for faster startup" instead of the default "Use Host GPU".
After all else failed...
My solution was to change the layout file from
= stylesheet_link_tag "reset-min", 'application'
to
= stylesheet_link_tag 'application'
And it worked! (You can put the reset file inside the manifest.)
The way that Magento themes handle actual url's is as such (in view partials - phtml files):
echo $this->getSkinUrl('images/logo.png');
If you need the actual base path on disk to the image directory use:
echo Mage::getBaseDir('skin');
Some more base directory types are available in this great blog post:
To understand the "encoding" attribute, you have to understand the difference between bytes and characters.
Think of bytes as numbers between 0 and 255, whereas characters are things like "a", "1" and "Ä". The set of all characters that are available is called a character set.
Each character has a sequence of one or more bytes that are used to represent it; however, the exact number and value of the bytes depends on the encoding used and there are many different encodings.
Most encodings are based on an old character set and encoding called ASCII which is a single byte per character (actually, only 7 bits) and contains 128 characters including a lot of the common characters used in US English.
For example, here are 6 characters in the ASCII character set that are represented by the values 60 to 65.
Extract of ASCII Table 60-65
+---------------------+
¦ Byte ¦ Character ¦
¦------+--------------¦
¦ 60 ¦ < ¦
¦ 61 ¦ = ¦
¦ 62 ¦ > ¦
¦ 63 ¦ ? ¦
¦ 64 ¦ @ ¦
¦ 65 ¦ A ¦
+---------------------+
In the full ASCII set, the lowest value used is zero and the highest is 127 (both of these are hidden control characters).
However, once you start needing more characters than the basic ASCII provides (for example, letters with accents, currency symbols, graphic symbols, etc.), ASCII is not suitable and you need something more extensive. You need more characters (a different character set) and you need a different encoding as 128 characters is not enough to fit all the characters in. Some encodings offer one byte (256 characters) or up to six bytes.
Over time a lot of encodings have been created. In the Windows world, there is CP1252, or ISO-8859-1, whereas Linux users tend to favour UTF-8. Java uses UTF-16 natively.
One sequence of byte values for a character in one encoding might stand for a completely different character in another encoding, or might even be invalid.
For example, in ISO 8859-1, â is represented by one byte of value 226
, whereas in UTF-8 it is two bytes: 195, 162
. However, in ISO 8859-1, 195, 162
would be two characters, Ã, ¢.
Think of XML as not a sequence of characters but a sequence of bytes.
Imagine the system receiving the XML sees the bytes 195, 162
. How does it know what characters these are?
In order for the system to interpret those bytes as actual characters (and so display them or convert them to another encoding), it needs to know the encoding used in the XML.
Since most common encodings are compatible with ASCII, as far as basic alphabetic characters and symbols go, in these cases, the declaration itself can get away with using only the ASCII characters to say what the encoding is. In other cases, the parser must try and figure out the encoding of the declaration. Since it knows the declaration begins with <?xml
it is a lot easier to do this.
Finally, the version
attribute specifies the XML version, of which there are two at the moment (see Wikipedia XML versions. There are slight differences between the versions, so an XML parser needs to know what it is dealing with. In most cases (for English speakers anyway), version 1.0 is sufficient.
xcopy "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i
Probably the problem is the space.Try with quotes.
Based on the proposed solution by @blootsvoets, I edited my jar target this way :
jar {
manifest {
attributes('Main-Class': 'eu.tib.sre.Main')
}
// Include the classpath from the dependencies
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
// This help solve the issue with jar lunch
{
exclude "META-INF/*.SF"
exclude "META-INF/*.DSA"
exclude "META-INF/*.RSA"
}
}
Use:
Random r = new Random();
int x= r.Next(10);//Max range
The comma got eaten by the quotes!
This part:
("username," visitorName);
Should be this:
("username", visitorName);
Aside: For pasting code into the console, you can paste them in one line at a time to help you pinpoint where things went wrong ;-)
Shorter way is do it as follows:
private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
Here is a COMPLETE Javascript-free, CSS-based solution that allows you to target Internet Explorer 1-11!
My Internet Explorer Only CSS Solution
This works by hiding IE1-7 from all your modern sheets using @import
, giving IE1-7 a clean, white page layout, then applies three simple CSS media query "hacks" to isolate IE8-11 in the imported sheet. It even affects IE on Mac!
The advantage to this strategy is its 100% effective in targeting IE1-11, giving you complete control over how you customize CSS for those targeted browsers, while freeing you up as a designer to focus on newer CSS3 and cutting-edge styles and layouts in Edge and all other modern browsers going forward. I have been using a version of this since 2004 but recently updated it for 2021.
HOW IT WORKS
First create two CSS style sheet links. The first is a basic element style sheet that gives all browsers, old and new, a simple white, block-level layout. Linked CSS has wide support in older CSS1 browsers going back to 1995. A wide range of old browsers will see this first sheet and display your content and layouts in a clean, white block-level content page. I like to put "reset" element-only styles in here. The second sheet is an import sheet that will load all your advanced CSS styles using a single @import
rule that hides styles to a wide range of browsers including IE1-7.
<link media="screen" rel="stylesheet" type="text/css" href="OldBrowsers.css" />
<link media="screen" rel="stylesheet" type="text/css" href="Import.css" />
Next, in your "Import.css" sheet add this @import rule exactly as formatted (Its hidden from IE1-7 and a wide range of older browsers listed below):
@import 'ModernBrowsers.css' all;
All CSS in this imported sheet will be hidden from IE1-7 and a wide range of older browsers. IE 1-7 doesn't understand "media type" value "all" so will fail to import this sheet. This specific version of import is also not recognized by many older browsers (pre-2001). Those browsers are so old now, you just need to deliver them a white web page with stacked blocks of content. Use "OldBrowsers" to do so.
Next, in "ModernBrowsers.css" you want to target IE8-11 using CSS media query "hacks" alongside all your normal selectors and classes. Simply apply the following media query, IE-only fixes to your modern, imported style sheet to target these specific IE browsers. Drop into these blocks any styles specific to them. You can attack your layout or other style issues in IE now in media query "batches" now rather than by multiple selector "hacks":
/* IE8 */
@media \0screen {
body {
background: red !important;
}
}
/* IE9 */
@media all and (monochrome:0) {
body {
background: blue\9 !important;
}
}
/* IE10-11 */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
body {
background: green !important;
}
}
Simple! You have now targeted styles for IE1-11 (all Internet Explorer browsers!)
With this solution you achieve the following:
The @import
excludes IE 1-7 from your modern styles, completely! Those agents, along with the list below, will never see your modern imported styles and get a clean white style sheet content page older browsers can still use as far as viewing your content (use "OldBrowsers.css" to style them). The following browsers are excluded from "ModernBrowsers.css" using the above @import
rule:
In your "ModernBrowsers" imported sheet, you can now safely target IE browsers version 8-11 using simple media query "hacks".
This system uses a simple @import
style sheet system that is fast and manageable using traditional, non-support for external style rules rather than CSS fixes sprinkled throughout multiple sheets. (BTW...Do not listen to anyone saying @import
is slow, as it is not. My import sheet has ONE LINE and is maybe a kilobyte or less in size! @import
has been used since the birth of the WWW and is no different than a simple CSS link. Compare this to the Megabytes of Javascript kids today are shoving into browsers using these new "modern" ECMAScript SPA API's just to display a tiny paragraph of news!)
All old IE browsers and a wide range of other user agnets are excluded from modern styles now using this import strategy, which allows these agents to collapse back to plain, "block-level", white pages and stacked content layouts that are fully accessible by older browsers.
Notice this solution has no IE conditional comments! (you should NEVER use those)
With this solution, web designs are now 100% free to use custom, cutting edge CSS3 technologies without having to ever worry about older browsers and IE1-11 ever again!
I will be posting my formal version of this Universal CSS System on GitHub soon! So stay tuned...
This is part of the new "progressive" CSS, 100% Javacript-free, design concept in 2021 for addressing cross-browser style issues, where older agents are allowed to degrade gracefully to simpler layouts rather than struggling to fix problems in cryptic old, broken, box-model agents (IE6) that don't need custom layouts any longer today as the long tail of their slow demise continues online.
And its my hope we stop creating these gigantic, CPU-hog, Javascripted, polyfill nightmare solutions for addressing what used to be years ago solved by simple CSS solutions like this one.
public static List<SelectListItem> States = new List<SelectListItem>()
{
new SelectListItem() {Text="Alabama", Value="AL"},
new SelectListItem() { Text="Alaska", Value="AK"},
new SelectListItem() { Text="Arizona", Value="AZ"},
new SelectListItem() { Text="Arkansas", Value="AR"},
new SelectListItem() { Text="California", Value="CA"},
new SelectListItem() { Text="Colorado", Value="CO"},
new SelectListItem() { Text="Connecticut", Value="CT"},
new SelectListItem() { Text="District of Columbia", Value="DC"},
new SelectListItem() { Text="Delaware", Value="DE"},
new SelectListItem() { Text="Florida", Value="FL"},
new SelectListItem() { Text="Georgia", Value="GA"},
new SelectListItem() { Text="Hawaii", Value="HI"},
new SelectListItem() { Text="Idaho", Value="ID"},
new SelectListItem() { Text="Illinois", Value="IL"},
new SelectListItem() { Text="Indiana", Value="IN"},
new SelectListItem() { Text="Iowa", Value="IA"},
new SelectListItem() { Text="Kansas", Value="KS"},
new SelectListItem() { Text="Kentucky", Value="KY"},
new SelectListItem() { Text="Louisiana", Value="LA"},
new SelectListItem() { Text="Maine", Value="ME"},
new SelectListItem() { Text="Maryland", Value="MD"},
new SelectListItem() { Text="Massachusetts", Value="MA"},
new SelectListItem() { Text="Michigan", Value="MI"},
new SelectListItem() { Text="Minnesota", Value="MN"},
new SelectListItem() { Text="Mississippi", Value="MS"},
new SelectListItem() { Text="Missouri", Value="MO"},
new SelectListItem() { Text="Montana", Value="MT"},
new SelectListItem() { Text="Nebraska", Value="NE"},
new SelectListItem() { Text="Nevada", Value="NV"},
new SelectListItem() { Text="New Hampshire", Value="NH"},
new SelectListItem() { Text="New Jersey", Value="NJ"},
new SelectListItem() { Text="New Mexico", Value="NM"},
new SelectListItem() { Text="New York", Value="NY"},
new SelectListItem() { Text="North Carolina", Value="NC"},
new SelectListItem() { Text="North Dakota", Value="ND"},
new SelectListItem() { Text="Ohio", Value="OH"},
new SelectListItem() { Text="Oklahoma", Value="OK"},
new SelectListItem() { Text="Oregon", Value="OR"},
new SelectListItem() { Text="Pennsylvania", Value="PA"},
new SelectListItem() { Text="Rhode Island", Value="RI"},
new SelectListItem() { Text="South Carolina", Value="SC"},
new SelectListItem() { Text="South Dakota", Value="SD"},
new SelectListItem() { Text="Tennessee", Value="TN"},
new SelectListItem() { Text="Texas", Value="TX"},
new SelectListItem() { Text="Utah", Value="UT"},
new SelectListItem() { Text="Vermont", Value="VT"},
new SelectListItem() { Text="Virginia", Value="VA"},
new SelectListItem() { Text="Washington", Value="WA"},
new SelectListItem() { Text="West Virginia", Value="WV"},
new SelectListItem() { Text="Wisconsin", Value="WI"},
new SelectListItem() { Text="Wyoming", Value="WY"}
};
How we do it is put this method into a class and then call the class from the view
@Html.DropDownListFor(x => x.State, Class.States)
<div id="wrap" class=' @(ViewContext.RouteData.Values["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>
EDIT 01-10-2014:
Since this question is so popular this answer has been improved.
The example above will only get the values from RouteData
, so only from the querystrings which are caught by some registered route. To get the querystring value you have to get to the current HttpRequest
. Fastest way is by calling (as TruMan pointed out) `Request.Querystring' so the answer should be:
<div id="wrap" class=' @(Request.QueryString["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>
You can also check RouteValues vs QueryString MVC?
EDIT 03-05-2019:
Above solution is working for .NET Framework.
As others pointed out if you would like to get query string value in .NET Core you have to use Query
object from Context.Request
path. So it would be:
<div id="wrap" class=' @(Context.Request.Query["iframe"] == new StringValues("1") ? /*do sth*/ : /*do sth else*/')> </div>
Please notice I am using StringValues("1")
in the statement because Query
returns StringValues
struct instead of pure string
. That's cleanes way for this scenerio which I've found.
Use find
on the command line:
find /my/directory -name '*.js'
Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".
You could add some logging to the Global.asax in Session_Start and Application_Start to track what's going on with the user's Session and the Application as a whole.
Also, watch out of you're running in Web Farm mode (multiple IIS threads defined in the application pool) or load balancing because the user can end up hitting a different server that does not have the same memory. If this is the case, you can switch the Session mode to SQL Server.
**to scroll up to desired height. I have come up with some good solution **
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.scrollBy(0, childView.getHeight());
}
}, 100);
The above answer by pl_rock is correct, the only thing I would add is to expect the ARG inside the Dockerfile if not you won't have access to it. So if you are doing
docker build -t essearch/ess-elasticsearch:1.7.6 --build-arg number_of_shards=5 --build-arg number_of_replicas=2 --no-cache .
Then inside the Dockerfile you should add
ARG number_of_replicas
ARG number_of_shards
I was running into this problem, so I hope I help someone (myself) in the future.
You are deleting the row from the gridview but you are then going and calling databind again which is just refreshing the gridview to the same state that the original datasource is in.
Either remove it from the datasource and then databind, or databind and remove it from the gridview without redatabinding.
Edit based on better answer below. Go down about 3 answers and find out about the coolness of basestring.
Old answer: Watch out for unicode strings, which you can get from several places, including all COM calls in Windows.
if isinstance(target, str) or isinstance(target, unicode):
If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.
Maybe you could take a look at JFileChooser, which allow you to use native dialogs in one line of code.
I would store it as a char(36).
{{app.session}}
refers to the Session
object and not the $_SESSION
array. I don't think the $_SESSION
array is accessible unless you explicitly pass it to every Twig template or if you do an extension that makes it available.
Symfony2 is object-oriented, so you should use the Session
object to set session attributes and not rely on the array. The Session
object will abstract this stuff away from you so it is easier to, say, store the session in a database because storing the session variable is hidden from you.
So, set your attribute in the session and retrieve the value in your twig template by using the Session
object.
// In a controller
$session = $this->get('session');
$session->set('filter', array(
'accounts' => 'value',
));
// In Twig
{% set filter = app.session.get('filter') %}
{% set account-filter = filter['accounts'] %}
Hope this helps.
Regards,
Matt
If possible, add this to the main Apache configuration file. It is a lighter-weight solution, less processing required.
<VirtualHost 64.65.66.67>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost 64.65.66.67>
ServerAdmin [email protected]
ServerName www.example.com
DocumentRoot /var/www/example
.
.
. etc
So, the separate VirtualHost
for "example.com" captures those requests and then permanently redirects them to your main VirtualHost
. So there's no REGEX parsing with every request, and your client browsers will cache the redirect so they'll never (or rarely) request the "wrong" url again, saving you on server load.
Note, the trailing slash in Redirect permanent / http://www.example.com/
.
Without it, a redirect from example.com/asdf
would redirect to http://www.example.comasdf
instead of http://www.example.com/asdf
.
UPDATE: Now it's very simple to add HTML attributes to the default editor templates. It neans instead of doing this:
@Html.TextBoxFor(m => m.userCode, new { @readonly="readonly" })
you simply can do this:
@Html.EditorFor(m => m.userCode, new { htmlAttributes = new { @readonly="readonly" } })
Benefits: You haven't to call .TextBoxFor
, etc. for templates. Just call .EditorFor
.
While @Shark's solution works correctly, and it is simple and useful, my solution (that I use always) is this one: Create an editor-template
that can handles readonly
attribute:
EditorTemplates
in ~/Views/Shared/
PartialView
named String.cshtml
Fill the String.cshtml
with this code:
@if(ViewData.ModelMetadata.IsReadOnly) {
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
new { @class = "text-box single-line readonly", @readonly = "readonly", disabled = "disabled" })
} else {
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
new { @class = "text-box single-line" })
}
In model class, put the [ReadOnly(true)]
attribute on properties which you want to be readonly
.
For example,
public class Model {
// [your-annotations-here]
public string EditablePropertyExample { get; set; }
// [your-annotations-here]
[ReadOnly(true)]
public string ReadOnlyPropertyExample { get; set; }
}
Now you can use Razor's default syntax simply:
@Html.EditorFor(m => m.EditablePropertyExample)
@Html.EditorFor(m => m.ReadOnlyPropertyExample)
The first one renders a normal text-box
like this:
<input class="text-box single-line" id="field-id" name="field-name" />
And the second will render to;
<input readonly="readonly" disabled="disabled" class="text-box single-line readonly" id="field-id" name="field-name" />
You can use this solution for any type of data (DateTime
, DateTimeOffset
, DataType.Text
, DataType.MultilineText
and so on). Just create an editor-template
.
I landed here with the same issue, then figured it out on my own. This weird character was appearing with my HTML.
The issue is most likely your code editor. I use Espresso and sometimes run into issues like this.
To fix it, simply highlight the affected code, then go to the menu and click "convert to numeric entities". You'll see the numeric value of this character appear; simply delete it and it's gone forever.
grep
can be used even if we're not looking for a string.
Simply running,
grep -RIl "" .
will print out the path to all text files, i.e. those containing only printable characters.
In CMD, write:
javac -Xlint:unchecked MyGui2.java
it will display the list of unchecked or unsafe operations.
If you have .Net installed, a tool to generate XSD schemas and classes is already included by default.
For me, the XSD tool is installed under the following structure. This may differ depending on your installation directory.
C:\Program Files\Microsoft Visual Studio 8\VC>xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
xsd.exe -
Utility to generate schema or class files from given source.
xsd.exe <schema>.xsd /classes|dataset [/e:] [/l:] [/n:] [/o:] [/s] [/uri:]
xsd.exe <assembly>.dll|.exe [/outputdir:] [/type: [...]]
xsd.exe <instance>.xml [/outputdir:]
xsd.exe <schema>.xdr [/outputdir:]
Normally the classes and schemas that this tool generates work rather well, especially if you're going to be consuming them in a .Net language
I typically take the XML document that I'm after, push it through the XSD tool with the /o:<your path>
flag to generate a schema (xsd) and then push the xsd file back through the tool using the /classes /L:VB (or CS) /o:<your path>
flags to get classes that I can import and use in my day to day .Net projects
I ran into the same error, when I just forgot to declare my custom component in my NgModule
- check there, if the others solutions won't work for you.
Although git pull origin yourbranch
works, it's not really a good idea
You can alternatively do the following:
git fetch origin
git merge origin/yourbranch
The first line fetches all the branches from origin, but doesn't merge with your branches. This simply completes your copy of the repository.
The second line merges your current branch with that of yourbranch
that you fetched from origin
(which is one of your remotes
).
This is assuming origin
points to the repository at address ssh://11.21.3.12:23211/dir1/dir2
pandas 0.21 introduces new functions for Parquet:
pd.read_parquet('example_pa.parquet', engine='pyarrow')
or
pd.read_parquet('example_fp.parquet', engine='fastparquet')
The above link explains:
These engines are very similar and should read/write nearly identical parquet format files. These libraries differ by having different underlying dependencies (fastparquet by using numba, while pyarrow uses a c-library).
As far as I know this:
div[class=yourclass] table { your style here; }
or in your case even this:
div.yourclass table { your style here; }
(but this will work for elements with yourclass
that might not be div
s) will affect only tables inside yourclass
. And, as Ken says, the > is not supported everywhere (and div[class=yourclass]
too, so use the point notation for classes).
You only need to prefix an if
statement with @
if you're not already inside a razor code block.
Edit: You have a couple of things wrong with your code right now.
You're declaring nmb
, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:
@if (ViewBag.Articles != null)
{
int nmb = 0;
foreach (var item in ViewBag.Articles)
{
if (nmb % 3 == 0)
{
@:<div class="row">
}
<a href="@Url.Action("Article", "Programming", new { id = item.id })">
<div class="tasks">
<div class="col-md-4">
<div class="task important">
<h4>@item.Title</h4>
<div class="tmeta">
<i class="icon-calendar"></i>
@item.DateAdded - Pregleda:@item.Click
<i class="icon-pushpin"></i> Authorrr
</div>
</div>
</div>
</div>
</a>
if (nmb % 3 == 0)
{
@:</div>
}
}
}
The important part here is the @:
. It's a short-hand of <text></text>
, which is used to force the razor engine to render text.
One other thing, the HTML standard specifies that a
tags can only contain inline elements, and right now, you're putting a div
, which is a block-level element, inside an a
.
I experienced same issue on MAC catalina 10.15 what you add in .bash_profile is not recognised when you echo it on terminal, it is stored temporarily. It is recommended to use .zprofile for permanent and add all environment variables in it.After trying for 5hours i found out this solution. Hope it will be useful for someone.
vi .zprofile
insert(press i)
export ANDROID_HOME=/Users/mypc/Library/Android/sdk
export PATH=$ANDROID_HOME/platform-tools:${PATH}
after adding environment variables press esc
then enter :wq!
try echo $ANDROID_HOME in new tab(it will not be empty) path will be
printed
nvidia-smi -l 1
This will loop and call the view at every second.
If you do not want to keep past traces of the looped call in the console history, you can also do:
watch -n0.1 nvidia-smi
Where 0.1 is the time interval, in seconds.
If you don't mind picking the same item again at some other time:
$items[rand(0, count($items) - 1)];
Hope this piece of code give you an idea of changing jPanels inside a JFrame.
public class PanelTest extends JFrame {
Container contentPane;
public PanelTest() {
super("Changing JPanel inside a JFrame");
contentPane=getContentPane();
}
public void createChangePanel() {
contentPane.removeAll();
JPanel newPanel=new JPanel();
contentPane.add(newPanel);
System.out.println("new panel created");//for debugging purposes
validate();
setVisible(true);
}
}
I don't like to install stuff with sudo. once you start with sudo you can't stop..
try giving permissions to the Gems directory.
sudo chown -R $(whoami) /Library/Ruby/Gems/2.0.0
For me worked only adding the config
or ssh_config
file that was on the dir ~/.ssh/config
on my Linux system on the c:\Program Files\Git\etc\ssh\
directory on Windows.
In some git versions we need to edit the C:\Users\<username>\AppData\Local\Programs\Git\etc\ssh\ssh_config
file.
After that, I was able to use all the alias and settings that I normally used on my Linux connecting or pushing via SSH on the Git Bash.
I had a similar error, but in my case the cause was file renaming. I was creating a gzipped file file1.tar.gz
and repeatedly updating it in another tarfile with tar -uvf ./combined.tar ./file1.tar.gz
. I got the unexpected EOF error when after untarring combined.tar
and trying to untar file1.tar.gz
.
I noticed there was a difference in the output of file
before and after tarring:
$file file1.tar.gz
file1.tar.gz: gzip compressed data, was "file1.tar", last modified: Mon Jul 29 12:00:00 2019, from Unix
$tar xvf combined.tar
$file file1.tar.gz
file1.tar.gz: gzip compressed data, was "file_old.tar", last modified: Mon Jul 29 12:00:00 2019, from Unix
So, it appears that the file had a different name when I originally created combined.tar
, and using the tar update function doesn't overwrite the metadata for the gzipped filename. The solution was to recreate combined.tar
from scratch instead of updating it.
I still don't know exactly what happened, since changing the name of a gzipped file doesn't normally break it.
There is a difference between the navigation bar and the status bar. The confusing part is that it looks like one solid feature at the top of the screen, but the areas can actually be separated into two distinct views; a status bar and a navigation bar. The status bar spans from y=0 to y=20 points and the navigation bar spans from y=20 to y=64 points. So the navigation bar (which is where the page title and navigation buttons go) has a height of 44 points, but the status bar and navigation bar together have a total height of 64 points.
Here is a great resource that addresses this question along with a number of other sizing idiosyncrasies in iOS7: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/
Your makefile should ideally be named makefile
, not make
. Note that you can call your makefile anything you like, but as you found, you then need the -f
option with make
to specify the name of the makefile. Using the default name of makefile
just makes life easier.
You can write your php file to the action
attr of form element.
At the php side you can get the form value by $_POST['element_name']
.
This function takes the difference between two dates and shows it in a date format yyyy-mm-dd. All you need is to execute the code below and then use the function. After executing you can use it like this
SELECT datedifference(date1, date2)
FROM ....
.
.
.
.
DELIMITER $$
CREATE FUNCTION datedifference(date1 DATE, date2 DATE) RETURNS DATE
NO SQL
BEGIN
DECLARE dif DATE;
IF DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2)))) < 0 THEN
SET dif=DATE_FORMAT(
CONCAT(
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 ,
'-',
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 ,
'-',
DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(DATE_SUB(date1, INTERVAL 1 MONTH)), '-', DAY(date2))))),
'%Y-%m-%d');
ELSEIF DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2)))) < DAY(LAST_DAY(DATE_SUB(date1, INTERVAL 1 MONTH))) THEN
SET dif=DATE_FORMAT(
CONCAT(
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 ,
'-',
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 ,
'-',
DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2))))),
'%Y-%m-%d');
ELSE
SET dif=DATE_FORMAT(
CONCAT(
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 ,
'-',
PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 ,
'-',
DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2))))),
'%Y-%m-%d');
END IF;
RETURN dif;
END $$
DELIMITER;
Object.assign will only work in single level of object reference.
To do a copy in any depth use as below:
let x = {'a':'a','b':{'c':'c'}};
let y = JSON.parse(JSON.stringify(x));
If want to use any library instead then go with the loadash.js
library.
In python notebooks I often want to filter out 'dangling' numpy.ndarray
's, in particular the ones that are stored in _1
, _2
, etc that were never really meant to stay alive.
I use this code to get a listing of all of them and their size.
Not sure if locals()
or globals()
is better here.
import sys
import numpy
from humanize import naturalsize
for size, name in sorted(
(value.nbytes, name)
for name, value in locals().items()
if isinstance(value, numpy.ndarray)):
print("{:>30}: {:>8}".format(name, naturalsize(size)))
Another way:
x=$'Some\nstring'
readarray -t y <<<"$x"
Or, if you don't have bash 4, the bash 3.2 equivalent:
IFS=$'\n' read -rd '' -a y <<<"$x"
You can also do it the way you were initially trying to use:
y=(${x//$'\n'/ })
This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'
. To make it work, you need to restrict the word separator before parsing it:
IFS=$'\n' y=(${x//$'\n'/ })
...and then, since you are changing the separator, you don't need to convert the \n
to space
anymore, so you can simplify it to:
IFS=$'\n' y=($x)
This approach will function unless $x
contains a matching globbing pattern (such as "*
") - in which case it will be replaced by the matched file name(s). The read
/readarray
methods require newer bash versions, but work in all cases.
a[title="My site"] {
color: red;
}
This also works with any attribute you want to add for instance:
HTML
<div class="my_class" anything="whatever">My Stuff</div>
CSS
.my_class[anything="whatever"] {
color: red;
}
See it work at: http://jsfiddle.net/vpYWE/1/
In dynamic languages, when the interpreter import
s, it simply reads a file and evaluates it.
In C, external libraries are located by the linker at compile time to build the final object if the library is statically compiled, while for dynamic libraries a smaller version of the linker is called at runtime which remaps addresses and so makes code in the library available to the executable.
In Java, import
is simply used by the compiler to let you name your classes by their unqualified name, let's say String
instead of java.lang.String
. You don't really need to import java.lang.*
because the compiler does it by default. However this mechanism is just to save you some typing. Types in Java are fully qualified class names, so a String
is really a java.lang.String
object when the code is run. Packages are intended to prevent name clashes and allow two classes to have the same simple name, instead of relying on the old C convention of prefixing types like this. java_lang_String
. This is called namespacing.
BTW, in Java there's the static import construct, which allows to further save typing if you use lots of constants from a certain class. In a compilation unit (a .java file) which declares
import static java.lang.Math.*;
you can use the constant PI
in your code, instead of referencing it through Math.PI
, and the method cos()
instead of Math.cos()
. So for example you can write
double r = cos(PI * theta);
Once you understand that classes are always referenced by their fully qualified name in the final bytecode, you must understand how the class code is actually loaded. This happens the first time an object of that class is created, or the first time a static member of the class is accessed. At this time, the ClassLoader
tries to locate the class and instantiate it. If it can't find the class a NoClassDefFoundError
is thrown (or a a ClassNotFoundException
if the class is searched programmatically). To locate the class, the ClassLoader
usually checks the paths listed in the $CLASSPATH
environment variable.
To solve your problem, it seems you need an applet
element like this
<applet
codebase = "http://san.redenetimoveis.com"
archive="test.jar, core.jar"
code="com.colorfulwolf.webcamapplet.WebcamApplet"
width="550" height="550" >
BTW, you don't need to import the archives in the standard JRE.