You should also consider that the target has a padding and thus use position
instead of offset
. You can also account for a potential nav bar you don't want to be overlapping the target.
const $navbar = $('.navbar');
$('a[href^="#"]').on('click', function(e) {
e.preventDefault();
const scrollTop =
$($(this).attr('href')).position().top -
$navbar.outerHeight();
$('html, body').animate({ scrollTop });
})
This is a quite old question, still comments show, that still people have problems, so here is my solution with following additional features:
CoordinatorLayout
Function - Example (I have this function in an utility class)
public static void animateViewVisibility(final View view, final int visibility)
{
// cancel runnning animations and remove and listeners
view.animate().cancel();
view.animate().setListener(null);
// animate making view visible
if (visibility == View.VISIBLE)
{
view.animate().alpha(1f).start();
view.setVisibility(View.VISIBLE);
}
// animate making view hidden (HIDDEN or INVISIBLE)
else
{
view.animate().setListener(new AnimatorListenerAdapter()
{
@Override
public void onAnimationEnd(Animator animation)
{
view.setVisibility(visibility);
}
}).alpha(0f).start();
}
}
Adjust animation
After calling view.animate()
you can adjust the animation to whatever you want (set duration, set interpolator and more...). You may as well hide a view by scaling it instead of adjusting it's alpha value, just replace the alpha(...)
with scaleX(...)
or scaleY(...)
in the utility method if you want that
When a float
is passed to printf
, it is automatically converted to a double
. This is part of the default argument promotions, which apply to functions that have a variable parameter list (containing ...
), largely for historical reasons. Therefore, the “natural” specifier for a float
, %f
, must work with a double
argument. So the %f
and %lf
specifiers for printf
are the same; they both take a double
value.
When scanf
is called, pointers are passed, not direct values. A pointer to float
is not converted to a pointer to double
(this could not work since the pointed-to object cannot change when you change the pointer type). So, for scanf
, the argument for %f
must be a pointer to float
, and the argument for %lf
must be a pointer to double
.
This one is easy. When you start the installation, Anaconda asks "Destination Folder" as below screenshot. If you are not sure where did default installation go, double click setup file and see what anaconda offers as a default location.
I have encountered two things in this situations.
You may have forgot to implement UITableViewDelegate protocol, or there's no delegation outlet between your class and your table view.
You might have a UIView inside your row that is a first responder and takes your clicks away. Say a UIButton or something similar.
Use
[A-Z]?
to make the letter optional. {1}
is redundant. (Of course you could also write [A-Z]{0,1}
which would mean the same, but that's what the ?
is there for.)
You could improve your regex to
^([0-9]{5})+\s+([A-Z]?)\s+([A-Z])([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})
And, since in most regex dialects, \d
is the same as [0-9]
:
^(\d{5})+\s+([A-Z]?)\s+([A-Z])(\d{3})(\d{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])\d{3}(\d{4})(\d{2})(\d{2})
But: do you really need 11 separate capturing groups? And if so, why don't you capture the fourth-to-last group of digits?
If you want to check if some string is present in another string, use something like String.contains
If you want to check if some pattern is present in a string, append and prepend the pattern with '.*'. The result will accept strings that contain the pattern.
Example: Suppose you have some regex a(b|c) that checks if a string matches ab
or ac
.*(a(b|c)).*
will check if a string contains a ab
or ac
.
A disadvantage of this method is that it will not give you the location of the match.
If you're really lucky, like I was, you can go back into your text editor and hit 'undo'.
I know that's not really a proper answer, but it saved me half a day's work so hopefully it'll do the same for someone else!
If the variant is empty then an error will be thrown. The bullet-proof code is the following:
Public Function GetLength(a As Variant) As Integer
If IsEmpty(a) Then
GetLength = 0
Else
GetLength = UBound(a) - LBound(a) + 1
End If
End Function
return=[entry for tag in tags for entry in entries if tag in entry for entry in entry]
Add the active: false
option (documentation)..
$("#accordion").accordion({ header: "h3", collapsible: true, active: false });
Delete data that is 30 days and older
DELETE FROM Table
WHERE DateColumn < GETDATE()- 30
Use this instead:
string objTextBox = t.Text;
The object t
is the TextBox
. The object you call objTextBox
is assigned the ID
property of the TextBox
.
So better code would be:
TextBox objTextBox = (TextBox)sender;
string theText = objTextBox.Text;
Note this solution will not let the user wait more: the delay of the splash screen depends on the start up time of the application.
When you open any android app you will get by default a some what black screen with the title and icon of the app on top, you can change that by using a style/theme.
First, create a style.xml in values folder and add a style to it.
<style name="splashScreenTheme" parent="@android:style/Theme.DeviceDefault.Light.NoActionBar">
<item name="android:windowBackground">@drawable/splash_screen</item>
</style>
Instead of using @android:style/Theme.DeviceDefault.Light.NoActionBar
you can use any other theme as a parent.
Second, in your app Manifest.xml add android:theme="@style/splashScreenTheme"
to your main activity.
<activity
android:name="MainActivity"
android:label="@string/app_name"
android:theme="@style/splashScreenTheme" >
Third, Update your theme in your onCreate() launch activity.
protected void onCreate(Bundle savedInstanceState) {
// Make sure this is before calling super.onCreate
setTheme(R.style.mainAppTheme);
super.onCreate(savedInstanceState);
}
UPDATE Check out this post.
Thanks to @mat1h and @adelriosantiago
If you have GNU tail available on your system, you can do the following:
tail -n +1000001 huge-file.log
It's the +
character that does what you want. To quote from the man page:
If the first character of K (the number of bytes or lines) is a `+', print beginning with the Kth item from the start of each file.
Thus, as noted in the comment, putting +1000001 starts printing with the first item after the first 1,000,000 lines.
You can do the following:
Example using PHP (you can do this in any language of your choice):
Server:
<?php $years = range(1900, strftime("%Y", time())); ?>
HTML
<select>
<option>Select Year</option>
<?php foreach($years as $year) : ?>
<option value="<?php echo $year; ?>"><?php echo $year; ?></option>
<?php endforeach; ?>
</select>
As an added benefit, this works has a browser compatibility of a 100% ;-)
myHash.each{|item|..}
is returning you array object for item
iterative variable like the following :--
[:company_name, "MyCompany"]
[:street, "Mainstreet"]
[:postcode, "1234"]
[:city, "MyCity"]
[:free_seats, "3"]
You should do this:--
def format
output = Hash.new
myHash.each do |k, v|
output[k] = cleanup(v)
end
output
end
You need to use array_merge_recursive
instead of array_merge
. Of course there can only be one key equal to 'c'
in the array, but the associated value will be an array containing both 3
and 4
.
I have had numerous problems with opencv and only succeded after a gruesome 4-6 months. This is the last problem I have had, but all of the above didn't work. What worked for me was just copying and pasting the opencv_core2*.dll (and opencv_highgui2*.dll which it will ask for since you included this as well) into the release (or debug folder - I'm assuming. Haven't tested this) folder of your project, where your application file is.
Hope this helps!
The main difference is an abstract class can contain default implementation whereas an interface cannot.
An interface is a contract of behaviour without any implementation.
The length of the string in a Base64
format is greater then original: 133%
on average. So it makes sense to first compress it with GZIP
, and then encode to Base64
. It gives a reduction of up to 77%
for strings greater than 200 characters and more. Example:
public static void main(String[] args) throws IOException {
byte[] original = randomString(100).getBytes(StandardCharsets.UTF_8);
byte[] base64 = encodeToBase64(original);
byte[] gzipToBase64 = encodeToBase64(encodeToGZIP(original));
byte[] fromBase64 = decodeFromBase64(base64);
byte[] fromBase64Gzip = decodeFromGZIP(decodeFromBase64(gzipToBase64));
// test
System.out.println("Original: " + original.length + " bytes, 100%");
System.out.println("Base64: " + base64.length + " bytes, "
+ (base64.length * 100 / original.length) + "%");
System.out.println("GZIP+Base64: " + gzipToBase64.length + " bytes, "
+ (gzipToBase64.length * 100 / original.length) + "%");
//Original: 3700 bytes, 100%
//Base64: 4936 bytes, 133%
//GZIP+Base64: 2868 bytes, 77%
System.out.println(Arrays.equals(original, fromBase64)); // true
System.out.println(Arrays.equals(original, fromBase64Gzip)); // true
}
public static byte[] decodeFromBase64(byte[] arr) {
return Base64.getDecoder().decode(arr);
}
public static byte[] encodeToBase64(byte[] arr) {
return Base64.getEncoder().encode(arr);
}
public static byte[] decodeFromGZIP(byte[] arr) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(arr);
GZIPInputStream gzip = new GZIPInputStream(bais);
return gzip.readAllBytes();
}
public static byte[] encodeToGZIP(byte[] arr) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(baos);
gzip.write(arr);
gzip.finish();
return baos.toByteArray();
}
public static String randomString(int count) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < count; i++) {
str.append(" ").append(UUID.randomUUID().toString());
}
return str.toString();
}
Check out the language reference:
http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx
expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)
You cannot return value after resolving promise. Instead call another function when promise is resolved:
function justTesting() {
promise.then(function(output) {
// instead of return call another function
afterResolve(output + 1);
});
}
function afterResolve(result) {
// do something with result
}
var test = justTesting();
A funny & simple sed
and tac
solution :
n=4
tac file.txt | sed "1,$n{d}" | tac
NOTE
"
are needed for the shell to evaluate the $n
variable in sed
command. In single quotes, no interpolate will be performed.tac
is a cat
reversed, see man 1 tac
{}
in sed
are there to separate $n
& d
(if not, the shell try to interpolate non existent $nd
variable)I was getting the same issue with a different application,
Faulting application name: javaw.exe, version: 8.0.51.16, time stamp: 0x55763d32
Faulting module name: mscorwks.dll, version: 2.0.50727.5485, time stamp: 0x53a11d6c
Exception code: 0xc0000005
Fault offset: 0x0000000000501090
Faulting process id: 0x2960
Faulting application start time: 0x01d0c39a93c695f2
Faulting application path: C:\Program Files\Java\jre1.8.0_51\bin\javaw.exe
Faulting module path:C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorwks.dll
I was using the The Enhanced Mitigation Experience Toolkit (EMET) from Microsoft and I found by disabling the EMET features on javaw.exe in my case as this was the faulting application, it enabled my application to run successfully. Make sure you don't have any similar software with security protections on memory.
There is a conflict between your build settings and the default build settings that Cocoapods wants. To see the Cocoapods build settings, view the .xcconfig file(s) in Pods/Target Support Files/Pods-${PROJECTNAME}/ in your project. For me this file contains:
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers" "${PODS_ROOT}/Headers/Commando"
OTHER_LDFLAGS = -ObjC -framework Foundation -framework QuartzCore -framework UIKit
PODS_ROOT = ${SRCROOT}/Pods
If you are happy with the Cocoapods settings, then go to Build Settings for your project, find the appropriate setting and hit the Delete key. This will use the setting from Cocoapods.
On the other hand, if you have a custom setting that you need to use, then add $(inherited) to that setting.
Darin Dimitrov's solution worked for me with one exception. When I submitted the partial view with (intentional) validation errors, I ended up with duplicate forms being returned in the dialog:
To fix this I had to wrap the Html.BeginForm in a div:
<div id="myForm">
@using (Html.BeginForm("CreateDialog", "SupportClass1", FormMethod.Post, new { @class = "form-horizontal" }))
{
//form contents
}
</div>
When the form was submitted, I cleared the div in the success function and output the validated form:
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#myForm').html('');
$('#result').html(result);
}
});
}
return false;
});
});
As can be seen from previous posts, one can argue that if class functionality needs to be circumvented then something is wrong in the class architecture. That might be true, but one cannot always restructure or refactor the class structure on a large mature project. The various levels of change management might be one problem, but to keep existing functionality operating the same after refactoring is not always a trivial task, especially if time constraints apply. On a mature project it can be quite an undertaking to keep various regression tests from passing after a code restructure; there are often obscure "oddities" that show up. We had a similar problem in some cases inherited functionality should not execute (or should perform something else). The approach we followed below, was to put the base code that need to be excluded in a separate virtual function. This function can then be overridden in the derived class and the functionality excluded or altered. In this example "Text 2" can be prevented from output in the derived class.
public class Base
{
public virtual void Foo()
{
Console.WriteLine("Hello from Base");
}
}
public class Derived : Base
{
public override void Foo()
{
base.Foo();
Console.WriteLine("Text 1");
WriteText2Func();
Console.WriteLine("Text 3");
}
protected virtual void WriteText2Func()
{
Console.WriteLine("Text 2");
}
}
public class Special : Derived
{
public override void WriteText2Func()
{
//WriteText2Func will write nothing when
//method Foo is called from class Special.
//Also it can be modified to do something else.
}
}
See the documentation on MDN about expressions and operators and statements.
this
keyword:var x = function()
vs. function x()
— Function declaration syntax(function(){
…})()
— IIFE (Immediately Invoked Function Expression)(function(){…})();
work but function(){…}();
doesn't?(function(){…})();
vs (function(){…}());
!function(){…}();
- What does the exclamation mark do before the function?+function(){…}();
- JavaScript plus sign in front of function expression!
vs leading semicolon(function(window, undefined){…}(window));
someFunction()()
— Functions which return other functions=>
— Equal sign, greater than: arrow function expression syntax|>
— Pipe, greater than: Pipeline operatorfunction*
, yield
, yield*
— Star after function
or yield
: generator functions[]
, Array()
— Square brackets: array notationIf the square brackets appear on the left side of an assignment ([a] = ...
), or inside a function's parameters, it's a destructuring assignment.
{key: value}
— Curly brackets: object literal syntax (not to be confused with blocks)If the curly brackets appear on the left side of an assignment ({ a } = ...
) or inside a function's parameters, it's a destructuring assignment.
`
…${
…}
…`
— Backticks, dollar sign with curly brackets: template literals`…${…}…`
code from the node docs mean?/
…/
— Slashes: regular expression literals$
— Dollar sign in regex replace patterns: $$
, $&
, $`
, $'
, $n
()
— Parentheses: grouping operatorobj.prop
, obj[prop]
, obj["prop"]
— Square brackets or dot: property accessors?.
, ?.[]
, ?.()
— Question mark, dot: optional chaining operator::
— Double colon: bind operatornew
operator...iter
— Three dots: spread syntax; rest parameters(...args) => {}
— What is the meaning of “…args” (three dots) in a function definition?[...iter]
— javascript es6 array feature […data, 0] “spread operator”{...props}
— Javascript Property with three dots (…)++
, --
— Double plus or minus: pre- / post-increment / -decrement operatorsdelete
operatorvoid
operator+
, -
— Plus and minus: addition or concatenation, and subtraction operators; unary sign operators|
, &
, ^
, ~
— Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators~1
equal -2
?%
— Percent sign: remainder operator&&
, ||
, !
— Double ampersand, double pipe, exclamation point: logical operators??
— Double question mark: nullish-coalescing operator**
— Double star: power operator (exponentiation)x ** 2
is equivalent to Math.pow(x, 2)
==
, ===
— Equal signs: equality operators!=
, !==
— Exclamation point and equal signs: inequality operators<<
, >>
, >>>
— Two or three angle brackets: bit shift operators?
…:
… — Question mark and colon: conditional (ternary) operator=
— Equal sign: assignment operator%=
— Percent equals: remainder assignment+=
— Plus equals: addition assignment operator&&=
, ||=
, ??=
— Double ampersand, pipe, or question mark, followed by equal sign: logical assignments||=
(or equals) in JavaScript?,
— Comma operator{
…}
— Curly brackets: blocks (not to be confused with object literal syntax)var
, let
, const
— Declaring variableslabel:
— Colon: labels#
— Hash (number sign): Private methods or private fieldsThis was the clearest solution for me
var dlg2 = $('#dialog2').dialog({
position: "center",
autoOpen: false,
width: 600,
buttons: {
"Ok": function() {
$(this).dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
dlg2.parent().appendTo('form:first');
$('#dialog_link2').click(function(){
dlg2.dialog('open');
All the content inside the dlg2
will be available to insert in your database. Don't forget to change the dialog
variable to match yours.
for mysql version 5
alter table *table_name* change column *old_column_name* *new_column_name* datatype();
You are using jQuery(document).ready(function($) {}
means here you are using jQuery
instead of $
. So to resolve your issue use following code.
jQuery("#submittername").text(submitter_name);
This will resolve your problem.
There's also an improved version of Pan Yan suggestion. It adds the button that shows code cells back:
%%html
<style id=hide>div.input{display:none;}</style>
<button type="button"
onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">
Show inputs</button>
Or python:
# Run me to hide code cells
from IPython.core.display import display, HTML
display(HTML(r"""<style id=hide>div.input{display:none;}</style><button type="button"onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">Show inputs</button>"""))
You can try this with Color.FromArgb
:
Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));
if(isset($_SESSION))
{}
else
{}
It might be most sensible to use multiprocessing.Pool
which produces a pool of worker processes based on the max number of cores available on your system, and then basically feeds tasks in as the cores become available.
The example from the standard docs (http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers) shows that you can also manually set the number of cores:
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
pool = Pool(processes=4) # start 4 worker processes
result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously
print result.get(timeout=1) # prints "100" unless your computer is *very* slow
print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
And it's also handy to know that there is the multiprocessing.cpu_count()
method to count the number of cores on a given system, if needed in your code.
Edit: Here's some draft code that seems to work for your specific case:
import multiprocessing
def f(name):
print 'hello', name
if __name__ == '__main__':
pool = multiprocessing.Pool() #use all available cores, otherwise specify the number you want as an argument
for i in xrange(0, 512):
pool.apply_async(f, args=(i,))
pool.close()
pool.join()
The sudo password is stored as a variable called ansible_sudo_pass
.
You can set this variable in a few ways:
Per host, in your inventory hosts file (inventory/<inventoryname>/hosts
)
[server]
10.0.0.0 ansible_sudo_pass=foobar
Per group, in your inventory groups file (inventory/<inventoryname>/groups
)
[server:vars]
ansible_sudo_pass=foobar
Per group, in group vars (group_vars/<groupname>/ansible.yml
)
ansible_sudo_pass: "foobar"
Per group, encrypted (ansible-vault create group_vars/<groupname>/ansible.yml
)
ansible_sudo_pass: "foobar"
You can update the existing package-lock.json file instead of creating a new one. Just change the version number to a different one.
{ "name": "theme","version": "1.0.1", "description": "theme description"}
I needed to find a way to do this too, using numbers from different places and not in a collection. I was sure there was a method to do this in c#...though by the looks of it I'm muddling my languages...
Anyway, I ended up writing a couple of generic methods to do it...
static T Max<T>(params T[] numberItems)
{
return numberItems.Max();
}
static T Min<T>(params T[] numberItems)
{
return numberItems.Min();
}
...call them this way...
int intTest = Max(1, 2, 3, 4);
float floatTest = Min(0f, 255.3f, 12f, -1.2f);
You can use subSequence , it's same as substr in C
Str.subSequence(int Start , int End)
If you are running multiple extensions that perform ad or script blocking you will need to
individually update each one to your whitelist
Taking from this source, here are some of the extensions that may cause the case and how to deal with them.
Adblock Plus
Firefox Tracking Protection
In Firefox “Tracking Protection” may activate our adblock notice. It can be temporarily disabled for a browsing session by clicking the “shield” icon in the url bar if visible and following the instructions.
For further details on Tracking Protection please review Mozilla’s support.
Adblock
Ghostery
uBlock / uBlock Origin
Click the uBlock / uBlock Origin icon.
Click the “power” button in the menu that appears to whitelist the current web site.
Click the reload icon to reload the page you were viewing.
Disconnect
Kaspersky Ant-Banner
Please review How to configure Anti-Banner in Kaspersky Total Security for information on how to whitelist with Kaspersky Total Security.
Pure Javascript solution
theId.onclick = () => window.scrollTo({top: 0})
If you want smooth scrolling
theId.onclick = () => window.scrollTo({ top: 0, behavior: `smooth` })
If you use Guava (former Google Collections) library there is a solution:
SetView<Number> difference = com.google.common.collect.Sets.difference(test2, test1);
The returned SetView
is a Set
, it is a live representation you can either make immutable or copy to another set. test1
and test2
are left intact.
I found something about JDK 1.0 and 1.1 and >= 1.2:
In JDK 1.0.x and 1.1.x the hashCode function for long Strings worked by sampling every nth character. This pretty well guaranteed you would have many Strings hashing to the same value, thus slowing down Hashtable lookup. In JDK 1.2 the function has been improved to multiply the result so far by 31 then add the next character in sequence. This is a little slower, but is much better at avoiding collisions. Source: http://mindprod.com/jgloss/hashcode.html
Something different, because you seem to need a number: How about using CRC32 or MD5 instead of hashcode and you are good to go - no discussions and no worries at all...
If you are using the Anaconda distribution, make sure when installing it that you check the "Change PATH" option.
You can use print_r to get human-readable output. But to display it as text we add "echo '';"
echo ''; print_r($row);
I ran into this same issue. I needed to get the file size and modified date of 90,000 files on a network share. Using Java, and being as minimalistic as possible, it would take a very long time. (I needed to get the URL from the file, and the path of the object as well. So its varied somewhat, but more than an hour.) I then used a native Win32 executable, and did the same task, just dumping the file path, modified, and size to the console, and executed that from Java. The speed was amazing. The native process, and my string handling to read the data could process over 1000 items a second.
So even though people down ranked the above comment, this is a valid solution, and did solve my issue. In my case I knew the folders I needed the sizes of ahead of time, and I could pass that in the command line to my win32 app. I went from hours to process a directory to minutes.
The issue did also seem to be Windows specific. OS X did not have the same issue and could access network file info as fast as the OS could do so.
Java File handling on Windows is terrible. Local disk access for files is fine though. It was just network shares that caused the terrible performance. Windows could get info on the network share and calculate the total size in under a minute too.
--Ben
char(13)
is CR
. For DOS-/Windows-style CRLF
linebreaks, you want char(13)+char(10)
, like:
'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'
You can use http://www.fontsquirrel.com/fontface/generator to encode any font for websites. It'll generate the code to include the font.
I don't really use it for fonts over 30px. They look much better as an image (because images are anti-aliased, and some browsers don't anti-alias fonts in the browser).
See: http://www.truetype-typography.com/ttalias.htm
Hope that helps...
The answer given by P????? creates a nullable bool, not a bool, which may be fine for you. For example in C# it would create: bool? AdminApproved
not bool AdminApproved
.
If you need to create a bool (defaulting to false):
ALTER TABLE person
ADD AdminApproved BIT
DEFAULT 0 NOT NULL;
No need to do your own implementation. I can recommend using geolocationmarker
from google-maps-utility-library-v3.
This would be an optimized way of doing it
StringBuilder sb = new StringBuilder();
for (String n : arr) {
sb.append("'").append(n).append("',");
}
if(sb.length()>0)
sb.setLength(sbDiscrep.length()-1);
return sb.toString();
Let the command you are trying to pass be
os.system('x')
then you covert it to a statement
t = os.system('x')
now the python will be waiting for the output from the commandline so that it could be assigned to the variable t
.
I am just wondering why to use some libraries for JWT token decoding and verification at all.
Encoded JWT token can be created using following pseudocode
var headers = base64URLencode(myHeaders);
var claims = base64URLencode(myClaims);
var payload = header + "." + claims;
var signature = base64URLencode(HMACSHA256(payload, secret));
var encodedJWT = payload + "." + signature;
It is very easy to do without any specific library. Using following code:
using System;
using System.Text;
using System.Security.Cryptography;
public class Program
{
// More info: https://stormpath.com/blog/jwt-the-right-way/
public static void Main()
{
var header = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";
var claims = "{\"sub\":\"1047986\",\"email\":\"[email protected]\",\"given_name\":\"John\",\"family_name\":\"Doe\",\"primarysid\":\"b521a2af99bfdc65e04010ac1d046ff5\",\"iss\":\"http://example.com\",\"aud\":\"myapp\",\"exp\":1460555281,\"nbf\":1457963281}";
var b64header = Convert.ToBase64String(Encoding.UTF8.GetBytes(header))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
var b64claims = Convert.ToBase64String(Encoding.UTF8.GetBytes(claims))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
var payload = b64header + "." + b64claims;
Console.WriteLine("JWT without sig: " + payload);
byte[] key = Convert.FromBase64String("mPorwQB8kMDNQeeYO35KOrMMFn6rFVmbIohBphJPnp4=");
byte[] message = Encoding.UTF8.GetBytes(payload);
string sig = Convert.ToBase64String(HashHMAC(key, message))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
Console.WriteLine("JWT with signature: " + payload + "." + sig);
}
private static byte[] HashHMAC(byte[] key, byte[] message)
{
var hash = new HMACSHA256(key);
return hash.ComputeHash(message);
}
}
The token decoding is reversed version of the code above.To verify the signature you will need to the same and compare signature part with calculated signature.
UPDATE: For those how are struggling how to do base64 urlsafe encoding/decoding please see another SO question, and also wiki and RFCs
Why not just convert all <button>
to <span>
with type="button"
and then style with your normal css button classes? Just confirmed that this works in IE11.
System.GC.Collect()
forces garbage collector to run. This is not recommended but can be used if situations arise.
Note my use of
t.format
comes from using Moment.js, it is not part of JavaScript's standardDate
prototype.
A Unix timestamp is the number of seconds since 1970-01-01 00:00:00 UTC.
The presence of the +0200
means the numeric string is not a Unix timestamp as it contains timezone adjustment information. You need to handle that separately.
If your timestamp string is in milliseconds, then you can use the milliseconds constructor and Moment.js to format the date into a string:
var t = new Date( 1370001284000 );
var formatted = t.format("dd.mm.yyyy hh:MM:ss");
If your timestamp string is in seconds, then use setSeconds
:
var t = new Date();
t.setSeconds( 1370001284 );
var formatted = t.format("dd.mm.yyyy hh:MM:ss");
If you are searching by the fieldname1
value, try this:
var r = exitDictionary
.Select(i => i.Value).Cast<Dictionary<string, object>>()
.Where(d => d.ContainsKey("fieldname1"))
.Select(d => d["fieldname1"]).Cast<List<Dictionary<string, string>>>()
.SelectMany(d1 =>
d1
.Where(d => d.ContainsKey("valueTitle"))
.Select(d => d["valueTitle"])
.Where(v => v != null)).ToList();
If you are looking by the type of the value in the subDictionary
(Dictionary<string, object>
explicitly), you may do this:
var r = exitDictionary
.Select(i => i.Value).Cast<Dictionary<string, object>>()
.SelectMany(d=>d.Values)
.OfType<List<Dictionary<string, string>>>()
.SelectMany(d1 =>
d1
.Where(d => d.ContainsKey("valueTitle"))
.Select(d => d["valueTitle"])
.Where(v => v != null)).ToList();
Both alternatives will return:
title1
title2
title3
title1
title2
title3
U can use something like this....
function (field,value) {
var newItemOrder= value;
// Make sure user hasnt already added this item
angular.forEach(arr, function(item) {
if (newItemOrder == item.value) {
arr.splice(arr.pop(item));
} });
submitFields.push({"field":field,"value":value});
};
If you want to do it within the form's __init__
method for some reason, you can manipulate the initial
dict:
class MyForm(forms.Form):
my_field = forms.CharField(max_length=255)
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.initial['my_field'] = 'Initial value'
I have a raspberry pi, and I am using python web server (using Flask). I have tried everything above, the only solution is to close the terminal(shell) and open it again. Or restart the raspberry pi, because nothing stops that webserver...
I know this question is very old, but I was making similar thing in my kotlin app recently. So here is an example if anyone needs it:
val dfs = DecimalFormatSymbols.getInstance(Locale.getDefault())
val bigD = BigDecimal("1e+30")
val formattedBigD = DecimalFormat("#,##0.#",dfs).format(bigD)
Result displaying $formattedBigD:
1,000,000,000,000,000,000,000,000,000,000
You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.
If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:
SQL Developer has a similar feature. See the "Load" link below:
If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.
Assuming ACL is complete, you'd pull the image like this:
declare
l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
l_http_request UTL_HTTP.req;
l_http_response UTL_HTTP.resp;
l_raw RAW(2000);
l_blob BLOB;
begin
-- Important: setup ACL access list first!
DBMS_LOB.createtemporary(l_blob, FALSE);
l_http_request := UTL_HTTP.begin_request(l_url);
l_http_response := UTL_HTTP.get_response(l_http_request);
-- Copy the response into the BLOB.
BEGIN
LOOP
UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
END LOOP;
EXCEPTION
WHEN UTL_HTTP.end_of_body THEN
UTL_HTTP.end_response(l_http_response);
END;
insert into my_pics (pic_id, pic) values (102, l_blob);
commit;
DBMS_LOB.freetemporary(l_blob);
end;
Hope that helps.
SELECT * FROM table
WHERE exec_datetime BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW();
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
You can access tempfile in Spring by casting if the class of interface MultipartFile
is CommonsMultipartFile
.
public File getTempFile(MultipartFile multipartFile)
{
CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
FileItem fileItem = commonsMultipartFile.getFileItem();
DiskFileItem diskFileItem = (DiskFileItem) fileItem;
String absPath = diskFileItem.getStoreLocation().getAbsolutePath();
File file = new File(absPath);
//trick to implicitly save on disk small files (<10240 bytes by default)
if (!file.exists()) {
file.createNewFile();
multipartFile.transferTo(file);
}
return file;
}
To get rid of the trick with files less than 10240 bytes maxInMemorySize
property can be set to 0 in @Configuration
@EnableWebMvc
class. After that, all uploaded files will be stored on disk.
@Bean(name = "multipartResolver")
public CommonsMultipartResolver createMultipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
resolver.setMaxInMemorySize(0);
return resolver;
}
Using HttpClient (Http's replacement) in Angular 4.3+, the entire mapping/casting process is made simpler/eliminated.
Using your CountryData class, you would define a service method like this:
getCountries() {
return this.httpClient.get<CountryData[]>('http://theUrl.com/all');
}
Then when you need it, define an array like this:
countries:CountryData[] = [];
and subscribe to it like this:
this.countryService.getCountries().subscribe(countries => this.countries = countries);
A complete setup answer is posted here also.
while importing libraries use the exact path to a file, including the directory relative to the current file, for example:
import Footer from './Footer/index.jsx'
import AddTodo from '../containers/AddTodo/index.jsx'
import VisibleTodoList from '../containers/VisibleTodoList/index.jsx'
Hope this may help
I believe that if you download the offline ISO image file, and use that to install Visual Studio Express, you won't have to register.
Go here and find the link that says "All - Offline Install ISO image file". Click on it to expand it, select your language, and then click "Download".
Otherwise, it's possible that online registration is simply down for a while, as the error message indicates. You have 30 days before it expires, so give it a few days before starting to panic.
Execute the same commands but replace the "-A" with "-D". For example:
iptables -A ...
becomes
iptables -D ...
Depending on the nature of the duplicate rows, it looks like all you want is to have case-sensitivity on those columns. Setting the collation on these columns should be what you're after:
SELECT DISTINCT p.IDNO COLLATE SQL_Latin1_General_CP1_CI_AS, p.FirstName COLLATE SQL_Latin1_General_CP1_CI_AS, p.LastName COLLATE SQL_Latin1_General_CP1_CI_AS
FROM people P
No need to make the nested class as static but it must be public
public class Test {
public static void main(String[] args) {
Shape shape = new Shape();
Shape s = shape.new Shape.ZShape();
}
}
SELECT
t.A,
t.B,
t.C,
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS number
FROM tableZ AS t
See working example at SQLFiddle
Of course, you may want to define the row-numbering order – if so, just swap OVER (ORDER BY (SELECT 1))
for, e.g., OVER (ORDER BY t.C)
, like in a normal ORDER BY
clause.
You can hold onto the percentage as decimal (value \ total)
and then when you want to render to a human you can make use of Habeeb's answer or using string interpolation you could have something even cleaner:
var displayPercentage = $"{(decimal)value / total:P}";
or
//Calculate percentage earlier in code
decimal percentage = (decimal)value / total;
...
//Now render percentage
var displayPercentage = $"{percentage:P}";
This technique is usually used for multiple axis in a figure. In this context it is often required to have a colorbar that corresponds in size with the result from imshow. This can be achieved easily with the axes grid tool kit:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
im = ax.imshow(data, cmap='bone')
fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()
Do this:
border: solid #000;
border-width: 0 1px;
Live demo: http://jsfiddle.net/aFzKy/
You can use the _contains function from the underscore.js library to achieve this:
if (_.contains(haystack, needle)) {
console.log("Needle found.");
};
$("#myinput").attr('type') == 'checkbox'
There are two things
Disable firewall if any or add exception or check if u have correct driver file. Disable any antivirus if any
and also make sure your driver type is mysql.jdbc.driver
.
This is the correct way:
public class JSONParser extends AsyncTask <String, Void, String>{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
@Override
protected String doInBackground(String... params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse getResponse = httpClient.execute(httpPost);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
//HttpResponse httpResponse = httpClient.execute(httpPost);
//HttpEntity httpEntity = httpResponse.getEntity();
is = getResponseEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
Log.d("IO", e.getMessage().toString());
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
protected void onPostExecute(String page)
{
//onPostExecute
}
}
To call it (from main):
mJSONParser = new JSONParser();
mJSONParser.execute();
There's whereIn()
:
$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();
See the example on the filter page. Use an object, and set the color in the color property:
Search by color: <input type="text" ng-model="search.color">
<div ng-repeat="product in products | filter:search">
SOLUTION
Remove the Quotes around the /p:PublishDir setting
i.e.
Instead of quotes
/p:PublishDir="\\BSIIS3\c$\DATA\WEBSITES\benesys.net\benesys.net\TotalEducationTest\"
Use no quotes
/p:PublishDir=\\BSIIS3\c$\DATA\WEBSITES\benesys.net\benesys.net\TotalEducationTest\
I am sorry I did not post my finding sooner. I actually had to research again to see what needed to be changed. Who would have thought removing quotes would have worked? I discovered this when viewing a coworkers build for another solution and noticed it did not have quotes.
I found that the above answer caused me an exception when I tried to instantiate the parser. I found the following code that resolved this at http://docstore.mik.ua/orelly/xml/sax2/ch03_02.htm.
import org.xml.sax.*;
import javax.xml.parsers.*;
XMLReader parser;
try {
SAXParserFactory factory;
factory = SAXParserFactory.newInstance ();
factory.setNamespaceAware (true);
parser = factory.newSAXParser ().getXMLReader ();
// success!
} catch (FactoryConfigurationError err) {
System.err.println ("can't create JAXP SAXParserFactory, "
+ err.getMessage ());
} catch (ParserConfigurationException err) {
System.err.println ("can't create XMLReader with namespaces, "
+ err.getMessage ());
} catch (SAXException err) {
System.err.println ("Hmm, SAXException, " + err.getMessage ());
}
>>> names = ['King', 'Queen', 'Joker']
>>> any(n in 'King and john' for n in names)
True
>>> all(n in 'King and Queen' for n in names)
False
It just reduce several line of code into one. You don't have to write lengthy code like:
for n in names:
if n in 'King and john':
print True
else:
print False
You need to setup a SDK for Java projects, like @rizzletang said, but you don't need to create a new project, you can do it from the Welcome
screen.
On the bottom right, select Configure > Project Defaults > Project Structure
:
Picking the Project
tab on the left will show that you have no SDK selected:
Just click the New...
button on the right hand side of the dropdown and point it to your JDK. After that, you can go back to the import screen and it should just show up.
Add a border
to the regular item, the same color
as the background
, so that it cannot be seen. That way the item has a border: 1px
whether it is being hovered or not.
If you want to disable all constraints in the database just run this code:
-- disable all constraints
EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
To switch them back on, run: (the print is optional of course and it is just listing the tables)
-- enable all constraints
exec sp_MSforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment).
If you are deleting all the data you may find this solution to be helpful.
Also sometimes it is handy to disable all triggers as well, you can see the complete solution here.
If it says the API key is listed as a header, more than likely you need to set it in the headers
option of your http request. Normally something like this :
headers: {'Authorization': '[your API key]'}
Here is an example from another Question
$http({method: 'GET', url: '[the-target-url]', headers: {
'Authorization': '[your-api-key]'}
});
Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :
$.ajax({
type : "GET",
url : "[the-target-url]",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
success : function(result) {
//set your variable to the result
},
error : function(result) {
//handle the error
}
});
I got this from this question and I'm at work so I can't test it at the moment but looks solid
Edit 2: Pretty sure you should be able to use this line :
headers: {'Authorization': '[your API key]'},
instead of the beforeSend
line in the first edit. This may be simpler for you
See also boost::format:
#include <boost/format.hpp>
std::string var = (boost::format("somtext %s sometext %s") % somevar % somevar).str();
try current($xml->code[0]->lat)
it returns element under current pointer of array, which is 0, so you will get value
Try this library (javadoc is here), min API level is 7:
dependencies {
compile 'com.shamanland:fab:0.0.8'
}
It provides single widget with ability to customize it via Theme, xml or java-code.
It's very simple to use. There are available normal
and mini
implementation according to Promoted Actions pattern.
<com.shamanland.fab.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_action_my"
app:floatingActionButtonColor="@color/my_fab_color"
app:floatingActionButtonSize="mini"
/>
Try to compile the demo app. There is exhaustive example: light and dark themes, using with ListView
, align between two Views.
UPDATE of Kunal Noel Answer
stringTest.All(char.IsDigit);
// This returns true if all characters of the string are digits.
But, for this case we have that empty strings will pass that test, so, you can:
if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
// Do your logic here
}
I solved a similar problem with one of our users who was used only for ssh port forwarding so he don't need to have access to PTY and it was prohibited in .ssh/authorized_keys file:
no-pty ssh-rsa AAA...nUB9 someuser
So when you tried to log in to this user, only message
PTY allocation request failed on channel 0
was returned. So check your user's authorized_keys file.
write it like this
p {
padding-bottom: 3cm;
}
or
p {
margin-bottom: 3cm;
}
Works for Safari, Firefox, and IE7 (haven't tried IE8). Simple test:
<button onclick='$("body,html").scrollTop(0);'> Top </button>
<button onclick='$("body,html").scrollTop(100);'> Middle </button>
<button onclick='$("body,html").scrollTop(250);'> Bottom </button>
Most examples use either one or both, but in reverse order (i.e., "html,body").
Cheers.
(And semantic purists out there, don't bust my chops -- I've been looking for this for weeks, this is a simple example, that validates XHTML strict. Feel free to create 27 layers of abstraction and event binding bloat for your OCD peace of mind. Just please give due credit, since the folks in the jQuery forums, SO, and the G couldn't cough up the goods. Peace out.)
Although it is not an IntelliJ option, you could use a simple Bash command (if your operating system is Linux/Unix). Go to your source directory and type:
find . -type f -name '*.java' | xargs cat | wc -l
Simply in Code Behind Page use:-
SqlConnection con = new SqlConnection("Data Source = DellPC; Initial Catalog = Account; user = sa; password = admin");
It Should Work Just Fine
Did you give yourself the rights to execute the script?
The following command as super user will do this for you:
sudo chmod 755 'filename'
For details you should read the man page of chmod.
The answer I was looking for is at https://unix.stackexchange.com/a/9557/114862.
Using the
-c
flag when the local file is of greater or equal size to the server version will avoid re-downloading.
For this specific use-case using try..except..else
is the cleanest solution, the else
clause will be executed if no exception was raised.
NOTE: The else
clause must follow all except
clauses
for i in iterator:
try:
# Do something.
except:
# Handle exception
else:
# Continue doing something
For me, just setting the compatibility level to higher level works fine. To see C.Level :
select compatibility_level from sys.databases where name = [your_database]
java.util.Date date = ...
DateTime dateTime = new DateTime(date);
Make sure date
isn't null
, though, otherwise it acts like new DateTime()
- I really don't like that.
If you don't extend JFrame
and use JFrame
itself in variable, you can use:
frame.dispose();
System.exit(0);
To get the current memory_limit value, run:
php -r "echo ini_get('memory_limit').PHP_EOL;"
Try increasing the limit in your php.ini
file (ex. /etc/php5/cli/php.ini
for Debian-like systems):
; Use -1 for unlimited or define an explicit value like 2G
memory_limit = -1
Or, you can increase the limit with a command-line argument:
php -d memory_limit=-1 composer.phar require hwi/oauth-bundle php-http/guzzle6-adapter php-http/httplug-bundle
To get loaded php.ini files location try:
php --ini
Another quick solution:
php composer.phar COMPOSER_MEMORY_LIMIT=-1 require hwi/oauth-bundle php-http/guzzle6-adapter php-http/httplug-bundle
Well, even in Java 8, long
and int
are still signed, only some methods treat them as if they were unsigned. If you want to write unsigned long
literal like that, you can do
static long values = Long.parseUnsignedLong("18446744073709551615");
public static void main(String[] args) {
System.out.println(values); // -1
System.out.println(Long.toUnsignedString(values)); // 18446744073709551615
}
We can achieve that like this:
public static IWebElement WaitForObject(IWebDriver DriverObj, By by, int TimeOut = 30)
{
try
{
WebDriverWait Wait1 = new WebDriverWait(DriverObj, TimeSpan.FromSeconds(TimeOut));
var WaitS = Wait1.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.PresenceOfAllElementsLocatedBy(by));
return WaitS[0];
}
catch (NoSuchElementException)
{
Reports.TestStep("Wait for Element(s) with xPath was failed in current context page.");
throw;
}
}
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(handleScreenTap(sender:)))
self.view.addGestureRecognizer(tap)}
then you use this function
func handleScreenTap(sender: UITapGestureRecognizer) {
self.view.endEditing(true)
}
To simplify, make sure to add a hash bang to the top of your ExecStart script, i.e.
#!/bin/bash
python -u alwayson.py
As reply to Jonathan Sampson, this is the best way to do it, without a clearing div:
.container { width:450px; overflow:hidden }
.cube { width:150px; height:150px; float:left }
<div class="container">
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
</div>
I have a similar problem but all mentioned requirements are met. In my case I try to save some entity class (Type of OBJEKTE) back to the DB. Other places do work but only in this case it fails and raises this exception.
My solution (HACK) was to re-map the objet of type OBJEKTE again and store it then. Suddenly it works. But don't ask why.
OBJEKTE t = _mapper.Map<OBJEKTE>(inparam);
OBJEKTE res = await _objRepo.UpdateAsync(t);
If inparam would go straight to UpdateAsync() it cannot find a matching persistor.
It could be explained by the way NH does this. It derives a proxy from your mapping class and implements the properties with dirty handling included. See this:
t.GetType()
{Name = "OBJEKTE" FullName = "MyComp.Persistence.OBJEKTE"}
inparam.GetType()
{Name = "OBJEKTEProxyForFieldInterceptor" FullName = "OBJEKTEProxyForFieldInterceptor"}
The fun thing though is that the source of inparam
is in fact the NH repository itself. Anyways. I stay with this reassign hack for the next time being.
Is there a method equivalent to getJSONArray in org.json so that I have proper error handling in case it isn't an array?
It depends on your input; i.e. the stuff you fetch from the URL. If the value of the "datasets" attribute is an associative array rather than a plain array, you will get a ClassCastException
.
But then again, the correctness of your old version also depends on the input. In the situation where your new version throws a ClassCastException
, the old version will throw JSONException
. Reference: http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)
On red hat linux I just use echo :
echo $(cat /some/file/name)
This gives me all records of a file on just one line.
To select rows whose column value equals a scalar, some_value
, use ==
:
df.loc[df['column_name'] == some_value]
To select rows whose column value is in an iterable, some_values
, use isin
:
df.loc[df['column_name'].isin(some_values)]
Combine multiple conditions with &
:
df.loc[(df['column_name'] >= A) & (df['column_name'] <= B)]
Note the parentheses. Due to Python's operator precedence rules, &
binds more tightly than <=
and >=
. Thus, the parentheses in the last example are necessary. Without the parentheses
df['column_name'] >= A & df['column_name'] <= B
is parsed as
df['column_name'] >= (A & df['column_name']) <= B
which results in a Truth value of a Series is ambiguous error.
To select rows whose column value does not equal some_value
, use !=
:
df.loc[df['column_name'] != some_value]
isin
returns a boolean Series, so to select rows whose value is not in some_values
, negate the boolean Series using ~
:
df.loc[~df['column_name'].isin(some_values)]
For example,
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
# A B C D
# 0 foo one 0 0
# 1 bar one 1 2
# 2 foo two 2 4
# 3 bar three 3 6
# 4 foo two 4 8
# 5 bar two 5 10
# 6 foo one 6 12
# 7 foo three 7 14
print(df.loc[df['A'] == 'foo'])
yields
A B C D
0 foo one 0 0
2 foo two 2 4
4 foo two 4 8
6 foo one 6 12
7 foo three 7 14
If you have multiple values you want to include, put them in a
list (or more generally, any iterable) and use isin
:
print(df.loc[df['B'].isin(['one','three'])])
yields
A B C D
0 foo one 0 0
1 bar one 1 2
3 bar three 3 6
6 foo one 6 12
7 foo three 7 14
Note, however, that if you wish to do this many times, it is more efficient to
make an index first, and then use df.loc
:
df = df.set_index(['B'])
print(df.loc['one'])
yields
A C D
B
one foo 0 0
one bar 1 2
one foo 6 12
or, to include multiple values from the index use df.index.isin
:
df.loc[df.index.isin(['one','two'])]
yields
A C D
B
one foo 0 0
one bar 1 2
two foo 2 4
two foo 4 8
two bar 5 10
one foo 6 12
let str = "abc"
let substr = str.substringToIndex(str.endIndex.predecessor()) // "ab"
As an complement to Stefan Steiger answer: (as it doesn't look nice as a comment)
Extending String prototype:
String.prototype.b64encode = function() {
return btoa(unescape(encodeURIComponent(this)));
};
String.prototype.b64decode = function() {
return decodeURIComponent(escape(atob(this)));
};
Usage:
var str = "äöüÄÖÜçéèñ";
var encoded = str.b64encode();
console.log( encoded.b64decode() );
NOTE:
As stated in the comments, using unescape
is not recommended as it may be removed in the future:
Warning: Although unescape() is not strictly deprecated (as in "removed from the Web standards"), it is defined in Annex B of the ECMA-262 standard, whose introduction states: … All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification.
Note: Do not use unescape to decode URIs, use decodeURI or decodeURIComponent instead.
Delete old configuration files from c:\Users\username\AppData\Local\appname and c:\Users\username\AppData\Roaming\appname and then try to restart your application.
Try this
$('#add_here').text('new-dynamic-text');
Try to change Tomcat version, in my case tomcat "8.0.41" and "8.5.8" didn't work. But "8.5.37" worked fine.
I had the similar issue, unfortunately I used the GitExtensions HMI and forgot that I wrote a passphrase. With HMI.... forget it ! Do not enter passphrase when you generate your key !
Since, you are able to run Python in PowerShell. You can just do python <scriptName>.py
to run the script. So, for a script named test.py
containing
name = raw_input("Enter your name: ")
print "Hello, " + name
The PowerShell session would be
PS C:\Python27> python test.py
Enter your name: Monty Python
Hello, Monty Python
PS C:\Python27>
It's weekend now!
public async void Go()
{
Console.WriteLine("Start fosterage...");
var t1 = Sleep(5000, "Kevin");
var t2 = Sleep(3000, "Jerry");
var result = await Task.WhenAll(t1, t2);
Console.WriteLine($"My precious spare time last for only {result.Max()}ms");
Console.WriteLine("Press any key and take same beer...");
Console.ReadKey();
}
private static async Task<int> Sleep(int ms, string name)
{
Console.WriteLine($"{name} going to sleep for {ms}ms :)");
await Task.Delay(ms);
Console.WriteLine("${name} waked up after {ms}ms :(";
return ms;
}
Pure Python2 w/o dep:
def relpath(cwd, path):
"""Create a relative path for path from cwd, if possible"""
if sys.platform == "win32":
cwd = cwd.lower()
path = path.lower()
_cwd = os.path.abspath(cwd).split(os.path.sep)
_path = os.path.abspath(path).split(os.path.sep)
eq_until_pos = None
for i in xrange(min(len(_cwd), len(_path))):
if _cwd[i] == _path[i]:
eq_until_pos = i
else:
break
if eq_until_pos is None:
return path
newpath = [".." for i in xrange(len(_cwd[eq_until_pos+1:]))]
newpath.extend(_path[eq_until_pos+1:])
return os.path.join(*newpath) if newpath else "."
Is this a simple eclipse java project without maven etc? In that case you will need to put the log4j2.xml
file under src
folder in order to be able to find it on the classpath.
If you use maven put it under src/main/resources
or src/test/resources
Well, running example:
WARNING! NEVER DO THIS AT HOME/WORK! Only in classroom ;)
Use semaphores, shared variables, etc. to avoid rush conditions.
from threading import Thread
import time
a = 0 # global variable
def thread1(threadname):
global a
for k in range(100):
print("{} {}".format(threadname, a))
time.sleep(0.1)
if k == 5:
a += 100
def thread2(threadname):
global a
for k in range(10):
a += 1
time.sleep(0.2)
thread1 = Thread(target=thread1, args=("Thread-1",))
thread2 = Thread(target=thread2, args=("Thread-2",))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
and the output:
Thread-1 0
Thread-1 1
Thread-1 2
Thread-1 2
Thread-1 3
Thread-1 3
Thread-1 104
Thread-1 104
Thread-1 105
Thread-1 105
Thread-1 106
Thread-1 106
Thread-1 107
Thread-1 107
Thread-1 108
Thread-1 108
Thread-1 109
Thread-1 109
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
If the timing were right, the a += 100
operation would be skipped:
Processor executes at T a+100
and gets 104. But it stops, and jumps to next thread
Here, At T+1 executes a+1
with old value of a, a == 4
. So it computes 5.
Jump back (at T+2), thread 1, and write a=104
in memory.
Now back at thread 2, time is T+3 and write a=5
in memory.
Voila! The next print instruction will print 5 instead of 104.
VERY nasty bug to be reproduced and caught.
#include<stdio.h>
struct examp{
int number;
};
struct examp a,*b=&a;`enter code here`
main()
{
a.number=5;
/* a.number,b->number,(*b).number produces same output. b->number is mostly used in linked list*/
printf("%d \n %d \n %d",a.number,b->number,(*b).number);
}
output is 5 5 5
Here's a way to keep the command window open regardless of how execution stops without modifying any code:
In Visual Studio, open Project Property Pages -> Debugging.
For Command, enter $(ComSpec)
For Command Arguments, enter /k $(TargetPath)
. Append any arguments to your own application.
Now F5 or Ctrl-F5 executes Windows/System32/cmd.exe in a new window, and /k ensures that the command prompt stays open after execution completes.
The downside is that execution won't stop on breakpoints.
The solution by user1236048 is correct, but the key point isn't called out. In your POJO classes used for the table's observable list, you not only have to set getter and setter methods, but a new one called Property. In Oracle's tableview tutorial (http://docs.oracle.com/javafx/2/ui_controls/table-view.htm), they left that key part off!
Here's what the Person class should look like:
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private final SimpleStringProperty email;
private Person(String fName, String lName, String email) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
this.email = new SimpleStringProperty(email);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public SimpleStringProperty firstNameProperty(){
return firstName;
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String fName) {
lastName.set(fName);
}
public SimpleStringProperty lastNameProperty(){
return lastName;
}
public String getEmail() {
return email.get();
}
public void setEmail(String fName) {
email.set(fName);
}
public SimpleStringProperty emailProperty(){
return email;
}
}
The real problem is how Netbeans JARs its projects. The "Class-Path:" in the Manifest file is unnecessary when actually publishing your program for others to use. If you have an external Library added in Netbeans it acts as a package. I suggest you use a program like WINRAR to view the files within the jar and add your libraries as packages directly into the jar file.
How the inside of the jar file should look:
MyProject.jar
Manifest.MF
Main-Class: mainClassFolder.Mainclass
mainClassFolder
Mainclass.class
packageFolder
IamUselessWithoutMain.class
I have to write a whole answer separately since it's hard to add a comment so long to the second answer.
I'm sorry to say this, but the second answer above doesn't work right.
The following three scenarios will show my point:
Scenario 1: Before the following way was deprecated,
$(window).load(function () {
alert("Window Loaded.");
});
if we execute the following two queries:
<script>
$(window).load(function () {
alert("Window Loaded.");
});
$(document).ready(function() {
alert("Dom Loaded.");
});
</script>,
the alert (Dom Loaded.) from the second query will show first, and the one (Window Loaded.) from the first query will show later, which is the way it should be.
Scenario 2: But if we execute the following two queries like the second answer above suggests:
<script>
$(window).ready(function () {
alert("Window Loaded.");
});
$(document).ready(function() {
alert("Dom Loaded.");
});
</script>,
the alert (Window Loaded.) from the first query will show first, and the one (Dom Loaded.) from the second query will show later, which is NOT right.
Scenario 3: On the other hand, if we execute the following two queries, we'll get the correct result:
<script>
$(window).on("load", function () {
alert("Window Loaded.");
});
$(document).ready(function() {
alert("Dom Loaded.");
});
</script>,
that is to say, the alert (Dom Loaded.) from the second query will show first, and the one (Window Loaded.) from the first query will show later, which is the RIGHT result.
In short, the FIRST answer is the CORRECT one:
$(window).on('load', function () {
alert("Window Loaded.");
});
A transaction isn't needed here, this should suffice:
function add_post($post_data) {
$this->db->insert('posts',$post_data);
return $this->db->insert_id();
}
You can also use the filter function from the dplyr package which returns rows with matching conditions.
> library(dplyr)
> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2
The term upstream also has some unambiguous meaning as comes to the suite of GIT tools, especially relative to tracking
For example :
$git rev-list --count --left-right "@{upstream}"...HEAD >4 12
will print (the last cached value of) the number of commits behind (left) and ahead (right) of your current working branch, relative to the (if any) currently tracking remote branch for this local branch. It will print an error message otherwise:
>error: No upstream branch found for ''
origin
(your forked repo on github) and upstream
(the repo on github you forked from). Those are just interchangeable names, only the 'git@...' url identifies them.Your
.git/config
reads :[remote "origin"] fetch = +refs/heads/*:refs/remotes/origin/* url = [email protected]:myusername/reponame.git [remote "upstream"] fetch = +refs/heads/*:refs/remotes/upstream/* url = [email protected]:authorname/reponame.git
it is 'the branch' (if any) on 'said remote', which is tracking the 'current branch' on your 'local repository'.
It's the branch you fetch/pull from whenever you issue a plain
git fetch
/git pull
, without arguments.
Let's say want to set the remote branch origin/master to be the tracking branch for the local master branch you've checked out. Just issue :
$ git branch --set-upstream master origin/master > Branch master set up to track remote branch master from origin.
This adds 2 parameters in
.git/config
:[branch "master"] remote = origin merge = refs/heads/master
now try (provided 'upstream' remote has a 'dev' branch)
$ git branch --set-upstream master upstream/dev > Branch master set up to track remote branch dev from upstream.
.git/config
now reads:[branch "master"] remote = upstream merge = refs/heads/dev
-u --set-upstream
For every branch that is up to date or successfully pushed, add upstream (tracking) reference, used by argument-less git-pull(1) and other commands. For more information, see
branch.<name>.merge
in git-config(1).branch.<name>.merge
Defines, together with
branch.<name>.remote
, the upstream branch for the given branch. It tells git fetch/git pull/git rebase which branch to merge and can also affect git push (see push.default). \ (...)branch.<name>.remote
When in branch < name >, it tells git fetch and git push which remote to fetch from/push to. It defaults to origin if no remote is configured. origin is also used if you are not on any branch.
take a look at git-config(1)
Manual Page
git config --global push.default upstream git config --global push.default tracking (deprecated)
This is to prevent accidental pushes to branches which you’re not ready to push yet.
int x = 0xFF; //your number - 11111111
How do I for example read a 3 bit integer value starting at the second bit
int y = x & ( 0x7 << 2 ) // 0x7 is 111
// and you shift it 2 to the left
It means another user is accessing the database. Simply restart PostgreSQL. This command will do the trick
root@kalilinux:~#sudo service postgresql restart
Then try dropping the database:
postgres=# drop database test_database;
This will do the trick.
For a single boxplot:
import seaborn as sb
sb.boxplot(data=Array).set_title('Title')
For more boxplot in the same plot:
import seaborn as sb
sb.boxplot(data=ArrayofArray).set_title('Title')
e.g.
import seaborn as sb
myarray=[78.195229, 59.104538, 19.884109, 25.941648, 72.234825, 82.313911]
sb.boxplot(data=myarray).set_title('myTitle')
Why not make a simple utility function that does this?
static <A> ArrayList<A> ll(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
"ll
" stands for "literal list".
ArrayList<String> places = ll("Buenos Aires", "Córdoba", "La Plata");
The problem that I had with the change
handler was that it triggered on every keypress that I scrolled up and down the <select>
.
I wanted to get the event for whenever an option was clicked or when enter
was pressed on the desired option. This is how I ended up doing it:
let blockChange = false;
$element.keydown(function (e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// prevents select opening when enter is pressed
if (keycode === 13) {
e.preventDefault();
}
// lets the change event know that these keypresses are to be ignored
if([38, 40].indexOf(keycode) > -1){
blockChange = true;
}
});
$element.keyup(function(e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// handle enter press
if(keycode === 13) {
doSomething();
}
});
$element.change(function(e) {
// this effective handles the click only as preventDefault was used on enter
if(!blockChange) {
doSomething();
}
blockChange = false;
});
@ECHO OFF
TITLE Addition
ECHO Type the first number you wish to add:
SET /P Num1Add=
ECHO Type the second number you want to add to the first number:
SET /P Num2Add=
ECHO.
SET /A Ans=%Num1Add%+%Num2Add%
ECHO The result is: %Ans%
ECHO.
ECHO Press any key to exit.
PAUSE>NUL
I know its too late, but I'm posting this for the upcoming developers.
For select all checkbox we need to check three conditions, 1. on click select all checkbox every checkbox should get selected 2. if all selected then on click select all checkbox, every checkbox should get deselected 3. if we deselect or select any of the checkbox the select all checkbox also should change.
with these three things we'll get a good result.for this you can approach this link https://qawall.in/2020/05/30/select-all-or-deselect-all-checkbox-using-jquery/ I got my solution from here, they have provided solution with examples.
<table>
<tr>
<th><input type="checkbox" id="select_all"/> Select all</th>
</tr>
<tr>
<td><input type="checkbox" class="check" value="1"/> Check 1</td>
<td><input type="checkbox" class="check" value="2"/> Check 2</td>
<td><input type="checkbox" class="check" value="3"/> Check 3</td>
<td><input type="checkbox" class="check" value="4"/> Check 4</td>
<td><input type="checkbox" class="check" value="5"/> Check 5</td>
</tr>
<script type="text/javascript">
$(document).ready(function(){
$('#select_all').on('click',function(){
if(this.checked){
$('.check').each(function(){
this.checked = true;
});
}else{
$('.check').each(function(){
this.checked = false;
});
}
});
$('.check').on('click',function(){
if($('.check:checked').length == $('.check').length){
$('#select_all').prop('checked',true);
}else{
$('#select_all').prop('checked',false);
}
});
});
hope this will help anyone ...:)
I know this is a rather old post but I have another slightly simpler solution. You could create another class within and make it abstract. Next make an Abstract method name it whatever you like. In the original class make a method that takes the new class as a parameter, in this method call the abstract method. It will look something like this.
public class Demo {
public Demo(/.../){
}
public void view(Action a){
a.preform();
}
/**
* The Action Class is for making the Demo
* View Custom Code
*/
public abstract class Action {
public Action(/.../){
}
abstract void preform();
}
}
Now you can do something like this to call a method from within the class.
/...
Demo d = new Demo;
Action a = new Action() {
@Override
void preform() {
//Custom Method Code Goes Here
}
};
/.../
d.view(a)
Like I said I know its old but this way I think is a little easier. Hope it helps.
Here is a more feature-rich solution I just made after studying this question:
const parseJwt = (token) => {
try {
if (!token) {
throw new Error('parseJwt# Token is required.');
}
const base64Payload = token.split('.')[1];
let payload = new Uint8Array();
try {
payload = Buffer.from(base64Payload, 'base64');
} catch (err) {
throw new Error(`parseJwt# Malformed token: ${err}`);
}
return {
decodedToken: JSON.parse(payload),
};
} catch (err) {
console.log(`Bonus logging: ${err}`);
return {
error: 'Unable to decode token.',
};
}
};
Here's some usage samples:
const unhappy_path1 = parseJwt('sk4u7vgbis4ewku7gvtybrose4ui7gvtmalformedtoken');
console.log('unhappy_path1', unhappy_path1);
const unhappy_path2 = parseJwt('sk4u7vgbis4ewku7gvtybrose4ui7gvt.malformedtoken');
console.log('unhappy_path2', unhappy_path2);
const unhappy_path3 = parseJwt();
console.log('unhappy_path3', unhappy_path3);
const { error, decodedToken } = parseJwt('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c');
if (!decodedToken.exp) {
console.log('almost_happy_path: token has illegal claims (missing expires_at timestamp)', decodedToken);
// note: exp, iat, iss, jti, nbf, prv, sub
}
I wasn't able to make that runnable in StackOverflow code snippet tool, but here's approximately what you would see if you ran that code:
I made the parseJwt
function always return an object (to some degree for static-typing reasons).
This allows you to utilize syntax such as:
const { decodedToken, error } = parseJwt(token);
Then you can test at run-time for specific types of errors and avoid any naming collision.
If anyone can think of any low effort, high value changes to this code, feel free to edit my answer for the benefit of next(person)
.
I use:
Imports System.IO
Dim strPath as String=Directory.GetCurrentDirectory
You could perhaps use the if-let-where clause:
Swift 3:
if let string = string, !string.isEmpty {
/* string is not blank */
}
Swift 2:
if let string = string where !string.isEmpty {
/* string is not blank */
}
Oh must add my own pick here, you will use this when you encode/decode some string obj you transfer between two programs.
Lets say you use base64encode some array in python, and then you want to decode that into c++. Once you have the string you decode from base64decode in c++. In order to get it back to array of float, all you need to do here is
float arr[1024];
memcpy(arr, ur_string.c_str(), sizeof(float) * 1024);
This is pretty common use I suppose.
try
<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>
you can use OnClick="document.getElementById('formID_NOT_NAME').SUBMIT()"
You can concatenate the CR and LF:
chr(13)||chr(10)
(on windows)
or just:
chr(10)
(otherwise)
dbms_output.put_line('Hi,'||chr(13)||chr(10) ||'good' || chr(13)||chr(10)|| 'morning' ||chr(13)||chr(10) || 'friends');
Kotlin Solution:
For custom class save in onSaveInstanceState
you can be converted your class to JSON
string and restore it with Gson
convertion and for single String, Double, Int, Long
value save and restore as following. The following example is for Fragment
and Activity
:
For Activity:
For put data in saveInstanceState
:
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
//for custom class-----
val gson = Gson()
val json = gson.toJson(your_custom_class)
outState.putString("CUSTOM_CLASS", json)
//for single value------
outState.putString("MyString", stringValue)
outState.putBoolean("MyBoolean", true)
outState.putDouble("myDouble", doubleValue)
outState.putInt("MyInt", intValue)
}
Restore data:
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
//for custom class restore
val json = savedInstanceState?.getString("CUSTOM_CLASS")
if (!json!!.isEmpty()) {
val gson = Gson()
testBundle = gson.fromJson(json, Session::class.java)
}
//for single value restore
val myBoolean: Boolean = savedInstanceState?.getBoolean("MyBoolean")
val myDouble: Double = savedInstanceState?.getDouble("myDouble")
val myInt: Int = savedInstanceState?.getInt("MyInt")
val myString: String = savedInstanceState?.getString("MyString")
}
You can restore it on Activity onCreate
also.
For fragment:
For put class in saveInstanceState
:
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
val gson = Gson()
val json = gson.toJson(customClass)
outState.putString("CUSTOM_CLASS", json)
}
Restore data:
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
//for custom class restore
if (savedInstanceState != null) {
val json = savedInstanceState.getString("CUSTOM_CLASS")
if (!json!!.isEmpty()) {
val gson = Gson()
val customClass: CustomClass = gson.fromJson(json, CustomClass::class.java)
}
}
// for single value restore
val myBoolean: Boolean = savedInstanceState.getBoolean("MyBoolean")
val myDouble: Double = savedInstanceState.getDouble("myDouble")
val myInt: Int = savedInstanceState.getInt("MyInt")
val myString: String = savedInstanceState.getString("MyString")
}
Sometimes, it is also because of a wrong table name or column name in the prepare statement.
See this.
The MultiCell
is used for print text with multiple lines. It has the same atributes of Cell
except for ln
and link
.
$pdf->MultiCell( 200, 40, $reportSubtitle, 1);
What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).
MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])
You can read the full documentation here.
SELECT *
FROM tbl
WHERE myDate BETWEEN #date one# AND #date two#;
Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here
and edited my code: (xmlDoc.DocumentElement.AppendChild(body))
//a dictionary:
Dictionary<string, string> Level2Data
{
{"level2", "text"},
{"level2", "other text"},
{"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR
foreach (KeyValuePair<string, string> entry in Level2Data)
{
//write to xml: - it works version 1.
XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
keyNode.InnerText = entry.Value;
body.AppendChild(keyNode); //close TAB
//Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
//XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
//XmlText value = xmlDoc.CreateTextNode(entry.Value);
//key.AppendChild(value);
//body.AppendChild(key);
}
Both versions (1 and 2 inside foreach loop) give the output:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>ther text</level2>
<same_level2>more text</same_level2>
</level1>
</body>
(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.
I got here googling for C# compiler error CS0176, through (duplicate) question Static member instance reference issue.
In my case, the error happened because I had a static method and an extension method with the same name. For that, see Static method and extension method with same name.
[May be this should have been a comment. Sorry that I don't have enough reputation yet.]
object["property"] = value;
or
object.property = value;
Object and Array in JavaScript are different in terms of usage. Its best if you understand them:
You can use getTime()
method to convert the Date
to the number of milliseconds since January 1, 1970. Then you can easy do any arithmetic operations with the dates. Of course you can convert the number back to the Date
with setTime()
. See here an example.
Shorter version for those who like short code:
// usage: deleteOldFiles("./xml", "xml,xsl", 24 * 3600)
function deleteOldFiles($dir, $patterns = "*", int $timeout = 3600) {
// $dir is directory, $patterns is file types e.g. "txt,xls", $timeout is max age
foreach (glob($dir."/*"."{{$patterns}}",GLOB_BRACE) as $f) {
if (is_writable($f) && filemtime($f) < (time() - $timeout))
unlink($f);
}
}
You need to instantiate a class instance here.
Use
p = Pump()
p.getPumps()
Small example -
>>> class TestClass:
def __init__(self):
print("in init")
def testFunc(self):
print("in Test Func")
>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func
Don't look too far.
If you develop with ASP.NET MVC, you simply have the user as a property of the Controller
class. So in case you get lost in some models looking for the current user, try to step back and to get the relevant information in the controller.
In the controller, just use:
using Microsoft.AspNet.Identity;
...
var userId = User.Identity.GetUserId();
...
with userId
as a string.
/usr/bin/swiftc --version
Is there a single declaration that fixes this for Webkit, Gecko, and Blink? No. However, there is a cross-browser solution by specifying multiple width property values that correspond to each layout engine's convention.
.mydiv {
...
width: intrinsic; /* Safari/WebKit uses a non-standard name */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
...
}
Adapted from: MDN
TL;DR - C# string extension method
I think the best solution to preserve the meaning of the string is to convert the characters instead of stripping them, which is well illustrated in the example crème brûlée
to crme brle
vs. creme brulee
.
I checked out Alexander's comment above and saw the Lucene.Net code is Apache 2.0 licensed, so I've modified the class into a simple string extension method. You can use it like this:
var originalString = "crème brûlée";
var maxLength = originalString.Length; // limit output length as necessary
var foldedString = originalString.FoldToASCII(maxLength);
// "creme brulee"
The function is too long to post in a StackOverflow answer (~139k characters of 30k allowed lol) so I made a gist and attributed the authors:
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// This class converts alphabetic, numeric, and symbolic Unicode characters
/// which are not in the first 127 ASCII characters (the "Basic Latin" Unicode
/// block) into their ASCII equivalents, if one exists.
/// <para/>
/// Characters from the following Unicode blocks are converted; however, only
/// those characters with reasonable ASCII alternatives are converted:
///
/// <ul>
/// <item><description>C1 Controls and Latin-1 Supplement: <a href="http://www.unicode.org/charts/PDF/U0080.pdf">http://www.unicode.org/charts/PDF/U0080.pdf</a></description></item>
/// <item><description>Latin Extended-A: <a href="http://www.unicode.org/charts/PDF/U0100.pdf">http://www.unicode.org/charts/PDF/U0100.pdf</a></description></item>
/// <item><description>Latin Extended-B: <a href="http://www.unicode.org/charts/PDF/U0180.pdf">http://www.unicode.org/charts/PDF/U0180.pdf</a></description></item>
/// <item><description>Latin Extended Additional: <a href="http://www.unicode.org/charts/PDF/U1E00.pdf">http://www.unicode.org/charts/PDF/U1E00.pdf</a></description></item>
/// <item><description>Latin Extended-C: <a href="http://www.unicode.org/charts/PDF/U2C60.pdf">http://www.unicode.org/charts/PDF/U2C60.pdf</a></description></item>
/// <item><description>Latin Extended-D: <a href="http://www.unicode.org/charts/PDF/UA720.pdf">http://www.unicode.org/charts/PDF/UA720.pdf</a></description></item>
/// <item><description>IPA Extensions: <a href="http://www.unicode.org/charts/PDF/U0250.pdf">http://www.unicode.org/charts/PDF/U0250.pdf</a></description></item>
/// <item><description>Phonetic Extensions: <a href="http://www.unicode.org/charts/PDF/U1D00.pdf">http://www.unicode.org/charts/PDF/U1D00.pdf</a></description></item>
/// <item><description>Phonetic Extensions Supplement: <a href="http://www.unicode.org/charts/PDF/U1D80.pdf">http://www.unicode.org/charts/PDF/U1D80.pdf</a></description></item>
/// <item><description>General Punctuation: <a href="http://www.unicode.org/charts/PDF/U2000.pdf">http://www.unicode.org/charts/PDF/U2000.pdf</a></description></item>
/// <item><description>Superscripts and Subscripts: <a href="http://www.unicode.org/charts/PDF/U2070.pdf">http://www.unicode.org/charts/PDF/U2070.pdf</a></description></item>
/// <item><description>Enclosed Alphanumerics: <a href="http://www.unicode.org/charts/PDF/U2460.pdf">http://www.unicode.org/charts/PDF/U2460.pdf</a></description></item>
/// <item><description>Dingbats: <a href="http://www.unicode.org/charts/PDF/U2700.pdf">http://www.unicode.org/charts/PDF/U2700.pdf</a></description></item>
/// <item><description>Supplemental Punctuation: <a href="http://www.unicode.org/charts/PDF/U2E00.pdf">http://www.unicode.org/charts/PDF/U2E00.pdf</a></description></item>
/// <item><description>Alphabetic Presentation Forms: <a href="http://www.unicode.org/charts/PDF/UFB00.pdf">http://www.unicode.org/charts/PDF/UFB00.pdf</a></description></item>
/// <item><description>Halfwidth and Fullwidth Forms: <a href="http://www.unicode.org/charts/PDF/UFF00.pdf">http://www.unicode.org/charts/PDF/UFF00.pdf</a></description></item>
/// </ul>
/// <para/>
/// See: <a href="http://en.wikipedia.org/wiki/Latin_characters_in_Unicode">http://en.wikipedia.org/wiki/Latin_characters_in_Unicode</a>
/// <para/>
/// For example, '&agrave;' will be replaced by 'a'.
/// </summary>
public static partial class StringExtensions
{
/// <summary>
/// Converts characters above ASCII to their ASCII equivalents. For example,
/// accents are removed from accented characters.
/// </summary>
/// <param name="input"> The string of characters to fold </param>
/// <param name="length"> The length of the folded return string </param>
/// <returns> length of output </returns>
public static string FoldToASCII(this string input, int? length = null)
{
// See https://gist.github.com/andyraddatz/e6a396fb91856174d4e3f1bf2e10951c
}
}
Hope that helps someone else, this is the most robust solution I've found!
Try this,
$('td').click(function(){
var row_index = $(this).parent().index();
var col_index = $(this).index();
});
If you need the index of table contain td then you can change it to
var row_index = $(this).parent('table').index();
this type of error usually occur when you try to access data through the index in which data data has not been assign. for example
//assign of data in to array
for(int i=0; i<10; i++){
arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}
the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.
You can use the keyword IDENTITY
as the data type to the column along with PRIMARY KEY
constraint when creating the table.
ex:
StudentNumber IDENTITY(1,1) PRIMARY KEY
In here the first '1' means the starting value and the second '1' is the incrementing value.
DisplayFor
is also useful for templating. You could write a template for your Model, and do something like this:
@Html.DisplayFor(m => m)
Similar to @Html.EditorFor(m => m)
. It's useful for the DRY principal so that you don't have to write the same display logic over and over for the same Model.
Take a look at this blog on MVC2 templates. It's still very applicable to MVC3:
http://www.dalsoft.co.uk/blog/index.php/2010/04/26/mvc-2-templates/
It's also useful if your Model has a Data annotation. For instance, if the property on the model is decorated with the EmailAddress
data annotation, DisplayFor
will render it as a mailto:
link.
In his paper, Memory Optimization, Christer Ericson says that while restrict
is not part of the C++ standard yet, that it is supported by many compilers and he recommends it's usage when available:
restrict keyword
! New to 1999 ANSI/ISO C standard
! Not in C++ standard yet, but supported by many C++ compilers
! A hint only, so may do nothing and still be conforming
A restrict-qualified pointer (or reference)...
! ...is basically a promise to the compiler that for the scope of the pointer, the target of the pointer will only be accessed through that pointer (and pointers copied from it).
In C++ compilers that support it it should probably behave the same as in C.
See this SO post for details: Realistic usage of the C99 ‘restrict’ keyword?
Take half an hour to skim through Ericson's paper, it's interesting and worth the time.
Edit
I also found that IBM's AIX C/C++ compiler supports the __restrict__
keyword.
g++ also seems to support this as the following program compiles cleanly on g++:
#include <stdio.h>
int foo(int * __restrict__ a, int * __restrict__ b) {
return *a + *b;
}
int main(void) {
int a = 1, b = 1, c;
c = foo(&a, &b);
printf("c == %d\n", c);
return 0;
}
I also found a nice article on the use of restrict
:
Demystifying The Restrict Keyword
Edit2
I ran across an article which specifically discusses the use of restrict in C++ programs:
Load-hit-stores and the __restrict keyword
Also, Microsoft Visual C++ also supports the __restrict
keyword.
First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
Because &
has a lesser priority than ==
.
Your code is equivalent to a[0] & (1 == 0)
, and unless a[0]
is a boolean this won't compile...
You need to:
(a[0] & 1) == 0
etc etc.
(yes, Java does hava a boolean &
operator -- a non shortcut logical and)
try this
df.rename(columns={ df.columns[1]: "your value" }, inplace = True)
<%= Html.Partial("PartialName", Model) %>
You should add overflow: hidden
to your styles:
Js:
<Button style={styles.submit}>Submit</Button>
Styles:
submit {
backgroundColor: '#68a0cf';
overflow: 'hidden';
}
chars are just integers, so you can actually do a straight comparison of your character against literals:
if( c >= '0' && c <= '9' ){
This applies to all characters. See your ascii table.
ctype.h also provides functions to do this for you.
Use CURRENT_TIMESTAMP() or now()
Like
INSERT INTO servers (server_name, online_status, exchange, disk_space,
network_shares,date_time) VALUES('m1','ONLINE','ONLINE','100GB','ONLINE',now() )
or
INSERT INTO servers (server_name, online_status, exchange, disk_space,
network_shares,date_time) VALUES('m1', 'ONLINE', 'ONLINE', '100GB', 'ONLINE'
,CURRENT_TIMESTAMP() )
Replace date_time with the column name you want to use to insert the time.
$('controlCheckBox').click(function(){
var temp = $(this).prop('checked');
$('controlledCheckBoxes').prop('checked', temp);
});
I'd try this:
Split your Model into a separate file called model.ts
:
export class Model {
param1: string;
}
Import it into your component. This will give you the added benefit of being able to use it in other components:
Import { Model } from './model';
Initialize in the component:
export class testWidget {
public model: Model;
constructor(){
this.model = new Model();
this.model.param1 = "your string value here";
}
}
Access it appropriately in the html:
@Component({
selector: "testWidget",
template: "<div>This is a test and {{model.param1}} is my param.</div>"
})
I want to add to the answer a comment made by @PatMigliaccio because it's important to adapt to the latest tools and technologies:
If you are using
angular-cli
you can callng g class model
and it will generate it for you. model being replaced with whatever naming you desire.
You can try this:
HTML
<table>
<tr>
<td class="shrink">element1</td>
<td class="shrink">data</td>
<td class="shrink">junk here</td>
<td class="expand">last column</td>
</tr>
<tr>
<td class="shrink">elem</td>
<td class="shrink">more data</td>
<td class="shrink">other stuff</td>
<td class="expand">again, last column</td>
</tr>
<tr>
<td class="shrink">more</td>
<td class="shrink">of </td>
<td class="shrink">these</td>
<td class="expand">rows</td>
</tr>
</table>
CSS
table {
border: 1px solid green;
border-collapse: collapse;
width:100%;
}
table td {
border: 1px solid green;
}
table td.shrink {
white-space:nowrap
}
table td.expand {
width: 99%
}
If you are running an Intel processor make sure the HAXM (Intel® Hardware Accelerated Execution Manager) installer is installed via SDK Manager by checking this option in SDK Manager. And then run the HAXM installer ext via the path below.
your_sdk_folder\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm.exe
Also check the RAM size allocated while doing HAX installation so it fits the RAM size of your emulator.
This video shows all the required steps which may help you to solve the problem.
This video will also help you if you face a problem after installing HAXM.
Don't lose time. Search for it in the registry:
reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
returns less than the SET command.
To change the JDK version of the Intellij-IDE himself:
Start the IDE -> Help -> Find Action
than type:
Switch Boot JDK
or (depend on your version)
Switch IDE boot JDK
To select multiple columns, extract and view them thereafter: df
is previously named data frame, than create new data frame df1
, and select the columns A to D which you want to extract and view.
df1 = pd.DataFrame(data_frame, columns=['Column A', 'Column B', 'Column C', 'Column D'])
df1
All required columns will show up!
Use -F [field separator]
to split the lines on "
s:
awk -F '"' '{print $2}' your_input_file
or for input from pipe
<some_command> | awk -F '"' '{print $2}'
output:
A B
C
D
Not using iframes puts you in a world of handling #document security issues with cross domain and links firing unexpected ways that was not intended for originally, do you really need bad Advertisements?
You can use jquery .load function to send the page to whatever html element you want to target, assuming your not getting this from another domain.
You can use javascript .innerHTML value to set and to rewrite the element with whatever you want, but if you add another file you might be writing against 2 documents in 1... like a in another
iframes are old, another way we can add "src" into the html alone without any use for javascript. But it's old, prehistoric, and just plain OLD! Frameset makes it worse because I can put #document in those to handle multiple html files. An Old way people created navigation menu's Long and before people had FLIP phones.
1.) Yes you will have to work in Javascript if you do NOT want to use an Iframe.
2.) There is a good hack in which you can set the domain to equal each other without having to set server stuff around. Means you will have to have edit capabilities of the documents.
3.) javascript window.document is limited to the iframe itself and can NOT go above the iframe if you want to grab something through the DOM itself. Because it treats it like a separate tab, it also defines it in another document object model.
I found solution here: https://code.visualstudio.com/docs/customization/colorizer
Go to VS_CODE_FOLDER/resources/app/extensions/
and there update package.json
Use the Apache BooleanUtils.
(If peak performance is the most important priority in your project then look at one of the other answers for a native solution that doesn't require including an external library.)
Don't reinvent the wheel. Leverage what's already been built and use isTrue()
:
BooleanUtils.isTrue( bool );
Checks if a Boolean
value is true, handling null
by returning false
.
If you're not limited to the libraries you're "allowed" to include, there are a bunch of great helper functions for all sorts of use-cases, including Booleans
and Strings
. I suggest you peruse the various Apache libraries and see what they already offer.
To "loop" and take advantage of Spark's parallel computation framework, you could define a custom function and use map.
def customFunction(row):
return (row.name, row.age, row.city)
sample2 = sample.rdd.map(customFunction)
or
sample2 = sample.rdd.map(lambda x: (x.name, x.age, x.city))
The custom function would then be applied to every row of the dataframe. Note that sample2 will be a RDD
, not a dataframe.
Map may be needed if you are going to perform more complex computations. If you just need to add a simple derived column, you can use the withColumn
, with returns a dataframe.
sample3 = sample.withColumn('age2', sample.age + 2)
SELECT * INTO #TempTable
FROM SampleTable
WHERE...
SELECT * FROM #TempTable
DROP TABLE #TempTable
I know this is an old question but...
import java.text.*;
public class FormatCurrency
{
public static void main(String[] args)
{
double price = 123.4567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(price));
}
}
$(document).keydown(function (event) {
//proper indentiation of keycode and which to be equal to 13.
if ( (event.keyCode || event.which) === 13) {
// Cancel the default action, if needed
event.preventDefault();
//call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
$("#btnsearch").trigger('click');
}
});
There should be three pages here:
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
In Android M the top solution won't work. I've written a helper class to fix that which you should call from your Application class and all Activities (I would suggest creating a BaseActivity and then make all the Activities inherit from it.
Note: This will also support properly RTL layout direction.
Helper class:
public class LocaleUtils {
private static Locale sLocale;
public static void setLocale(Locale locale) {
sLocale = locale;
if(sLocale != null) {
Locale.setDefault(sLocale);
}
}
public static void updateConfig(ContextThemeWrapper wrapper) {
if(sLocale != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Configuration configuration = new Configuration();
configuration.setLocale(sLocale);
wrapper.applyOverrideConfiguration(configuration);
}
}
public static void updateConfig(Application app, Configuration configuration) {
if (sLocale != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
//Wrapping the configuration to avoid Activity endless loop
Configuration config = new Configuration(configuration);
// We must use the now-deprecated config.locale and res.updateConfiguration here,
// because the replacements aren't available till API level 24 and 17 respectively.
config.locale = sLocale;
Resources res = app.getBaseContext().getResources();
res.updateConfiguration(config, res.getDisplayMetrics());
}
}
}
Application:
public class App extends Application {
public void onCreate(){
super.onCreate();
LocaleUtils.setLocale(new Locale("iw"));
LocaleUtils.updateConfig(this, getBaseContext().getResources().getConfiguration());
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
LocaleUtils.updateConfig(this, newConfig);
}
}
BaseActivity:
public class BaseActivity extends Activity {
public BaseActivity() {
LocaleUtils.updateConfig(this);
}
}
I use this way:-
$occDate='2014-01-28';
$forOdNextMonth= date('m', strtotime("+1 month", strtotime($occDate)));
//Output:- $forOdNextMonth=02
/*****************more example****************/
$occDate='2014-12-28';
$forOdNextMonth= date('m', strtotime("+1 month", strtotime($occDate)));
//Output:- $forOdNextMonth=01
//***********************wrong way**********************************//
$forOdNextMonth= date('m', strtotime("+1 month", $occDate));
//Output:- $forOdNextMonth=02; //instead of $forOdNextMonth=01;
//******************************************************************//
zvolkov's answer is the perfect one to find out if there is such a customer. If you need to use the customer afterwards, you can do:
Customer customer = list.FirstOrDefault(cus => cus.FirstName == "John");
if (customer != null)
{
// Use customer
}
I know this isn't what you were asking, but I thought I'd pre-empt a follow-on question :) (Of course, this only finds the first such customer... to find all of them, just use a normal where
clause.)
The simplest answer, assuming you don't mind the vagaries and variations in format between different platforms, is the standard %p
notation.
The C99 standard (ISO/IEC 9899:1999) says in §7.19.6.1 ¶8:
p
The argument shall be a pointer tovoid
. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.
(In C11 — ISO/IEC 9899:2011 — the information is in §7.21.6.1 ¶8.)
On some platforms, that will include a leading 0x
and on others it won't, and the letters could be in lower-case or upper-case, and the C standard doesn't even define that it shall be hexadecimal output though I know of no implementation where it is not.
It is somewhat open to debate whether you should explicitly convert the pointers with a (void *)
cast. It is being explicit, which is usually good (so it is what I do), and the standard says 'the argument shall be a pointer to void
'. On most machines, you would get away with omitting an explicit cast. However, it would matter on a machine where the bit representation of a char *
address for a given memory location is different from the 'anything else pointer' address for the same memory location. This would be a word-addressed, instead of byte-addressed, machine. Such machines are not common (probably not available) these days, but the first machine I worked on after university was one such (ICL Perq).
If you aren't happy with the implementation-defined behaviour of %p
, then use C99 <inttypes.h>
and uintptr_t
instead:
printf("0x%" PRIXPTR "\n", (uintptr_t)your_pointer);
This allows you to fine-tune the representation to suit yourself. I chose to have the hex digits in upper-case so that the number is uniformly the same height and the characteristic dip at the start of 0xA1B2CDEF
appears thus, not like 0xa1b2cdef
which dips up and down along the number too. Your choice though, within very broad limits. The (uintptr_t)
cast is unambiguously recommended by GCC when it can read the format string at compile time. I think it is correct to request the cast, though I'm sure there are some who would ignore the warning and get away with it most of the time.
Kerrek asks in the comments:
I'm a bit confused about standard promotions and variadic arguments. Do all pointers get standard-promoted to void*? Otherwise, if
int*
were, say, two bytes, andvoid*
were 4 bytes, then it'd clearly be an error to read four bytes from the argument, non?
I was under the illusion that the C standard says that all object pointers must be the same size, so void *
and int *
cannot be different sizes. However, what I think is the relevant section of the C99 standard is not so emphatic (though I don't know of an implementation where what I suggested is true is actually false):
§6.2.5 Types
¶26 A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.39) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.
39) The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.
(C11 says exactly the same in the section §6.2.5, ¶28, and footnote 48.)
So, all pointers to structures must be the same size as each other, and must share the same alignment requirements, even though the structures the pointers point at may have different alignment requirements. Similarly for unions. Character pointers and void pointers must have the same size and alignment requirements. Pointers to variations on int
(meaning unsigned int
and signed int
) must have the same size and alignment requirements as each other; similarly for other types. But the C standard doesn't formally say that sizeof(int *) == sizeof(void *)
. Oh well, SO is good for making you inspect your assumptions.
The C standard definitively does not require function pointers to be the same size as object pointers. That was necessary not to break the different memory models on DOS-like systems. There you could have 16-bit data pointers but 32-bit function pointers, or vice versa. This is why the C standard does not mandate that function pointers can be converted to object pointers and vice versa.
Fortunately (for programmers targetting POSIX), POSIX steps into the breach and does mandate that function pointers and data pointers are the same size:
§2.12.3 Pointer Types
All function pointer types shall have the same representation as the type pointer to void. Conversion of a function pointer to
void *
shall not alter the representation. Avoid *
value resulting from such a conversion can be converted back to the original function pointer type, using an explicit cast, without loss of information.Note: The ISO C standard does not require this, but it is required for POSIX conformance.
So, it does seem that explicit casts to void *
are strongly advisable for maximum reliability in the code when passing a pointer to a variadic function such as printf()
. On POSIX systems, it is safe to cast a function pointer to a void pointer for printing. On other systems, it is not necessarily safe to do that, nor is it necessarily safe to pass pointers other than void *
without a cast.
Just call mkdir C:\VTS
no matter what. It will simply report that the subdirectory already exists.
Edit: As others have noted, this does set the %ERRORLEVEL% if the folder already exists. If your batch (or any processes calling it) doesn't care about the error level, this method works nicely. Since the question made no mention of avoiding the error level, this answer is perfectly valid. It fulfills the needs of creating the folder if it doesn't exist, and it doesn't overwrite the contents of an existing folder. Otherwise follow Martin Schapendonk's answer.
type data1.csv > combined.csv
type data2.csv >> combined.csv
type data3.csv >> combined.csv
type data4.csv >> combined.csv
etc.
Assume that your using files without headers and all files have the same columns.
You have to indent the docstring after the function definition there (line 3, 4):
def print_lol(the_list):
"""this doesn't works"""
print 'Ain't happening'
Indented:
def print_lol(the_list):
"""this works!"""
print 'Aaaand it's happening'
Or you can use #
to comment instead:
def print_lol(the_list):
#this works, too!
print 'Hohoho'
Also, you can see PEP 257 about docstrings.
Hope this helps!