Pseudo code from Wikipedia translated into the most compact Java
(year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))
I found this problem in the book "Illustrated Guide to Python 3". It was in a very early chapter that only discussed the math operations, no loops, no comparisons, no conditionals. How can you tell if a given year is a leap year?
Below is what I came up with:
y = y % 400
a = y % 4
b = y % 100
c = y // 100
ly = (0**a) * ((1-(0**b)) + 0**c) # ly is not zero for leap years, else 0
I like JoshAdel's answer because of the focus on performance. A minor performance improvement is to avoid the overhead of initializing with zeros, only to be overwritten. This has a measurable difference when N is large, empty is used instead of zeros, and the column of zeros is written as a separate step:
In [1]: import numpy as np
In [2]: N = 10000
In [3]: a = np.ones((N,N))
In [4]: %timeit b = np.zeros((a.shape[0],a.shape[1]+1)); b[:,:-1] = a
1 loops, best of 3: 492 ms per loop
In [5]: %timeit b = np.empty((a.shape[0],a.shape[1]+1)); b[:,:-1] = a; b[:,-1] = np.zeros((a.shape[0],))
1 loops, best of 3: 407 ms per loop
If you are using Google Play App Signing, you don't need to add your SHA-1 keys manually, just login into Firebase go into "project settings"->"integration" and press a button to link Google Play with firebase, SHA-1 will be added automatically.
HTML
<form name="my_form" id="my_form" accept-charset="multipart/form-data" onsubmit="return false">
<input id="name" name="name" placeholder="Enter Name" type="text" value="">
<textarea id="detail" name="detail" placeholder="Enter Detail"></textarea>
<select name="gender" id="gender">
<option value="male" selected="selected">Male</option>
<option value="female">Female</option>
</select>
<input type="file" id="my_images" name="my_images" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
</form>
JavaScript
var data = new FormData();
//Form data
var form_data = $('#my_form').serializeArray();
$.each(form_data, function (key, input) {
data.append(input.name, input.value);
});
//File data
var file_data = $('input[name="my_images"]')[0].files;
for (var i = 0; i < file_data.length; i++) {
data.append("my_images[]", file_data[i]);
}
//Custom data
data.append('key', 'value');
$.ajax({
url: "URL",
method: "post",
processData: false,
contentType: false,
data: data,
success: function (data) {
//success
},
error: function (e) {
//error
}
});
PHP
<?php
echo '<pre>';
print_r($_POST);
print_r($_FILES);
echo '</pre>';
die();
?>
Note that I did find one way to do it, but this looks more like material for The Daily WTF:
catch (Exception ex)
{
switch (ex.GetType().Name)
{
case "System.FormatException":
case "System.OverflowException":
WebId = Guid.Empty;
break;
default:
throw;
}
}
Calling the isHTML()
method after the instance Body
property (I mean $mail->Body
) has been set solved the problem for me:
$mail->Subject = $Subject;
$mail->Body = $Body;
$mail->IsHTML(true); // <=== call IsHTML() after $mail->Body has been set.
Actually, I do like mark instruction but little differently.
I've added C:\Program Files (x86)\GnuWin32\bin\
to the Path variable,
and try to run it with type awk using cmd.
Hope it works.
I compared some of the methods suggested here in Firefox for speed.
The string I used contained the following characters: œ´®†¥¨ˆøp¬°??©ƒ?ßåO˜çv?˜µ=
All results are averages of 3 runs each. Times are in milliseconds. Note that all URIEncoding methods behaved similarly and had extreme results, so I only included one.
While there are some fluctuations based on the size of the string, the charCode methods (lovasoa and fuweichin) both perform similarly and the fastest overall, with fuweichin's charCode method the fastest. The Blob and TextEncoder methods performed similarly to each other. Generally the charCode methods were about 75% faster than the Blob and TextEncoder methods. The URIEncoding method was basically unacceptable.
Here are the results I got:
Size 6.4 * 10^6 bytes:
Lauri Oherd – URIEncoding: 6400000 et: 796
lovasoa – charCode: 6400000 et: 15
fuweichin – charCode2: 6400000 et: 16
simap – Blob: 6400000 et: 26
Riccardo Galli – TextEncoder: 6400000 et: 23
Size 19.2 * 10^6 bytes: Blob does kind of a weird thing here.
Lauri Oherd – URIEncoding: 19200000 et: 2322
lovasoa – charCode: 19200000 et: 42
fuweichin – charCode2: 19200000 et: 45
simap – Blob: 19200000 et: 169
Riccardo Galli – TextEncoder: 19200000 et: 70
Size 64 * 10^6 bytes:
Lauri Oherd – URIEncoding: 64000000 et: 12565
lovasoa – charCode: 64000000 et: 138
fuweichin – charCode2: 64000000 et: 133
simap – Blob: 64000000 et: 231
Riccardo Galli – TextEncoder: 64000000 et: 211
Size 192 * 10^6 bytes: URIEncoding methods freezes browser at this point.
lovasoa – charCode: 192000000 et: 754
fuweichin – charCode2: 192000000 et: 480
simap – Blob: 192000000 et: 701
Riccardo Galli – TextEncoder: 192000000 et: 654
Size 640 * 10^6 bytes:
lovasoa – charCode: 640000000 et: 2417
fuweichin – charCode2: 640000000 et: 1602
simap – Blob: 640000000 et: 2492
Riccardo Galli – TextEncoder: 640000000 et: 2338
Size 1280 * 10^6 bytes: Blob & TextEncoder methods are starting to hit the wall here.
lovasoa – charCode: 1280000000 et: 4780
fuweichin – charCode2: 1280000000 et: 3177
simap – Blob: 1280000000 et: 6588
Riccardo Galli – TextEncoder: 1280000000 et: 5074
Size 1920 * 10^6 bytes:
lovasoa – charCode: 1920000000 et: 7465
fuweichin – charCode2: 1920000000 et: 4968
JavaScript error: file:///Users/xxx/Desktop/test.html, line 74: NS_ERROR_OUT_OF_MEMORY:
Here is the code:
function byteLengthURIEncoding(str) {
return encodeURI(str).split(/%..|./).length - 1;
}
function byteLengthCharCode(str) {
// returns the byte length of an utf8 string
var s = str.length;
for (var i=str.length-1; i>=0; i--) {
var code = str.charCodeAt(i);
if (code > 0x7f && code <= 0x7ff) s++;
else if (code > 0x7ff && code <= 0xffff) s+=2;
if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
}
return s;
}
function byteLengthCharCode2(s){
//assuming the String is UCS-2(aka UTF-16) encoded
var n=0;
for(var i=0,l=s.length; i<l; i++){
var hi=s.charCodeAt(i);
if(hi<0x0080){ //[0x0000, 0x007F]
n+=1;
}else if(hi<0x0800){ //[0x0080, 0x07FF]
n+=2;
}else if(hi<0xD800){ //[0x0800, 0xD7FF]
n+=3;
}else if(hi<0xDC00){ //[0xD800, 0xDBFF]
var lo=s.charCodeAt(++i);
if(i<l&&lo>=0xDC00&&lo<=0xDFFF){ //followed by [0xDC00, 0xDFFF]
n+=4;
}else{
throw new Error("UCS-2 String malformed");
}
}else if(hi<0xE000){ //[0xDC00, 0xDFFF]
throw new Error("UCS-2 String malformed");
}else{ //[0xE000, 0xFFFF]
n+=3;
}
}
return n;
}
function byteLengthBlob(str) {
return new Blob([str]).size;
}
function byteLengthTE(str) {
return (new TextEncoder().encode(str)).length;
}
var sample = "œ´®†¥¨ˆøp¬°??©ƒ?ßåO˜çv?˜µ=i";
var string = "";
// Adjust multiplier to change length of string.
let mult = 1000000;
for (var i = 0; i < mult; i++) {
string += sample;
}
let t0;
try {
t0 = Date.now();
console.log("Lauri Oherd – URIEncoding: " + byteLengthURIEncoding(string) + " et: " + (Date.now() - t0));
} catch(e) {}
t0 = Date.now();
console.log("lovasoa – charCode: " + byteLengthCharCode(string) + " et: " + (Date.now() - t0));
t0 = Date.now();
console.log("fuweichin – charCode2: " + byteLengthCharCode2(string) + " et: " + (Date.now() - t0));
t0 = Date.now();
console.log("simap – Blob: " + byteLengthBlob(string) + " et: " + (Date.now() - t0));
t0 = Date.now();
console.log("Riccardo Galli – TextEncoder: " + byteLengthTE(string) + " et: " + (Date.now() - t0));
.abc, .xyz { margin-left: 20px; }
is what you are looking for.
I think your regular expression would look like:
/FOO\[(.+)\]/
Assuming that FOO going to be constant.
So, to put this in Java:
Pattern p = Pattern.compile("FOO\\[(.+)\\]");
Matcher m = p.matcher(inputLine);
I was using a Node http
request and listening for the data
event. This event only puts the data into a buffer temporarily, and so a complete JSON is not available. To fix, each data
event must be appended to a variable. Might help someone (http://nodejs.org/api/http.html).
Click on the camera icon above simulator to capture screenshot and save to your camera roll
Another option: File > Save Screen from simulator
It's possible to make the multiple transitions set with different values for duration, delay and timing function. To split different transitions use ,
button{
transition: background 1s ease-in-out 2s, width 2s linear;
-webkit-transition: background 1s ease-in-out 2s, width 2s linear; /* Safari */
}
Reference: https://kolosek.com/css-transition/
Another option I have working, in a linux server with Postfix:
First, configure CI email to use your server's email system: eg, in email.php
, for example
# alias to postfix in a typical Postfix server
$config['protocol'] = 'sendmail';
$config['mailpath'] = '/usr/sbin/sendmail';
Then configure your postfix to relay the mail to google (perhaps depending on the sender address). You'll probably need to put you user-password settings in /etc/postfix/sasl_passwd
(docs)
This is much simpler (and less fragmente) if you have a linux box, already configured to send some/all of its outgoing emails to Google.
You should be using @RequestParam
instead of @ModelAttribute
, e.g.
@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id,
@RequestParam String someAttr) {
}
You can even omit @RequestParam
altogether if you choose, and Spring will assume that's what it is:
@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id,
String someAttr) {
}
Either you can use RAW SQL:
INSERT INTO DEST_TABLE (Field1, Field2)
SELECT Source_Field1, Source_Field2
FROM SOURCE_TABLE
Or use the wizard:
Then execute:
TRUNCATE TABLE SOURCE_TABLE
To rename a column:
sp_rename 'table_name.old_column_name', 'new_column_name' , 'COLUMN';
To rename a table:
sp_rename 'old_table_name','new_table_name';
I built on a previous answer and have this, some extra padding just to be able to conveniently join all the output:
SELECT
CONCAT('SELECT ''',A.TABLE_NAME, '-' ,A.COLUMN_NAME,''' FROM ', A.TABLE_SCHEMA, '.', A.TABLE_NAME,
' WHERE ', A.COLUMN_NAME, ' LIKE \'%Value%\' UNION')
FROM INFORMATION_SCHEMA.COLUMNS A
WHERE
A.TABLE_SCHEMA != 'mysql'
AND A.TABLE_SCHEMA != 'innodb'
AND A.TABLE_SCHEMA != 'performance_schema'
AND A.TABLE_SCHEMA != 'information_schema'
UNION SELECT 'SELECT '''
-- for exact match use: A.COLUMN_NAME, ' LIKE \'Value\' instead
First you run this, then paste in and run the result (no editing) and it will display all the table names and columns where the value is used.
If you don't want execute assembly goal on package, you can use next command:
mvn package assembly:single
Here package is keyword.
With a little bit correcting @Jolly1234's Answer: here is the code:
raw_string=path.encode('unicode_escape').decode()
I have used this very often in neural networks. It is well known that when we start training a neural network we randomly initialise the weights. The model is trained on these weights on a particular dataset. After number of epochs you get trained set of weights.
Now suppose you want to again train from scratch or you want to pass the model to others to reproduce your results, the weights will be again initialised to a random numbers which mostly will be different from earlier ones. The obtained trained weights after same number of epochs ( keeping same data and other parameters ) as earlier one will differ. The problem is your model is no more reproducible that is every time you train your model from scratch it provides you different sets of weights. This is because the model is being initialized by different random numbers every time.
What if every time you start training from scratch the model is initialised to the same set of random initialise weights? In this case your model could become reproducible. This is achieved by numpy.random.seed(0). By mentioning seed() to a particular number, you are hanging on to same set of random numbers always.
You can get the current route using
const currentRoute = this.props.routes[this.props.routes.length - 1];
...which gives you access to the props from the lowest-level active <Route ...>
component.
Given...
<Route path="childpath" component={ChildComponent} />
currentRoute.path
returns 'childpath'
and currentRoute.component
returns function _class() { ... }
.
If you use jCanvas library you can use opacity property when drawing. If you need fade effect on top of that, simply redraw with different values.
mariadb uses by defaults UNIX_SOCKET plugin to authenticate user root. https://mariadb.com/kb/en/mariadb/unix_socket-authentication-plugin/
"Because he has identified himself to the operating system, he does not need to do it again for the database"
so you need to login as the root user on unix to login as root in mysql/mariadb:
sudo mysql
if you want to login with root from your normal unix user, you can disable the authentication plugin for root.
Beforehand you can set the root password with mysql_secure_installation (default password is blank), then to let every user authenticate as root login with:
shell$ sudo mysql -u root
[mysql] use mysql;
[mysql] update user set plugin='' where User='root';
[mysql] flush privileges;
[mysql] \q
Use padding
on the div
(top and bottom) and vertical-align:middle
on the label
and input
.
example at http://jsfiddle.net/VLFeV/1/
Just an observation. The input is a list of lists, but the output from the very nice solution: rotated = zip(*original[::-1]) returns a list of tuples.
This may or may not be an issue.
It is, however, easily corrected:
original = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
def rotated(array_2d):
list_of_tuples = zip(*array_2d[::-1])
return [list(elem) for elem in list_of_tuples]
# return map(list, list_of_tuples)
print(list(rotated(original)))
# [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
The list comp or the map will both convert the interior tuples back to lists.
Const: Absolute constant value during the application life time.
Readonly: It can be changed in running time.
We can Supply parameter in different way after some search I found some useful
<plugin>
<artifactId>${release.artifactId}</artifactId>
<version>${release.version}-${release.svm.version}</version>...
...
Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .
While Running build we need supply value for those parameter as follows.
RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74
Here I am supplying
release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74
It worked for me. Thanks
The solutions like cmd /c pause
cause a new command interpreter to start and run in the background. Although acceptable in some cases, this isn't really ideal.
The solutions using Read-Host
force the user to press Enter and are not really "any key".
This solution will give you a true "press any key to continue" interface and will not start a new interpreter, which will essentially mimic the original pause
command.
Write-Host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
To declare a variable as a Decimal
, first declare it as a Variant
and then convert to Decimal
with CDec
. The type would be Variant/Decimal
in the watch window:
Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.
In the example below, we see that the expression:
0.1 + 0.11 = 0.21
is either True
or False
, depending on whether the collectibles (0.1,0.11) are declared as Double
or as Decimal
:
Public Sub TestMe()
Dim preciseA As Variant: preciseA = CDec(0.1)
Dim preciseB As Variant: preciseB = CDec(0.11)
Dim notPreciseA As Double: notPreciseA = 0.1
Dim notPreciseB As Double: notPreciseB = 0.11
Debug.Print preciseA + preciseB
Debug.Print preciseA + preciseB = 0.21 'True
Debug.Print notPreciseA + notPreciseB
Debug.Print notPreciseA + notPreciseB = 0.21 'False
End Sub
If every char in the file is properly encoded in UTF-8, you won't have any problem reading it using a reader with the UTF-8 encoding. Up to you to check every char of the file and see if you consider it printable or not.
Assuming:
(unsigned long)
you mean unsigned 32-bit integer,then you just need to add 2**32 (or 1 << 32)
to the negative value.
For example, apply this to -1:
>>> -1
-1
>>> _ + 2**32
4294967295L
>>> bin(_)
'0b11111111111111111111111111111111'
Assumption #1 means you want -1 to be viewed as a solid string of 1 bits, and assumption #2 means you want 32 of them.
Nobody but you can say what your hidden assumptions are, though. If, for example, you have 1's-complement representations in mind, then you need to apply the ~
prefix operator instead. Python integers work hard to give the illusion of using an infinitely wide 2's complement representation (like regular 2's complement, but with an infinite number of "sign bits").
And to duplicate what the platform C compiler does, you can use the ctypes
module:
>>> import ctypes
>>> ctypes.c_ulong(-1) # stuff Python's -1 into a C unsigned long
c_ulong(4294967295L)
>>> _.value
4294967295L
C's unsigned long
happens to be 4 bytes on the box that ran this sample.
The first thing to do is to install the dependencies.
sudo apt-get build-dep python-psycopg2
After that go inside your virtualenv and use
pip install psycopg2-binary
These two commands should solve the problem.
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
One suggestion in other answers is to use ax.set_axis_bgcolor("red")
. This however is deprecated, and doesn't work on MatPlotLib >= v2.0.
There is also the suggestion to use ax.patch.set_facecolor("red")
(works on both MatPlotLib v1.5 & v2.2). While this works fine, an even easier solution for v2.0+ is to use
ax.set_facecolor("red")
System.exit(int i)
is to be used, but I would include it inside a more generic shutdown()
method, where you would include "cleanup" steps as well, closing socket connections, file descriptors, then exiting with System.exit(x)
.
The option to save the .orig file can be disabled by configuring KDiff3
using System.Linq;
list.Where(x=> x.Name == nameToExtract);
Edit: misread question (now all matches)
There is also a nice implementation described here by McEwan and @StefanGustavson that looks like Perlin noise, but "does not require any setup, i.e. not textures nor uniform arrays. Just add it to your shader source code and call it wherever you want".
That's very handy, especially given that Gustavson's earlier implementation, which @dep linked to, uses a 1D texture, which is not supported in GLSL ES (the shader language of WebGL).
an existing folder will FAIL with FileExists
Function FileExists(strFileName)
' Check if a file exists - returns True or False
use instead or in addition:
Function FolderExists(strFolderPath)
' Check if a path exists
NULL-safe condition would looks like:
select * from table
where NOT (tester <=> 'username')
I've found three commands on how you can change your Git branch name, and these commands are a faster way to do that:
git branch -m old_branch new_branch # Rename branch locally
git push origin :old_branch # Delete the old branch
git push --set-upstream origin new_branch # Push the new branch, set local branch to track the new remote
If you need step-by-step you can read this great article:
I forgot to tell a bug when i use I use req.session.email = req.param('email'), the server error says cannot sett property email of undefined.
The reason of this error is a wrong order of app.use. You must configure express in this order:
app.use(express.cookieParser());
app.use(express.session({ secret: sessionVal }));
app.use(app.route);
You don't need to --relocate
since the branch is within the same repository URL. Just do:
svn switch https://www.example.com/svn/branches/v1p2p3
Using NOT EXISTS
:
INSERT INTO TABLE_2
(id, name)
SELECT t1.id,
t1.name
FROM TABLE_1 t1
WHERE NOT EXISTS(SELECT id
FROM TABLE_2 t2
WHERE t2.id = t1.id)
Using NOT IN
:
INSERT INTO TABLE_2
(id, name)
SELECT t1.id,
t1.name
FROM TABLE_1 t1
WHERE t1.id NOT IN (SELECT id
FROM TABLE_2)
Using LEFT JOIN/IS NULL
:
INSERT INTO TABLE_2
(id, name)
SELECT t1.id,
t1.name
FROM TABLE_1 t1
LEFT JOIN TABLE_2 t2 ON t2.id = t1.id
WHERE t2.id IS NULL
Of the three options, the LEFT JOIN/IS NULL
is less efficient. See this link for more details.
I got this error with a mis-configured test event. I changed the source buckets ARN but forgot to edit the default S3 bucket name.
I.e. make sure that in the bucket section of the test event both the ARN and bucket name are set correctly:
"bucket": {
"arn": "arn:aws:s3:::your_bucket_name",
"name": "your_bucket_name",
"ownerIdentity": {
"principalId": "EXAMPLE"
}
Here's my best try:
.inner_shadow {_x000D_
color:transparent;_x000D_
background-color:white;_x000D_
text-shadow: 0 0 20px rgba(198,28,39,0.8), 0 0 0 black;_x000D_
font-family:'ProclamateHeavy'; // Or whatever floats your boat_x000D_
font-size:150px;_x000D_
}
_x000D_
_x000D_
<span class="inner_shadow">Inner Shadow</span>_x000D_
_x000D_
The problem is how to clip the shadow that bleeds around the edges!!! I tried in webkit using background-clip:text, but webkit renders the shadow above the background so it doesn't work.
Making a Text Mask with CSS?
Without a top mask layer it is impossible to do a true inner shadow on text.
Perhaps someone should recommend that the W3C add background-clip: reverse-text, that would cut a mask through the background instead of cutting the background to fit inside the text.
Either that or render the text-shadow as part of the background and clip it with background-clip: text.
I tried absolutely positioning an identical text element above it, but the problem is background-clip: text crops the background to fit inside the text, but we need the reverse of that.
I tried using text-stroke: 20px white; on both this element and the one above it, but the text stroke goes in as well as out.
Alternate Methods
Since there is currently no way to make an inverted-text mask in CSS, you could turn to SVG or Canvas and make a text replacement image with the three layers to get your effect.
Since SVG is a subset of XML, SVG text would still be select-able and searchable, and the effect can be produced with less code than Canvas.
It would be harder to achieve this with Canvas because it doesn't have a dom with layers like SVG does.
You could produce the SVG either server-side, or as a javascript text-replacement method in the browser.
Further Reading:
SVG versus Canvas:
http://dev.opera.com/articles/view/svg-or-canvas-choosing-between-the-two/
Clipping and Masking with SVG Text:
Note you are not allowed to nest FORM elements!
http://www.w3.org/MarkUp/html3/forms.html
https://www.w3.org/TR/html4/appendix/changes.html#h-A.3.9 (html4 specification notes no changes regarding nesting forms from 3.2 to 4)
https://www.w3.org/TR/html4/appendix/changes.html#h-A.1.1.12 (html4 specification notes no changes regarding nesting forms from 4.0 to 4.1)
https://www.w3.org/TR/html5-diff/ (html5 specification notes no changes regarding nesting forms from 4 to 5)
https://www.w3.org/TR/html5/forms.html#association-of-controls-and-forms comments to "This feature allows authors to work around the lack of support for nested form elements.", but does not cite where this is specified, I think they are assuming that we should assume that it's specified in the html3 specification :)
public class Preferences {
public static final String PREF_NAME = "your preferences name";
@SuppressWarnings("deprecation")
public static final int MODE = Context.MODE_WORLD_WRITEABLE;
public static final String USER_ID = "USER_ID_NEW";
public static final String USER_NAME = "USER_NAME";
public static final String NAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String PHONE = "PHONE";
public static final String address = "address";
public static void writeBoolean(Context context, String key, boolean value) {
getEditor(context).putBoolean(key, value).commit();
}
public static boolean readBoolean(Context context, String key,
boolean defValue) {
return getPreferences(context).getBoolean(key, defValue);
}
public static void writeInteger(Context context, String key, int value) {
getEditor(context).putInt(key, value).commit();
}
public static int readInteger(Context context, String key, int defValue) {
return getPreferences(context).getInt(key, defValue);
}
public static void writeString(Context context, String key, String value) {
getEditor(context).putString(key, value).commit();
}
public static String readString(Context context, String key, String defValue) {
return getPreferences(context).getString(key, defValue);
}
public static void writeFloat(Context context, String key, float value) {
getEditor(context).putFloat(key, value).commit();
}
public static float readFloat(Context context, String key, float defValue) {
return getPreferences(context).getFloat(key, defValue);
}
public static void writeLong(Context context, String key, long value) {
getEditor(context).putLong(key, value).commit();
}
public static long readLong(Context context, String key, long defValue) {
return getPreferences(context).getLong(key, defValue);
}
public static SharedPreferences getPreferences(Context context) {
return context.getSharedPreferences(PREF_NAME, MODE);
}
public static Editor getEditor(Context context) {
return getPreferences(context).edit();
}
}
****Use Preferences to Write value using:-****
Preferences.writeString(getApplicationContext(),
Preferences.NAME, "dev");
****Use Preferences to Read value using:-****
Preferences.readString(getApplicationContext(), Preferences.NAME,
"");
One problem with option 1 in answer from Victor Zamanian is that if the type isn't exported then users of your package can't declare it as the type for function parameters etc. One way around this would be to export an interface instead of the struct e.g.
package candidate
// Exporting interface instead of struct
type Candidate interface {}
// Struct is not exported
type candidate struct {
Name string
Votes uint32 // Defaults to 0
}
// We are forced to call the constructor to get an instance of candidate
func New(name string) Candidate {
return candidate{name, 0} // enforce the default value here
}
Which lets us declare function parameter types using the exported Candidate interface. The only disadvantage I can see from this solution is that all our methods need to be declared in the interface definition, but you could argue that that is good practice anyway.
I had this error in code that looked like this:
int A = 1;
int B = A;
The fix is to change it to this
int A = 1;
#define B A
The compiler assigns a location in memory to a variable. The second is trying a assign a second variable to the same location as the first - which makes no sense. Using the macro preprocessor solves the problem.
if(displayit){
login_div.Style["display"]="inline"; //the default display mode
}else{
login_div.Style["display"]="none";
}
Adding this code into Page_Load
should work. (if doing it at Page_Init you'll have to contend with viewstate changing what you put in it)
checkexists() {
while [ -n "$1" ]; do
[ -n "$(which "$1")" ] || echo "$1": command not found
shift
done
}
Not a lot to go on there, but I think what you're looking for is to flip the width
and max-width
values:
#container2 {
width: 90%;
max-width: 960px;
/* etc, etc... */
}
That'll give you a container that's 90% of the width of the available space, up to a maximum of 960px, but that's dependent on its container being resizable itself. Responsive design is a whole big ball of wax though, so this doesn't even scratch the surface.
You can use the Like
operator with a wildcard to determine whether a given substring exists in a string, for example:
If cell.Value Like "*Word1*" Then
'...
ElseIf cell.Value Like "*Word2*" Then
'...
End If
In this example the *
character in "*Word1*"
is a wildcard character which matches zero or more characters.
NOTE: The Like
operator is case-sensitive, so "Word1" Like "word1"
is false, more information can be found on this MSDN page.
In phpMyAdmin, navigate to the table in question and click the "Operations" tab. On the left under Table Options you will be allowed to set the current AUTO_INCREMENT value.
Note: This is an answer useful for Python's ElementTree standard library without using hardcoded namespaces.
To extract namespace's prefixes and URI from XML data you can use ElementTree.iterparse
function, parsing only namespace start events (start-ns):
>>> from io import StringIO
>>> from xml.etree import ElementTree
>>> my_schema = u'''<rdf:RDF xml:base="http://dbpedia.org/ontology/"
... xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
... xmlns:owl="http://www.w3.org/2002/07/owl#"
... xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
... xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
... xmlns="http://dbpedia.org/ontology/">
...
... <owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
... <rdfs:label xml:lang="en">basketball league</rdfs:label>
... <rdfs:comment xml:lang="en">
... a group of sports teams that compete against each other
... in Basketball
... </rdfs:comment>
... </owl:Class>
...
... </rdf:RDF>'''
>>> my_namespaces = dict([
... node for _, node in ElementTree.iterparse(
... StringIO(my_schema), events=['start-ns']
... )
... ])
>>> from pprint import pprint
>>> pprint(my_namespaces)
{'': 'http://dbpedia.org/ontology/',
'owl': 'http://www.w3.org/2002/07/owl#',
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
'xsd': 'http://www.w3.org/2001/XMLSchema#'}
Then the dictionary can be passed as argument to the search functions:
root.findall('owl:Class', my_namespaces)
Change your positioning a bit:
.container {
border: 1px solid #DDDDDD;
width: 200px;
height: 200px;
position:relative;
}
.tag {
float: left;
position: absolute;
left: 0px;
top: 0px;
background-color: green;
}
You need to set relative positioning on the container and then absolute on the inner tag div. The inner tag's absolute positioning will be with respect to the outer relatively positioned div. You don't even need the z-index rule on the tag div.
As shown below, range
only supports integers:
>>> range(15.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got float.
>>> range(15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>>
However, c/10
is a float because /
always returns a float.
Before you put it in range
, you need to make c/10
an integer. This can be done by putting it in int
:
range(int(c/10))
or by using //
, which returns an integer:
range(c//10)
Adding margins to a button makes it wider so that les buttons fit in the grid system. If only a visual effect is important, then give the button a white border with [style="margin:0px; border:solid white;"] This leaves the button width unaffected.
Thanks for the above script. One little modification to add in the file ending correctly. Try this ...
$filenameFormat = "MyFileName" + " " + (Get-Date -Format "yyyy-MM-dd") **+ ".txt"**
Rename-Item -Path "C:\temp\MyFileName.txt" -NewName $filenameFormat
I have moved into the world of namespace specific open graph data and therefore dont rely on the FB types. See "edit open graph" in the apps dev tool dashboard.
IMO (and it is only an opinion) the key characteristic of an object orientated language would be that it would support polymorphism. Pretty much all dynamic languages do that.
The next characteristic would be encapsulation and that is pretty easy to do in Javascript also.
However in the minds of many it is inheritance (specifically implementation inheritance) which would tip the balance as to whether a language qualifies to be called object oriented.
Javascript does provide a fairly easy means to inherit implementation via prototyping but this is at the expense of encapsulation.
So if your criteria for object orientation is the classic threesome of polymorphism, encapsulation and inheritance then Javascript doesn't pass.
Edit: The supplementary question is raised "how does prototypal inheritance sacrifice encapsulation?" Consider this example of a non-prototypal approach:-
function MyClass() {
var _value = 1;
this.getValue = function() { return _value; }
}
The _value attribute is encapsulated, it cannot be modified directly by external code. We might add a mutator to the class to modify it in a way entirely controlled by code that is part of the class. Now consider a prototypal approach to the same class:-
function MyClass() {
var _value = 1;
}
MyClass.prototype.getValue = function() { return _value; }
Well this is broken. Since the function assigned to getValue is no longer in scope with _value it can't access it. We would need to promote _value to an attribute of this
but that would make it accessable outside of the control of code written for the class, hence encapsulation is broken.
Despite this my vote still remains that Javascript is object oriented. Why? Because given an OOD I can implement it in Javascript.
public static class Employee
{
public static string SomeSetting
{
get
{
return ConfigurationManager.AppSettings["SomeSetting"];
}
}
}
Declare the property as static, as well. Also, Don't bother storing a private reference to ConfigurationManager.AppSettings. ConfigurationManager is already a static class.
If you feel that you must store a reference to appsettings, try
public static class Employee
{
private static NameValueCollection _appSettings=ConfigurationManager.AppSettings;
public static NameValueCollection AppSettings { get { return _appSettings; } }
}
It's good form to always give an explicit access specifier (private, public, etc) even though the default is private.
The Best Way I Can Use My Project.Use hasOwnProperty
in Tricky Way!.
var arr = []; (or) arr = new Array();
var obj = {}; (or) arr = new Object();
arr.constructor.prototype.hasOwnProperty('push') //true (This is an Array)
obj.constructor.prototype.hasOwnProperty('push') // false (This is an Object)
I use Fragments for better user experience. For example if you have a Button and you want to run let's say a webservice when you click it, I attach a Fragment to the parent Activity.
if (id == R.id.forecast) {
ForecastFragment forecastFragment = new ForecastFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.main_content, forecastFragment);
ft.addToBackStack("backstack");
forecastFragment.setArguments(b);
ft.commit();
}
In that way the user won't have to move in another activity.
And secondly I prefer Fragments because you can handle them easily during rotation.
After installing Microsoft.Web.Infrastructure through Nuget-Package Manager
PM> Install-Package Microsoft.Web.Infrastructure
Copy the Microsoft.Web.Infrastructure.dll
manually from the Nuget-Package
folder on your web application and then paste it in your bin folder of your web application deployed on the web server.
packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll
It worked for me.
take a look here
SELECT SUBSTR('Take the first four characters', 1, 4) FIRST_FOUR FROM DUAL;
Finally found perfect solution to hide default back text in whole app.
Just add one transparent Image and add following code in your AppDelegate.
UIBarButtonItem.appearance().setBackButtonBackgroundImage(#imageLiteral(resourceName: "transparent"), for: .normal, barMetrics: .default)
This workaround worked for me...
<td style="white-space: normal; width:300px;">
When I used --allow-unrelated-histories
, this command generated too many conflicts. There were conflicts in files which I didn't even work on. To get over the error " Refusing to merge unrelated histories"
, I used following rebase command:
git pull --rebase=preserve --allow-unrelated-histories
After this commit the uncommitted changes with a commit message. Finally, run the following command:
git rebase --continue
After this, my working copy was up-to-date with the remote copy and I was able to push my changes as before. No more unrelated histories error while pulling.
When Card I always use RoundedRectangleBorder.
Card(
color: Colors.grey[900],
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.white70, width: 1),
borderRadius: BorderRadius.circular(10),
),
margin: EdgeInsets.all(20.0),
child: Container(
child: Column(
children: <Widget>[
ListTile(
title: Text(
'example',
style: TextStyle(fontSize: 18, color: Colors.white),
),
),
],
),
),
),
My original reply was factually incorrect and I'm glad it was removed. The code below will work under the following conditions a) you know that nobody else modified the sequence b) the sequence was modified by your session. In my case, I encountered a similar issue where I was calling a procedure which modified a value and I'm confident the assumption is true.
SELECT mysequence.CURRVAL INTO v_myvariable FROM DUAL;
Sadly, if you didn't modify the sequence in your session, I believe others are correct in stating that the NEXTVAL is the only way to go.
Available in OS X v10.7 and later.
If you are worried about the order,right way to do
NSArray *no = [[NSOrderedSet orderedSetWithArray:originalArray]allObjects];
Here is the code of removing duplicates values from NSArray in Order.
Borrowed from @Deena above, that function modification for labels is more versatile than you might have thought. For example, I had a ggplot where the denominator of counted variables was 140. I used her example thus:
scale_y_continuous(labels = function(x) paste0(round(x/140*100,1), "%"), breaks = seq(0, 140, 35))
This allowed me to get my percentages on the 140 denominator, and then break the scale at 25% increments rather than the weird numbers it defaulted to. The key here is that the scale breaks are still set by the original count, not by your percentages. Therefore the breaks must be from zero to the denominator value, with the third argument in "breaks" being the denominator divided by however many label breaks you want (e.g. 140 * 0.25 = 35).
Run command:
c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ga %username%
c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
reloadRowsAtIndexPaths:
is fine, but still will force UITableViewDelegate
methods to fire.
The simplest approach I can imagine is:
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
[self configureCell:cell forIndexPath:indexPath];
It's important to invoke your configureCell:
implementation on main thread, as it wont work on non-UI thread (the same story with reloadData
/reloadRowsAtIndexPaths:
). Sometimes it might be helpful to add:
dispatch_async(dispatch_get_main_queue(), ^
{
[self configureCell:cell forIndexPath:indexPath];
});
It's also worth to avoid work that would be done outside of the currently visible view:
BOOL cellIsVisible = [[self.tableView indexPathsForVisibleRows] indexOfObject:indexPath] != NSNotFound;
if (cellIsVisible)
{
....
}
Well if you want fully transparent than you can use
border: 5px solid transparent;
If you mean opaque/transparent, than you can use
border: 5px solid rgba(255, 255, 255, .5);
Here, a
means alpha, which you can scale, 0-1.
Also some might suggest you to use opacity
which does the same job as well, the only difference is it will result in child elements getting opaque too, yes, there are some work arounds but rgba
seems better than using opacity
.
For older browsers, always declare the background color using #
(hex) just as a fall back, so that if old browsers doesn't recognize the rgba
, they will apply the hex
color to your element.
Demo 2 (With a background image for nested div)
Demo 3 (With an img
tag instead of a background-image
)
body {
background: url(http://www.desktopas.com/files/2013/06/Images-1920x1200.jpg);
}
div.wrap {
border: 5px solid #fff; /* Fall back, not used in fiddle */
border: 5px solid rgba(255, 255, 255, .5);
height: 400px;
width: 400px;
margin: 50px;
border-radius: 50%;
}
div.inner {
background: #fff; /* Fall back, not used in fiddle */
background: rgba(255, 255, 255, .5);
height: 380px;
width: 380px;
border-radius: 50%;
margin: auto; /* Horizontal Center */
margin-top: 10px; /* Vertical Center ... Yea I know, that's
manually calculated*/
}
Note (For Demo 3): Image will be scaled according to the height and width provided so make sure it doesn't break the scaling ratio.
If you care to check for overflows and have Guava handy, there is Ints.checkedCast()
:
int theInt = Ints.checkedCast(theLong);
The implementation is dead simple, and throws IllegalArgumentException on overflow:
public static int checkedCast(long value) {
int result = (int) value;
checkArgument(result == value, "Out of range: %s", value);
return result;
}
i just update my android studio from 2.3.2 to 3.1.2 version. and this error occurs.
i clean project, rebuild project, invalidate cache/restart but nothing works.
i resolve this error by updating appcompat library from
compile 'com.android.support:appcompat-v7:23.4.0'
to
compile 'com.android.support:appcompat-v7:25.1.1'
in app build.gradle file.
Python is very sensitive to indentation, with the code below I got the same error:
except IntegrityError as e:
if 'unique constraint' in e.args:
return render(request, "calender.html")
The correct indentation is:
except IntegrityError as e:
if 'unique constraint' in e.args:
return render(request, "calender.html")
I've searched around, and only this solution helped me:
mysql -u root -p
set global net_buffer_length=1000000; --Set network buffer length to a large byte number
set global max_allowed_packet=1000000000; --Set maximum allowed packet size to a large byte number
SET foreign_key_checks = 0; --Disable foreign key checking to avoid delays,errors and unwanted behaviour
source file.sql --Import your sql dump file
SET foreign_key_checks = 1; --Remember to enable foreign key checks when procedure is complete!
The answer is found here.
Rajesh's suggestion did not work for me. What I did was go to
File -> Settings ->HTTP Proxy(Under IDE Settings) ->Manual proxy configuration
I still left the proxy information in Project Settings under Gradle, like Rajesh suggested. But I'm not entirely sure if it's necessary.
I am using 0.8.6 Beta
I am a fan of Cmder, a package including clink, conemu, msysgit, and some cosmetic enhancements.
https://github.com/cmderdev/cmder
While technically valid, all these jumps obscure control flow -- especially the continue
statement.
I would use such a trick as a last resort, not first one.
How about
while (something = get_something())
{
switch (something)
{
case A:
case B:
do_something();
}
}
It's shorter and perform its stuff in a more clear way.
In Xcode 4.x press
(or click Menubar
> Product
> Scheme
> Edit Scheme
)
select the "Diagnostics" tab and click "Enable Zombie Objects":
This turns released objects into NSZombie instances that print console warnings when used again. This is a debugging aid that increases memory use (no object is really released) but improves error reporting.
A typical case is when you over-release an object and you don't know which one:
-[UITableView release]: message sent to deallocated instance
This Xcode setting is ignored when you archive the application for App Store submission. You don't need to touch anything before releasing your application.
Pressing ??R is the same as selecting Product > Run while keeping the Alt key pressed.
Clicking the "Enable Zombie Objects" checkbox is the same as manually adding "NSZombieEnabled = YES" in the section "Environment Variables" of the tab Arguments.
In my case it happened when calling a function by passing a parameter of a Core Data managed object's property. At the time of calling the object was no longer existed, and that caused this error.
I have solved the issue by checking if the managed object exists or not before calling the function.
I use this mnemonic:
This is not 100% correct according to the specs, but this mnemonic helps me (human being).
Verified the following on Virtualbox-5.0.24, Android_x86-4.4-r5. You get a screen similar to an 8" table. You can play around with the xxx in DPI=xxx, to change the resolution. xxx=100 makes it really small to match a real table exactly, but it may be too small when working with android in Virtualbox.
VBoxManage setextradata <VmName> "CustomVideoMode1" "440x680x16"
With the following appended to android kernel cmd:
UVESA_MODE=440x680 DPI=120
Use jQuery.attr()
in your click handler:
$("#myform").attr('action', 'page1.php');
Systemd which now runs in the majority of distros
Find your user defined services mine was at /usr/lib/systemd/system/
Create a text file with your favorite text editor name it whatever_you_want.service
Put following
Template to the file whatever_you_want.service
[Unit]
Description=webserver Daemon
[Service]
ExecStart=/usr/bin/java -jar /web/server.jar
User=user
[Install]
WantedBy=multi-user.target
Run your service
as super user
$ systemctl start whatever_you_want.service # starts the service
$ systemctl enable whatever_you_want.service # auto starts the service
$ systemctl disable whatever_you_want.service # stops autostart
$ systemctl stop whatever_you_want.service # stops the service
$ systemctl restart whatever_you_want.service # restarts the service
Try this one:
HTML:
<div id="para1"></div>
JavaScript:
document.getElementById("para1").innerHTML = formatAMPM();
function formatAMPM() {
var d = new Date(),
minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
ampm = d.getHours() >= 12 ? 'pm' : 'am',
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
}
Result:
Mon Sep 18 2017 12:40pm
probably the onclick
handler should read onclick='hello();'
instead of onclick=hello();
To open and read a text file line per line, you could use the following:
// define your file name
string file_name = "data.txt";
// attach an input stream to the wanted file
ifstream input_stream(file_name);
// check stream status
if (!input_stream) cerr << "Can't open input file!";
// file contents
vector<string> text;
// one line
string line;
// extract all the text from the input file
while (getline(input_stream, line)) {
// store each line in the vector
text.push_back(line);
}
To open and read a binary file you need to explicitly declare the reading format in your input stream to be binary, and read memory that has no explicit interpretation using stream member function read()
:
// define your file name
string file_name = "binary_data.bin";
// attach an input stream to the wanted file
ifstream input_stream(file_name, ios::binary);
// check stream status
if (!input_stream) cerr << "Can't open input file!";
// use function that explicitly specifies the amount of block memory read
int memory_size = 10;
// allocate 10 bytes of memory on heap
char* dynamic_buffer = new char[memory_size];
// read 10 bytes and store in dynamic_buffer
file_name.read(dynamic_buffer, memory_size);
When doing this you'll need to #include
the header : <iostream>
you must use [ngModel] instead of two way model binding with [(ngModel)]. then use manual change event with (ngModelChange). this is public rule for all two way input in components.
because pipe on event emitter is wrong.
You can rename classes or any file by hitting F2 on the filename in Eclipse. It will ask you if you want to update references. It's really as easy as that :)
For the record: The following snippet can help you to get details about input, textarea, select, button, a tags through a temp title when hover them.
$( 'body' ).on( 'mouseover', 'input, textarea, select, button, a', function() {
var $tag = $( this );
var $form = $tag.closest( 'form' );
var title = this.title;
var id = this.id;
var name = this.name;
var value = this.value;
var type = this.type;
var cls = this.className;
var tagName = this.tagName;
var options = [];
var hidden = [];
var formDetails = '';
if ( $form.length ) {
$form.find( ':input[type="hidden"]' ).each( function( index, el ) {
hidden.push( "\t" + el.name + ' = ' + el.value );
} );
var formName = $form.prop( 'name' );
var formTitle = $form.prop( 'title' );
var formId = $form.prop( 'id' );
var formClass = $form.prop( 'class' );
formDetails +=
"\n\nFORM NAME: " + formName +
"\nFORM TITLE: " + formTitle +
"\nFORM ID: " + formId +
"\nFORM CLASS: " + formClass +
"\nFORM HIDDEN INPUT:\n" + hidden.join( "\n" );
}
var tempTitle =
"TAG: " + tagName +
"\nTITLE: " + title +
"\nID: " + id +
"\nCLASS: " + cls;
if ( 'SELECT' === tagName ) {
$tag.find( 'option' ).each( function( index, el ) {
options.push( el.value );
} );
tempTitle +=
"\nNAME: " + name +
"\nVALUE: " + value +
"\nTYPE: " + type +
"\nSELECT OPTIONS:\n\t" + options;
} else if ( 'A' === tagName ) {
tempTitle +=
"\nHTML: " + $tag.html();
} else {
tempTitle +=
"\nNAME: " + name +
"\nVALUE: " + value +
"\nTYPE: " + type;
}
tempTitle += formDetails;
$tag.prop( 'title', tempTitle );
$tag.on( 'mouseout', function() {
$tag.prop( 'title', title );
} )
} );
Here is an example of showing the line number of where exception takes place.
import sys
try:
print(5/0)
except Exception as e:
print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
print('And the rest of program continues')
srand
doesn't return anything so you can't initialize a
with its return value because, well, because it doesn't return a value. Did you mean to call rand
as well?
My problem was that the Id of the table is not AUTO_INCREMENT and I was trying to add range.
An explicit default initialization can help:
struct foo {
bool a {};
bool b {};
bool c {};
} bar;
Behavior bool a {}
is same as bool b = bool();
and return false
.
By setting script tag type
other than text/javascript
, browser will not execute the internal code of script tag. This is called micro template. This concept is widely used in Single page application(aka SPA).
<script type="text/template">I am a Micro template.
I am going to make your web page faster.</script>
For micro template, type of the script tag is text/template
. It is very well explained by Jquery creator John Resig http://ejohn.org/blog/javascript-micro-templating/
In order to work on all modern browsers, you will need two steps:
Add javascript:void(0);
as src
attribute for the iframe element. Otherwise the content will be overriden by the empty src
on Firefox.
<iframe src="javascript:void(0);"></iframe>
Programatically change the content of the inner html
element.
$(iframeSelector).contents().find('html').html(htmlContent);
Step 1 from comment (link) by @susan
Step 2 from solutions (link1, link2) by @erimerturk and @x10
When I needed HTML to PDF conversion earlier this year, I tried the trial of Winnovative HTML to PDF converter (I think ExpertPDF is the same product, too). It worked great so we bought a license at that company. I don't go into it too in depth after that.
You'll have it in your connection string like:
"mysql:host=$host;dbname=$db;charset=utf8"
HOWEVER, prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:
$dbh = new PDO("mysql:$connstr", $user, $password);
$dbh->exec("set names utf8");
For increasing execution time and file size, you need to mention below values in your .htaccess file. It will work.
php_value upload_max_filesize 80M
php_value post_max_size 80M
php_value max_input_time 18000
php_value max_execution_time 18000
One way is to use the Database property off the DbContext:
SqlParameter param1 = new SqlParameter("@firstName", "Frank");
SqlParameter param2 = new SqlParameter("@lastName", "Borland");
context.Database.ExecuteSqlCommand("sp_MyStoredProc @firstName, @lastName",
param1, param2);
EF5 definitely supports that.
I do neither for a daily complete reload of data. For example say I am loading my Denver site. There are other strategies for near real time deltas.
I use a create table SQL as I have found is just almost as fast as a bulk load For example, below a create table statement is used to stage the data, casting the columns to the correct data type needed:
CREATE TABLE sales_dataTemp as select cast (column1 as Date) as SALES_QUARTER, cast (sales as number) as SALES_IN_MILLIONS, .... FROM TABLE1;
this temporary table mirrors my target table's structure exactly which is list partitioned by site. I then do a partition swap with the DENVER partition and I have a new data set.
to deal with Null Comparisons use Object.Equals()
instead of ==
check this reference
In my benchmark script, each method is tested 10000 times and the difference of the total time for each method is printed. You should this on your own configuration, I'm sure results will vary!
These are my results:
SELECT NULL" -> PGO()
faster by ~ 0.35 secondsSHOW TABLE STATUS" -> mysqli()
faster by ~ 2.3 secondsSELECT * FROM users" -> mysqli()
faster by ~ 33 secondsNote: by using ->fetch_row() for mysqli, the column names are not added to the array, I didn't find a way to do that in PGO. But even if I use ->fetch_array() , mysqli is slightly slower but still faster than PGO (except for SELECT NULL).
Simple solution would be as below. This is improvement of solution from vale.
private void dgMapTable_SelectionChanged(object sender, EventArgs e)
{
int active_map=0;
if(dgMapTable.SelectedRows.Count>0)
active_map = dgMapTable.SelectedRows[0].Index;
// User code if required Process_ROW(active_map);
}
Note for other reader, for above code to work FullRowSelect
selection mode for datagridview should be used. You may extend this to give message if more than two rows selected.
Though this question is rather old, here's a answer :)
What you are asking for can be achieved by using jQuery's .click() event method and .on() event method
So this could be the code:
// Set the global variables
var userImage = $("#img-giLkojRpuK");
var hangoutButton = $("#hangout-giLkojRpuK");
$(document).ready(function() {
// When the document is ready/loaded, execute function
// Hide hangoutButton
hangoutButton.hide();
// Assign "click"-event-method to userImage
userImage.on("click", function() {
console.log("in onclick");
hangoutButton.click();
});
});
you can use
git name-rev --name-only HEAD
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
I don't know how to delete all at once, but you can use ipcs
to list resources, and then use loop and delete with ipcrm
. This should work, but it needs a little work. I remember that I made it work once in class.
There is an easy way, just remove the symbolic link from "/usr/bin". It will work.
You can do like below to achieve your result:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
....
....
#use filter with plot
#or
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') | (df1['Retailer country']=='France')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
#also
#and
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') & (df1['Year']=='2013')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
If you use Eclipse Collections you can use the collectIf()
method.
MutableList<Integer> source =
Lists.mutable.with(1, null, 2, null, 3, null, 4, null, 5);
MutableList<String> result = source.collectIf(Objects::nonNull, String::valueOf);
Assert.assertEquals(Lists.immutable.with("1", "2", "3", "4", "5"), result);
It evaluates eagerly and should be a bit faster than using a Stream.
Note: I am a committer for Eclipse Collections.
For my enums I don't really like to think of them being allocated with 1 String each. This is how I implement a toString() method on enums.
enum Animal
{
DOG, CAT, BIRD;
public String toString(){
switch (this) {
case DOG: return "Dog";
case CAT: return "Cat";
case BIRD: return "Bird";
}
return null;
}
}
SELECT STR_TO_DATE(dateString, '%d/%m/%y') FROM yourTable...
You have to put the entire path as a parameter to os.path.split. See The docs. It doesn't work like string split.
In your giant elif
chain, you skipped 13. You might want to throw an error if you hit the end of the chain without returning anything, to catch numbers you missed and incorrect calls of the function:
...
elif x == 90:
return 6
else:
raise ValueError(x)
You can also solve this problem by creating an array of values and assigning that array:
newheaders <- c("a", "b", "c", ... "x")
colnames(data) <- newheaders
When you echo $array;
, the result is Array
, result[0]
then represents the first character in Array
which is A
.
One way to handle this problem would be like this:
ajax.php
<?php
$array = array(1,2,3,4,5,6);
foreach($array as $a)
echo $a.",";
?>
jquery code
$(function(){ /* short for $(document).ready(function(){ */
$('#prev').click(function(){
$.ajax({type: 'POST',
url: 'ajax.php',
data: 'id=testdata',
cache: false,
success: function(data){
var tmp = data.split(",");
$('#content1').html(tmp[0]);
}
});
});
});
Alternatively, you can install "SourceForge Notepad++ Compare Plugin 1.5.6". It provides compare functionality between two files and show the differences between two files.
Link to refer : https://sourceforge.net/projects/npp-compare/files/1.5.6/
You could use a lookahead:
re.split(r'[ ](?=[A-Z]+\b)', input)
This will split at every space that is followed by a string of upper-case letters which end in a word-boundary.
Note that the square brackets are only for readability and could as well be omitted.
If it is enough that the first letter of a word is upper case (so if you would want to split in front of Hello
as well) it gets even easier:
re.split(r'[ ](?=[A-Z])', input)
Now this splits at every space followed by any upper-case letter.
Uncheck
"Work Offline"
in Settings -> Maven ! It worked for me ! :D
Use str.replace
.
>>> papa.replace('papa', '')
' is a good man'
>>> app.replace('papa', '')
'app is important'
Alternatively use re
and use regular expressions. This will allow the removal of leading/trailing spaces.
>>> import re
>>> papa = 'papa is a good man'
>>> app = 'app is important'
>>> papa3 = 'papa is a papa, and papa'
>>>
>>> patt = re.compile('(\s*)papa(\s*)')
>>> patt.sub('\\1mama\\2', papa)
'mama is a good man'
>>> patt.sub('\\1mama\\2', papa3)
'mama is a mama, and mama'
>>> patt.sub('', papa3)
'is a, and'
Numpy is required by pandas (and by virtually all numerical tools for Python). Scipy is not strictly required for pandas but is listed as an "optional dependency". I wouldn't say that pandas is an alternative to Numpy and/or Scipy. Rather, it's an extra tool that provides a more streamlined way of working with numerical and tabular data in Python. You can use pandas data structures but freely draw on Numpy and Scipy functions to manipulate them.
Here are a few ways:
1) sub
sub(".*:", "", string)
## [1] "E001" "E002" "E003"
2) strsplit
sapply(strsplit(string, ":"), "[", 2)
## [1] "E001" "E002" "E003"
3) read.table
read.table(text = string, sep = ":", as.is = TRUE)$V2
## [1] "E001" "E002" "E003"
4) substring
This assumes second portion always starts at 4th character (which is the case in the example in the question):
substring(string, 4)
## [1] "E001" "E002" "E003"
4a) substring/regex
If the colon were not always in a known position we could modify (4) by searching for it:
substring(string, regexpr(":", string) + 1)
5) strapplyc
strapplyc
returns the parenthesized portion:
library(gsubfn)
strapplyc(string, ":(.*)", simplify = TRUE)
## [1] "E001" "E002" "E003"
6) read.dcf
This one only works if the substrings prior to the colon are unique (which they are in the example in the question). Also it requires that the separator be colon (which it is in the question). If a different separator were used then we could use sub
to replace it with a colon first. For example, if the separator were _
then string <- sub("_", ":", string)
c(read.dcf(textConnection(string)))
## [1] "E001" "E002" "E003"
7) separate
7a) Using tidyr::separate
we create a data frame with two columns, one for the part before the colon and one for after, and then extract the latter.
library(dplyr)
library(tidyr)
library(purrr)
DF <- data.frame(string)
DF %>%
separate(string, into = c("pre", "post")) %>%
pull("post")
## [1] "E001" "E002" "E003"
7b) Alternately separate
can be used to just create the post
column and then unlist
and unname
the resulting data frame:
library(dplyr)
library(tidyr)
DF %>%
separate(string, into = c(NA, "post")) %>%
unlist %>%
unname
## [1] "E001" "E002" "E003"
8) trimws We can use trimws
to trim word characters off the left and then use it again to trim the colon.
trimws(trimws(string, "left", "\\w"), "left", ":")
## [1] "E001" "E002" "E003"
The input string
is assumed to be:
string <- c("G1:E001", "G2:E002", "G3:E003")
You want to use regexp_substr()
for this. This should work for your example:
select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t
Here, by the way, is the SQL Fiddle.
Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace()
for the first part:
select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t
And here is this corresponding SQL Fiddle.
Ctrl + N : Open class.
Alt + F7 : Find usages.
I think this is what you are looking for:
df.drop('Region', axis=1).apply(lambda x: x.mean(), axis=1)
Something important when dealing with outliers is that one should try to use estimators as robust as possible. The mean of a distribution will be biased by outliers but e.g. the median will be much less.
Building on eumiro's answer:
def reject_outliers(data, m = 2.):
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d/mdev if mdev else 0.
return data[s<m]
Here I have replace the mean with the more robust median and the standard deviation with the median absolute distance to the median. I then scaled the distances by their (again) median value so that m
is on a reasonable relative scale.
Note that for the data[s<m]
syntax to work, data
must be a numpy array.
You can get a reference to the constructor function which created the object by using the constructor property:
function MyObject(){
}
var obj = new MyObject();
obj.constructor; // MyObject
If you need to confirm the type of an object at runtime you can use the instanceof operator:
obj instanceof MyObject // true
To change the text;
multipleLine.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
MainActivity.myArray.set(pickId,String.valueOf(s));
MainActivity.myAdapt.notifyDataSetChanged();
}
@Override
public void afterTextChanged(Editable s) {
}
I wanted to replace only a part of the url, and with this solution, I don't have to pass the whole url, just the dynamic part:
public interface APIService {
@GET("users/{user_id}/playlists")
Call<List<Playlist> getUserPlaylists(@Path(value = "user_id", encoded = true) String userId);
}
This is coming a bit late, but here's a solution I use to vertical align elements within a parent div.
This is useful for when you know the size of the container div, but not that of the contained image. (this is frequently the case when working with lightboxes or image carousels).
Here's the styling you should try:
container div
{
display:table-cell;
vertical-align:middle;
height:200px;
width:200px;
}
img
{
/*Apply any styling here*/
}
Synchronize OS X environment variables for command line and GUI applications from a single source with osx-env-sync.
I also posted an answer to a related question here.
It seems to me, that it is by design that this file is empty.
A similar question has been asked here: https://stackoverflow.com/questions/2567432/ubuntu-apache-httpd-conf-or-apache2-conf
So, you should have a look for /etc/apache2/apache2.conf
I received the same error in pushing files to my private bitbucket repository. For some odd reasons, the request couldn't be sent and an empty reply was the result! I tried again with a proxy tunnel (you can use any other VPN applications) and it has been solved till now.
I was using Android Pie and nothing seemed to worked so I played around with app:tabTextAppearance attribute. I know its not the perfect answer but might help someone.
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabTextAppearance="@style/TextAppearance.AppCompat.Caption" />
UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)
For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:
https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
All these loops! How about some functional goodness :) May run in to tail call issues on old/current js engines, solved in ES6
function isPalendrome(str){
var valid = false;
if(str.length < 2 ) return true;
function even(i,ii){
str[i]===str[ii] ? ((i+1 !== ii) ? even(i+1,ii-1) : valid = true) : null
}
function odd(i, ii){
str[i]===str[ii] ? ((i !== ii) ? odd(i+1,ii-1) : valid = true) : null
}
if(str.length % 2){
return odd(0,str.length-1),valid;
}else{
return even(0,str.length-1),valid;
}
}
To test your call stack run this code, you will be able to parse strings double the call stack size
function checkStackSize(){
var runs = 70000;
var max_process = 1;
var max = 0;
function recurse_me() {
max_process++;
if(max_process === runs) return;
max = max_process;
try {
recurse_me()
} catch(e) {
max = max_process;
}
}
recurse_me()
console.log(max);
}
Due to the symmetrical nature of the problem you could chunk the string from the outside in and process the chunks that are within call stack limits.
by that I mean if the palindromes length is 1000. You could join 0-250 and 750-1000 and join 250-499 with 500-749. You can then pass each chunk in to the function. The advantage to this is you could run the process in parallel using web workers or threads for very large data sets.
You can create a batch file with .bat
extension with the following contents
Use java
for .jar
that does not have UI and is a command line application
@ECHO OFF
start java -jar <your_jar_file_name>.jar
Use javaw
for .jar
that has a UI
@ECHO OFF
start javaw -jar <your_jar_file_name>.jar
Please make sure your JAVA_HOME
is set in the environment variables.
I wasn't using Azure, but I got the same error locally. Using <customErrors mode="Off" />
seemed to have no effect, but checking the Application logs in Event Viewer revealed a warning from ASP.NET which contained all the detail I needed to resolve the issue.
as header
AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)
curl \
--header "Content-Type: application/json" \
--header "Authorization: Basic $AUTH" \
--request POST \
--data '{"key1":"value1", "key2":"value2"}' \
https://example.com/
not sure if this is what you wanted but
var arr = ["A", "B", "C"];
var arrString = arr.join(", ");
This results in the following output:
A, B, C
You can get the maximum like this:
>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
A B
0 1 -2
1 2 8
2 3 1
>>> df[["A", "B"]]
A B
0 1 -2
1 2 8
2 3 1
>>> df[["A", "B"]].max(axis=1)
0 1
1 8
2 3
and so:
>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
If you know that "A" and "B" are the only columns, you could even get away with
>>> df["C"] = df.max(axis=1)
And you could use .apply(max, axis=1)
too, I guess.
Whether or not you install opencv3 manually or from Gohlke's whl package, I found the need to create/edit the file cv.py in site_packages as follows to make compatable with old code:
import cv2 as cv
$oblast = Oblast::all();
$category = Category::where('slug', $catName)->first();
$availableProjects = $category->availableProjects;
return view('pages.business-area')->with(array('category'=>$category, 'availableProjects'=>$availableProjects, 'oblast'=>$oblast));
by using jquery to register .mousemove to document to change the image .css left and top to event.pageX and event.pageY.
example as below http://jsfiddle.net/BfLAh/1/
$(document).mousemove(function(e) {
$("#follow").css({
left: e.pageX,
top: e.pageY
});
});
_x000D_
#follow {
position: absolute;
text-align: center;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="follow"><img src="https://placekitten.com/96/140" /><br>Kitteh</br>
</div>
_x000D_
updated to follow slowly
for the orientation , you need to get the current css left and css top and compare with event.pageX and event.pageY , then set the image orientation with
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
for the speed , you can set the jquery .animation duration to certain amount.
re.sub
is definitely what you are looking for. And so you know, you don't need the anchors and the wildcards.
re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)
will do the same thing--matching the first substring that looks like "interfaceOpDataFile" and replacing it.
If you're looking to use the standard construct of element = element1 || element2 where JavaScript will return the first one that is truthy, you could do exactly that:
element = $('#someParentElement .somethingToBeFound') || $('#someParentElement .somethingElseToBeFound');
which would return the first element that is actually found. But a better way would probably be to use the jQuery selector comma construct (which returns an array of found elements) in this fashion:
element = $('#someParentElement').find('.somethingToBeFound, .somethingElseToBeFound')[0];
which will return the first found element.
I use that from time to time to find either an active element in a list or some default element if there is no active element. For example:
element = $('ul#someList').find('li.active, li:first')[0]
which will return any li with a class of active or, should there be none, will just return the last li.
Either will work. There are potential performance penalties, though, as the || will stop processing as soon as it finds something truthy whereas the array approach will try to find all elements even if it has found one already. Then again, using the || construct could potentially have performance issues if it has to go through several selectors before finding the one it will return, because it has to call the main jQuery object for each one (I really don't know if this is a performance hit or not, it just seems logical that it could be). In general, though, I use the array approach when the selector is a rather long string.
x & 1
is equivalent to x % 2
.
x >> 1
is equivalent to x / 2
So, these things are basically the result and remainder of divide by two.
Hi you should try the string split method:
i = "Hello world"
output = i.split()
j = 'is not enough'
print 'The', output[1], j
Ran into the problem today, none of the existing answers helped me. Assume you want to deduplicate your table named your_table
.
Step 1: Create a new table with deduped values
If borrowed this code from somewhere else on StackOverflow but can't seem to find it again. It works fine against PostgreSQL. It creates a table your_table_deduped
where (col1, col2)
are unique.
CREATE TABLE your_table_deduped AS
SELECT * FROM your_table WHERE ctid NOT IN
(SELECT ctid FROM
(SELECT ctid, ROW_NUMBER() OVER
(PARTITION BY col1, col2 ORDER BY ctid) AS rnum
FROM your_table) t
WHERE t.rnum > 1);
Step 2: Replace your first table with the deduped copy
We only delete the values in this step, because it allows us to keep the indexes, constraints, etc. in your table.
DELETE FROM your_table;
INSERT INTO your_table
SELECT * FROM your_table_deduped;
Step 3: Delete the deduped copy
DROP TABLE site_daily_kpis_dedup;
And voila, you have deduplicated your table!
I just posted this on Disable Submit button until Input fields filled in. Works for me.
Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.
http://www.w3schools.com/jsref/event_form_onsubmit.asp
<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
...
</form>
function validateCreditCardForm(){
var result = false;
if (($('#billing-cc-exp').val().length > 0) &&
($('#billing-cvv').val().length > 0) &&
($('#billing-cc-number').val().length > 0)) {
result = true;
}
return result;
}
My problems solved by remove all the runtime part
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
This isn't exactly a notification but in the title you say monitor and this can fit that scenario.
Using the SQL Server timestamp column can allow you to easily see any changes (that still persist) between queries.
The SQL Server timestamp column type is badly named in my opinion as it is not related to time at all, it's a database wide value that auto increments on any insert or update. You can select Max(timestamp) in a table you are after or return the timestamp from the row you just inserted then just select where timestamp > storedTimestamp, this will give you all the results that have been updated or inserted between those times.
As it's a database wide value too you can use your stored timestamp to check any table has had data written to it since you last checked/updated your stored timestamp.
git pull --rebase
may hide a history rewriting from a collaborator git push --force
. I recommend to use git pull --rebase
only if you know you forgot to push your commits before someone else does the same.
If you did not commit anything, but your working space is not clean, just git stash
before to git pull
. This way you won't silently rewrite your history (which could silently drop some of your work).
If you want to pull a particular file from another branch just do
git checkout branch1 -- filenamefoo.txt
This will pull a version of the file from one branch into the current tree
You can use Environment.Exit(0)
and Application.Exit
.
Environment.Exit()
: terminates this process and gives the underlying operating system the specified exit code.
You can do it in two different ways.
Option 1: The -eq
operator
>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False
Option 2: The .Equals()
method of the string
object. Because strings in PowerShell are .Net System.String
objects, any method of that object can be called directly.
>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method
List of System.String
methods follows.
Thowable
catches really everything even ThreadDeath which gets thrown by default to stop a thread from the now deprecated Thread.stop()
method. So by catching Throwable
you can be sure that you'll never leave the try block without at least going through your catch block, but you should be prepared to also handle OutOfMemoryError
and InternalError
or StackOverflowError
.
Catching Throwable
is most useful for outer server loops that delegate all sorts of requests to outside code but may itself never terminate to keep the service alive.
As shown here, the second argument to substr
is the length, not the ending position:
string substr ( size_t pos = 0, size_t n = npos ) const;
Generate substring
Returns a string object with its contents initialized to a substring of the current object. This substring is the character sequence that starts at character position
pos
and has a length ofn
characters.
Your line b = a.substr(i,i+1);
will generate, for values of i
:
substr(0,1) = 1
substr(1,2) = 23
substr(2,3) = 345
substr(3,4) = 45 (since your string stops there).
What you need is b = a.substr(i,2);
You should also be aware that your output will look funny for a number like 12045. You'll get 12 20 4 45
due to the fact that you're using atoi()
on the string section and outputting that integer. You might want to try just outputing the string itself which will be two characters long:
b = a.substr(i,2);
cout << b << " ";
In fact, the entire thing could be more simply written as:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string a;
cin >> a;
for (int i = 0; i < a.size() - 1; i++)
cout << a.substr(i,2) << " ";
cout << endl;
return 0;
}
If you intend to change A, B, C.... you see high above the columns, you can not. You can hide A, B, C...: Button Office(top left) Excel Options(bottom) Advanced(left) Right looking: Display options fot this worksheet: Select the worksheet(eg. Sheet3) Uncheck: Show column and row headers Ok
dt.Rows[1].ItemArray
gives you a copy of item arrays. When you modify it, you're not modifying the original.
You can simply do this:
dt.Rows[1][3] = "Value";
ItemArray property is used when you want to modify all row values.
ex.:
dt.Rows[1].ItemArray = newItemArray;
To trim a string down so it does not contain two or more spaces in a row. Every instance of 2 or more space will be trimmed down to 1 space. A simple solution:
While ImageText1.Contains(" ") '2 spaces.
ImageText1 = ImageText1.Replace(" ", " ") 'Replace with 1 space.
End While
when you are dealing with popups window.opener plays an important role, because we have to deal with fields of parent page as well as child page, when we have to use values on parent page we can use window.opener or we want some data on the child window or popup window at the time of loading then again we can set the values using window.opener
input[type=text] {
width: 150px;
length: 150px;
}
input[name=myname] {
width: 100px;
length: 150px;
}
_x000D_
<input type="text">
<br>
<input type="text" name="myname">
_x000D_
A nice online tool: yUML
It happens cause of multiple reasons but the answer missing above there's the "className" while extending your controller.
Make sure your class name is the same as your controller name is your controllers. e.g., If your controller name is Settings.php, you must extend the controller like.
class Settings extends CI_Controller
{
// some actions like...
public function __construct(){
// and so and so...
}
}
Solution : SpreadsheetApp.getActiveSheet().getRange('F2').setValue('hello')
Explanation :
Setting value in a cell in spreadsheet to which script is attached
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);
Setting value in a cell in sheet which is open currently and to which script is attached
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(RANGE).setValue(VALUE);
Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet name known)
SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);
Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet position known)
SpreadsheetApp.openById(SHEET_ID).getSheets()[POSITION].getRange(RANGE).setValue(VALUE);
These are constants, you must define them yourself
SHEET_ID
SHEET_NAME
POSITION
VALUE
RANGE
By script attached to a sheet I mean that script is residing in the script editor of that sheet. Not attached means not residing in the script editor of that sheet. It can be in any other place.
<!DOCTYPE html>
<html>
<head>
<script>
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("demo").innerHTML = clicks;
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
</html>
This should work for you :) Yes var should be used
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
Here is an example on Python 3.x
, much simpler than 2.x
:
import smtplib
from email.message import EmailMessage
def send_mail(to_email, subject, message, server='smtp.example.cn',
from_email='[email protected]'):
# import smtplib
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = ', '.join(to_email)
msg.set_content(message)
print(msg)
server = smtplib.SMTP(server)
server.set_debuglevel(1)
server.login(from_email, 'password') # user & password
server.send_message(msg)
server.quit()
print('successfully sent the mail.')
call this function:
send_mail(to_email=['[email protected]', '[email protected]'],
subject='hello', message='Your analysis has done!')
If you use 126/163, ????, you need to set"???????", like below:
ref: https://stackoverflow.com/a/41470149/2803344 https://docs.python.org/3/library/email.examples.html#email-examples
Try using the float
package and then the [H]
option for your figure.
\usepackage{float}
...
\begin{figure}[H]
\centering
\includegraphics{fig1}
\caption{Write some caption here}\label{fig1}
\end{figure}
as already suggested by this insightful answer!
https://tex.stackexchange.com/questions/8625/force-figure-placement-in-text
List foreign key ( NOTE that its different from index name )
SHOW CREATE TABLE <Table Name>
The result will show you the foreign key name.
Format:
CONSTRAINT `FOREIGN_KEY_NAME` FOREIGN KEY (`FOREIGN_KEY_COLUMN`) REFERENCES `FOREIGN_KEY_TABLE` (`id`),
Drop (Foreign/primary/key) Key
ALTER TABLE <Table Name> DROP FOREIGN KEY <Foreign key name>
Drop the index.
It can be done via https and oauth or ssh.
https and oauth: create an access token that has "repo" scope and then use this syntax:
"package-name": "git+https://<github_token>:[email protected]/<user>/<repo>.git"
or
ssh: setup ssh and then use this syntax:
"package-name": "git+ssh://[email protected]:<user>/<repo>.git"
(note the use of colon instead of slash before user)
Alternatively you can use img2pdf to convert images to pdf. Install it on Debian or Ubuntu with:
sudo apt install img2pdf
Convert one or more images to pdf:
img2pdf img.jpg -o output.pdf
It uses a different mechanism than imagemagick to embed the image into the pdf. When possible Img2pdf embeds the image directly into the pdf, without decoding and recoding the image.
Since C++11 it can be done inside a class with constexpr
.
class stat {
public:
// init inside class
static constexpr double inlineStaticVar = 22;
};
The variable can now be accessed with:
stat::inlineStaticVar
Using <pre>
HTML code and pretty_generate
is good trick:
<%
require 'json'
hash = JSON[{hey: "test", num: [{one: 1, two: 2, threes: [{three: 3, tthree: 33}]}]}.to_json]
%>
<pre>
<%= JSON.pretty_generate(hash) %>
</pre>
Alternativly if your using bootstrap then you can just add align-middle
to vertical align the element.
<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">Continue
<i class="icon-ok align-middle" style="font-size:40px;"></i>
</button>
How can I programatically (C#) ZIP a file (in Windows) without using any third party libraries?
If using the 4.5+ Framework, there is now the ZipArchive and ZipFile classes.
using (ZipArchive zip = ZipFile.Open("test.zip", ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(@"c:\something.txt", "data/path/something.txt");
}
You need to add references to:
For .NET Core targeting net46, you need to add dependencies for
Example project.json:
"dependencies": {
"System.IO.Compression": "4.1.0",
"System.IO.Compression.ZipFile": "4.0.1"
},
"frameworks": {
"net46": {}
}
For .NET Core 2.0, just adding a simple using statement is all that is needed:
Here is how the default implementation (ASP.NET Framework or ASP.NET Core) works. It uses a Key Derivation Function with random salt to produce the hash. The salt is included as part of the output of the KDF. Thus, each time you "hash" the same password you will get different hashes. To verify the hash the output is split back to the salt and the rest, and the KDF is run again on the password with the specified salt. If the result matches to the rest of the initial output the hash is verified.
Hashing:
public static string HashPassword(string password)
{
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(0x20);
}
byte[] dst = new byte[0x31];
Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
return Convert.ToBase64String(dst);
}
Verifying:
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] buffer4;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != 0x31) || (src[0] != 0))
{
return false;
}
byte[] dst = new byte[0x10];
Buffer.BlockCopy(src, 1, dst, 0, 0x10);
byte[] buffer3 = new byte[0x20];
Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
{
buffer4 = bytes.GetBytes(0x20);
}
return ByteArraysEqual(buffer3, buffer4);
}
Exceute the program by pressing SHIFT+F6, instead of clicking the RUN button on the window. This might be silly, bt the error main class not found is not occurring, the project is executing well...
Note that the '=' is optional in C++11 universal initialization syntax, and it is generally considered better style to write :
char myarray[ARRAY_SIZE] {0}
In Ghost4J library (http://ghost4j.sourceforge.net), since version 0.4.0 you can use a SimpleRenderer to do the job with few lines of code:
Load PDF or PS file (use PSDocument class for that):
PDFDocument document = new PDFDocument();
document.load(new File("input.pdf"));
Create the renderer
SimpleRenderer renderer = new SimpleRenderer();
// set resolution (in DPI)
renderer.setResolution(300);
Render
List<Image> images = renderer.render(document);
Then you can do what you want with your image objects, for example, you can write them as PNG like this:
for (int i = 0; i < images.size(); i++) {
ImageIO.write((RenderedImage) images.get(i), "png", new File((i + 1) + ".png"));
}
Note: Ghost4J uses the native Ghostscript C API so you need to have a Ghostscript installed on your box.
I hope it will help you :)
First you should know, how much memory is allocated when you define and allocate memory in below case.
typedef struct person{
char firstName[100], surName[51]
} PERSON;
PERSON *testPerson = (PERSON*) malloc(sizeof(PERSON));
1) The sizeof(PERSON) now returns 151 bytes (Doesn't include padding)
2) The memory of 151 bytes is allocated in heap.
3) To free, call free(testPerson).
but If you declare your structure as
typedef struct person{
char *firstName, *surName;
} PERSON;
PERSON *testPerson = (PERSON*) malloc(sizeof(PERSON));
then
1) The sizeof(PERSON) now returns 8 bytes (Doesn't include padding)
2) Need to allocate memory for firstName and surName by calling malloc() or calloc(). like
testPerson->firstName = (char *)malloc(100);
3) To free, first free the members in the struct than free the struct. i.e, free(testPerson->firstName); free(testPerson->surName); free(testPerson);
As others have said, some email programs will not read the css styles. If you already have a web email written up you can use the following tool from zurb to inline all of your styles:
http://zurb.com/ink/inliner.php
This comes in extremely handy when using templates like those mentioned above from mailchimp, campaign monitor, etc. as they, as you have found, will not work in some email programs. This tool leaves your style section for the mail programs that will read it and puts all the styles inline to get more universal readability in the format that you wanted.
In my case, setting httpErrors
and the like in Web.config did not help to identify the issue.
Instead I did:
I then saw an entry with a detailed exception information. In my case it was
\?\C:\Websites\example.com\www\web.config ( 592) :Cannot add duplicate collection entry of type 'mimeMap' with unique key attribute 'fileExtension' set to '.json'
I now was able to resolve it and fix the error. After that I deactivated "Failed Request Tracing" again.
they resize automatically with your text and are colored the same color. Plug and play :)
jsBin demo playground
body{
font-size: 25px; /* Change font and see the magic! */
color: #f07; /* Change color and see the magic! */
}
/* RESPONSIVE ARROWS */
[class^=arr-]{
border: solid currentColor;
border-width: 0 .2em .2em 0;
display: inline-block;
padding: .20em;
}
.arr-right {transform:rotate(-45deg);}
.arr-left {transform:rotate(135deg);}
.arr-up {transform:rotate(-135deg);}
.arr-down {transform:rotate(45deg);}
_x000D_
This is <i class="arr-right"></i> .arr-right<br>
This is <i class="arr-left"></i> .arr-left<br>
This is <i class="arr-up"></i> .arr-up<br>
This is <i class="arr-down"></i> .arr-down
_x000D_
$( 'input[name="testGroup"]:radio' ).on('change', function(e) {_x000D_
console.log(e.type);_x000D_
return false;_x000D_
});
_x000D_
This syntax is a little more flexible to handle events. Not only can you observe "changes", but also other types of events can be controlled here too by using one single event handler. You can do this by passing the list of events as arguments to the first parameter. See jQuery On
Secondly, .change() is a shortcut for .on( "change", handler ). See here. I prefer using .on() rather than .change because I have more control over the events.
Lastly, I'm simply showing an alternative syntax to attach the event to the element.
The command on OSX should be exactly the same as it is Unix under the pretty UI.