$_SERVER['HTTP_REFERER']
is the answer
I was having alot of trouble with this because I was using:
if($.cookie('token') === null || $.cookie('token') === "")
{
//no cookie
}
else
{
//have cookie
}
The above was ALWAYS returning false, no matter what I did in terms of setting the cookie or not. From my tests it seems that the object is therefore undefined before it's set so adding the following to my code fixed it.
if($.cookie('token') === null || $.cookie('token') === ""
|| $.(cookie('token') === "null" || $.cookie('token') === undefined)
{
//no cookie
}
else
{
//have cookie
}
The difference lies in the fact that ./gradlew
indicates you are using a gradle wrapper. The wrapper is generally part of a project and it facilitates installation of gradle. If you were using gradle without the wrapper you would have to manually install it - for example, on a mac brew install gradle
and then invoke gradle using the gradle
command. In both cases you are using gradle, but the former is more convenient and ensures version consistency across different machines.
Each Wrapper is tied to a specific version of Gradle, so when you first run one of the commands above for a given Gradle version, it will download the corresponding Gradle distribution and use it to execute the build.
Not only does this mean that you don’t have to manually install Gradle yourself, but you are also sure to use the version of Gradle that the build is designed for. This makes your historical builds more reliable
Read more here - https://docs.gradle.org/current/userguide/gradle_wrapper.html
Also, Udacity has a neat, high level video explaining the concept of the gradle wrapper - https://www.youtube.com/watch?v=1aA949H-shk
For OGG on Windows: Theoraconverter
You should convert them to number before compare.
Try:
if (+x > +y) {
//...
}
or
if (Number(x) > Number(y)) {
// ...
}
Note: parseFloat
and pareseInt
(for compare integer, and you need to specify the radix) will give you NaN
for an empty string, compare with NaN
will always be false
, If you don't want to treat empty string be 0
, then you could use them.
CHAR :
VARCHAR :
any comments......!!!!
Swift 4 & Swift 5:
You need to add target for that button.
myButton.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)
And of course you need to set tag of that button since you are using it.
myButton.tag = indexPath.row
You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.
To get the tag in the connected function:
@objc func connected(sender: UIButton){
let buttonTag = sender.tag
}
You can use the Content property on pretty much all visual WPF controls to access the stuff inside them. There's a heirarchy of classes that the controls belong to, and any descendants of ContentControl will work in this way.
phihag's answer puts each row in a single cell, while you are asking for each value to be in a separate cell. This seems to do it:
<?php
// Create a table from a csv file
echo "<html><body><table>\n\n";
$f = fopen("so-csv.csv", "r");
while (($line = fgetcsv($f)) !== false) {
$row = $line[0]; // We need to get the actual row (it is the first element in a 1-element array)
$cells = explode(";",$row);
echo "<tr>";
foreach ($cells as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
?>
Add header:
#include<math.h>
Note: use abs(), sometimes at the time of evaluation sqrt() can take negative values which leave to domain error.
abs()- provides absolute values;
example, abs(-3) =3
Include -lm at the end of your command during compilation time:
gcc <filename.extension> -lm
As to formulas being "updated" in the new row, since all the copying occurs after the shift, the old row (now one index up from the new row) has already had its formula shifted, so copying it to the new row will make the new row reference the old rows cells. A solution would be to parse out the formulas BEFORE the shift, then apply those (a simple String array would do the job. I'm sure you can code that in a few lines).
At start of function:
ArrayList<String> fArray = new ArrayList<String>();
Row origRow = sheet.getRow(sourceRow);
for (int i = 0; i < origRow.getLastCellNum(); i++) {
if (origRow.getCell(i) != null && origRow.getCell(i).getCellType() == Cell.CELL_TYPE_FORMULA)
fArray.add(origRow.getCell(i).getCellFormula());
else fArray.add(null);
}
Then when applying the formula to a cell:
newCell.setCellFormula(fArray.get(i));
ROUTER LINK DIRECTIVE:
[routerLink]="link" //when u pass URL value from COMPONENT file
[routerLink]="['link','parameter']" //when you want to pass some parameters along with route
routerLink="link" //when you directly pass some URL
[routerLink]="['link']" //when you directly pass some URL
Use the method defined below to write data to the CSV file.
open('outputFile.csv', 'a',newline='')
Just add an additional newline=''
parameter inside the open
method :
def writePhoneSpecsToCSV():
rowData=["field1", "field2"]
with open('outputFile.csv', 'a',newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(rowData)
This will write CSV rows without creating additional rows!
Nothing.
$('#content').click(function(e) {
alert(1);
});
Will bind to an existing HTML element with the ID set to content
, and will show a message box on click.
#content
exists before using that codejQuery has some issues loading binary data using AJAX requests, as it does not yet implement some HTML5 XHR v2 capabilities, see this enhancement request and this discussion
Given that, you have one of two solutions:
First solution, abandon JQuery and use XMLHTTPRequest
Go with the native HTMLHTTPRequest, here is the code to do what you need
var req = new XMLHttpRequest();
req.open("GET", "/file.pdf", true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
};
req.send();
Second solution, use the jquery-ajax-native plugin
The plugin can be found here and can be used to the XHR V2 capabilities missing in JQuery, here is a sample code how to use it
$.ajax({
dataType: 'native',
url: "/file.pdf",
xhrFields: {
responseType: 'blob'
},
success: function(blob){
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
}
});
You can find an easy guide here
The step are 2: - Copy the icon in the correct folder/folders - Change the AndroidManifest.xml
Using python string formatting.
>>> "%0.2f" % 3
'3.00'
DECLARE @table1 TABLE (
idx int identity(1,1),
col1 int )
DECLARE @counter int
SET @counter = 1
WHILE(@counter < SELECT MAX(idx) FROM @table1)
BEGIN
DECLARE @colVar INT
SELECT @colVar = col1 FROM @table1 WHERE idx = @counter
-- Do your work here
SET @counter = @counter + 1
END
Believe it or not, this is actually more efficient and performant than using a cursor.
Open Terminal (or iTerm) install Homebrew then run brew install live-server
and run live-server.
You also can install Python 3 and run python3 -m http.server PORT
.
If you have VS Code installed open it and install extension liveserver, then click Go Live in the bottom right corner.
Alternatively you can install WSL2 and follow the macOS steps via apt (sudo apt-get
).
Open your favorite terminal emulator and follow the macOS steps via apt (sudo apt-get
).
C:\> wmic cpu get loadpercentage
LoadPercentage
0
Or
C:\> @for /f "skip=1" %p in ('wmic cpu get loadpercentage') do @echo %p%
4%
For some reason you don't use jQuery nor ES6? This might help you:
var values = "Test,Prof,Off";_x000D_
var splitValues = values.split(',');_x000D_
var multi = document.getElementById('strings');_x000D_
_x000D_
multi.value = null; // Reset pre-selected options (just in case)_x000D_
var multiLen = multi.options.length;_x000D_
for (var i = 0; i < multiLen; i++) {_x000D_
if (splitValues.indexOf(multi.options[i].value) >= 0) {_x000D_
multi.options[i].selected = true;_x000D_
}_x000D_
}
_x000D_
<select name='strings' id="strings" multiple style="width:100px;">_x000D_
<option value="Test">Test</option>_x000D_
<option value="Prof">Prof</option>_x000D_
<option value="Live">Live</option>_x000D_
<option value="Off">Off</option>_x000D_
<option value="On" selected>On</option>_x000D_
</select>
_x000D_
For generate Model , controller with resources and migration best command is:
php artisan make:model ModelName -m -cr
Nothing built in, my solution would be as follows :
function tConvert (time) {
// Check correct time format and split into components
time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
if (time.length > 1) { // If time format correct
time = time.slice (1); // Remove full string match value
time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
time[0] = +time[0] % 12 || 12; // Adjust hours
}
return time.join (''); // return adjusted time or original string
}
tConvert ('18:00:00');
This function uses a regular expression to validate the time string and to split it into its component parts. Note also that the seconds in the time may optionally be omitted. If a valid time was presented, it is adjusted by adding the AM/PM indication and adjusting the hours.
The return value is the adjusted time if a valid time was presented or the original string.
Working example
(function() {_x000D_
_x000D_
function tConvert(time) {_x000D_
// Check correct time format and split into components_x000D_
time = time.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];_x000D_
_x000D_
if (time.length > 1) { // If time format correct_x000D_
time = time.slice(1); // Remove full string match value_x000D_
time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM_x000D_
time[0] = +time[0] % 12 || 12; // Adjust hours_x000D_
}_x000D_
return time.join(''); // return adjusted time or original string_x000D_
}_x000D_
_x000D_
var tel = document.getElementById('tests');_x000D_
_x000D_
tel.innerHTML = tel.innerHTML.split(/\r*\n|\n\r*|\r/).map(function(v) {_x000D_
return v ? v + ' => "' + tConvert(v.trim()) + '"' : v;_x000D_
}).join('\n');_x000D_
})();
_x000D_
<h3>tConvert tests : </h3>_x000D_
<pre id="tests">_x000D_
18:00:00_x000D_
18:00_x000D_
00:00_x000D_
11:59:01_x000D_
12:00:00_x000D_
13:01:57_x000D_
24:00_x000D_
sdfsdf_x000D_
12:61:54_x000D_
</pre>
_x000D_
Shift Pageup/End works for me.
Please try this way.
<table border="1">
<tr>
<th scope="col">Header</th>
<th scope="col">Header</th>
<th colspan="2">Header</th>
</tr>
<tr>
<td scope="row"> </td>
<td scope="row"> </td>
<td scope="col">Split this one</td>
<td scope="col">into two columns</td>
</tr>
</table>
&&
is new in C++11, and it signifies that the function accepts an RValue-Reference -- that is, a reference to an argument that is about to be destroyed.
I would achieve it in a one-liner as shown below:
using System;
using System.Collections;
namespace stackoverflowQuestions
{
class Program
{
static void Main(string[] args)
{
//get bit Array for number 20
var myBitArray = new BitArray(BitConverter.GetBytes(20));
}
}
}
Please note that every element of a BitArray
is stored as bool as shown in below snapshot:
So below code works:
if (myBitArray[0] == false)
{
//this code block will execute
}
but below code doesn't compile at all:
if (myBitArray[0] == 0)
{
//some code
}
You would think this common problem would be taken care of by Hibernate. But its not! There are a few "hacks" to get it right.
The one I use is to store the Date as a Long in the database. So I am always working with milliseconds after 1/1/70. I then have getters and setters on my Class that return/accept only Dates. So the API remains the same. The down side is that I have longs in the database. SO with SQL I can pretty much only do <,>,= comparisons -- not fancy date operators.
Another approach is to user a custom mapping type as described here: http://www.hibernate.org/100.html
I think the correct way to deal with this is to use a Calendar instead of a Date though. With the Calendar you can set the TimeZone before persisting.
NOTE: Silly stackoverflow won't let me comment, so here is a response to david a.
If you create this object in Chicago:
new Date(0);
Hibernate persists it as "12/31/1969 18:00:00". Dates should be devoid of timezone, so I'm not sure why the adjustment would be made.
Using a collection initializer
From C# 3, you can use collection initializers to construct a List and populate it using a single expression. The following example constructs a Human and its ContactNumbers:
var human = new Human(1, "Address", "Name") {
ContactNumbers = new List<ContactNumber>() {
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
}
}
Specializing the Human
constructor
You can change the constructor of the Human
class to provide a way to populate the ContactNumbers
property:
public class Human
{
public Human(int id, string address, string name, IEnumerable<ContactNumber> contactNumbers) : this(id, address, name)
{
ContactNumbers = new List<ContactNumber>(contactNumbers);
}
public Human(int id, string address, string name, params ContactNumber[] contactNumbers) : this(id, address, name)
{
ContactNumbers = new List<ContactNumber>(contactNumbers);
}
}
// Using the first constructor:
List<ContactNumber> numbers = List<ContactNumber>() {
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
};
var human = new Human(1, "Address", "Name", numbers);
// Using the second constructor:
var human = new Human(1, "Address", "Name",
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
);
Bottom line
Which alternative is a best practice? Or at least a good practice? You judge it! IMO, the best practice is to write the program as clearly as possible to anyone who has to read it. Using the collection initializer is a winner for me, in this case. With much less code, it can do almost the same things as the alternatives -- at least, the alternatives I gave...
UPDATE:
This answer is incomplete and gives misleading results. For example, null
is also considered of type object
in JavaScript, not to mention several other edge cases. Follow the recommendation below and move on to other "most upvoted (and correct!) answer":
typeof yourVariable === 'object' && yourVariable !== null
Original answer:
Try using typeof(var)
and/or var instanceof something
.
EDIT: This answer gives an idea of how to examine variable's properties, but it is not a bulletproof recipe (after all there's no recipe at all!) for checking whether it's an object, far from it. Since people tend to look for something to copy from here without doing any research, I'd highly recommend that they turn to the other, most upvoted (and correct!) answer.
\ef <function_name>
in psql. It will give the whole function with editable text.
I had the same issue on Windows, Docker 18.06.1-ce-win73 (19507)
.
Removing and re-adding the shared drive via the Docker settings panel and everything worked again.
What worked for me immediately was:
I located bin folder (picture below shows).
moved all dll in other folder for safety.
then rebuild ed the project.
after solved the issue, deleted old dll files.
Inspired by the code above :D
def money_format(value):
value = str(value).split('.')
money = ''
count = 1
for digit in value[0][::-1]:
if count != 3:
money += digit
count += 1
else:
money += f'{digit},'
count = 1
if len(value) == 1:
money = ('$' + money[::-1]).replace('$-','-$')
else:
money = ('$' + money[::-1] + '.' + value[1]).replace('$-','-$')
return money
Maybe this example listed here can help you out. Statement from the author
about 24 lines of code to encrypt, 23 to decrypt
Due to the fact that the link in the original posting is dead - here the needed code parts (c&p without any change to the original source)
/*
Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
#region Usings
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
#endregion
namespace Utilities.Encryption
{
/// <summary>
/// Utility class that handles encryption
/// </summary>
public static class AESEncryption
{
#region Static Functions
/// <summary>
/// Encrypts a string
/// </summary>
/// <param name="PlainText">Text to be encrypted</param>
/// <param name="Password">Password to encrypt with</param>
/// <param name="Salt">Salt to encrypt with</param>
/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
/// <param name="PasswordIterations">Number of iterations to do</param>
/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
/// <param name="KeySize">Can be 128, 192, or 256</param>
/// <returns>An encrypted string</returns>
public static string Encrypt(string PlainText, string Password,
string Salt = "Kosher", string HashAlgorithm = "SHA1",
int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
int KeySize = 256)
{
if (string.IsNullOrEmpty(PlainText))
return "";
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
byte[] CipherTextBytes = null;
using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
{
using (MemoryStream MemStream = new MemoryStream())
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
{
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
CryptoStream.FlushFinalBlock();
CipherTextBytes = MemStream.ToArray();
MemStream.Close();
CryptoStream.Close();
}
}
}
SymmetricKey.Clear();
return Convert.ToBase64String(CipherTextBytes);
}
/// <summary>
/// Decrypts a string
/// </summary>
/// <param name="CipherText">Text to be decrypted</param>
/// <param name="Password">Password to decrypt with</param>
/// <param name="Salt">Salt to decrypt with</param>
/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
/// <param name="PasswordIterations">Number of iterations to do</param>
/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
/// <param name="KeySize">Can be 128, 192, or 256</param>
/// <returns>A decrypted string</returns>
public static string Decrypt(string CipherText, string Password,
string Salt = "Kosher", string HashAlgorithm = "SHA1",
int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
int KeySize = 256)
{
if (string.IsNullOrEmpty(CipherText))
return "";
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
int ByteCount = 0;
using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
{
using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
{
ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
MemStream.Close();
CryptoStream.Close();
}
}
}
SymmetricKey.Clear();
return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
}
#endregion
}
}
Try using the TimeRange object in C# to complete your goal.
TimeRange timeRange = new TimeRange();
timeRange = TimeRange.Parse("13:00-14:00");
bool IsNowInTheRange = timeRange.IsIn(DateTime.Now.TimeOfDay);
Console.Write(IsNowInTheRange);
java.io.DataInput.readUTF()
and java.io.DataOutput.writeUTF(String)
say that a String
object is represented by two bytes of length information and the modified UTF-8 representation of every character in the string. This concludes that the length of String is limited by the number of bytes of the modified UTF-8 representation of the string when used with DataInput
and DataOutput
.
In addition, The specification of CONSTANT_Utf8_info
found in the Java virtual machine specification defines the structure as follows.
CONSTANT_Utf8_info {
u1 tag;
u2 length;
u1 bytes[length];
}
You can find that the size of 'length' is two bytes.
That the return type of a certain method (e.g. String.length()
) is int
does not always mean that its allowed maximum value is Integer.MAX_VALUE
. Instead, in most cases, int
is chosen just for performance reasons. The Java language specification says that integers whose size is smaller than that of int
are converted to int
before calculation (if my memory serves me correctly) and it is one reason to choose int
when there is no special reason.
The maximum length at compilation time is at most 65536. Note again that the length is the number of bytes of the modified UTF-8 representation, not the number of characters in a String
object.
String
objects may be able to have much more characters at runtime. However, if you want to use String
objects with DataInput
and DataOutput
interfaces, it is better to avoid using too long String
objects. I found this limitation when I implemented Objective-C equivalents of DataInput.readUTF()
and DataOutput.writeUTF(String)
.
What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}
) and then use this to get the parent directory and cd
to it at the beginning of the script.
#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
cd "$parent_path"
cat ../some.text
This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh
inside dir
.
Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)
Did you try df.groupby('id').head(2)
Ouput generated:
>>> df.groupby('id').head(2)
id value
id
1 0 1 1
1 1 2
2 3 2 1
4 2 2
3 7 3 1
4 8 4 1
(Keep in mind that you might need to order/sort before, depending on your data)
EDIT: As mentioned by the questioner, use df.groupby('id').head(2).reset_index(drop=True)
to remove the multindex and flatten the results.
>>> df.groupby('id').head(2).reset_index(drop=True)
id value
0 1 1
1 1 2
2 2 1
3 2 2
4 3 1
5 4 1
Make sure you really need to invert the matrix. This is often unnecessary and can be numerically unstable. When most people ask how to invert a matrix, they really want to know how to solve Ax = b where A is a matrix and x and b are vectors. It's more efficient and more accurate to use code that solves the equation Ax = b for x directly than to calculate A inverse then multiply the inverse by B. Even if you need to solve Ax = b for many b values, it's not a good idea to invert A. If you have to solve the system for multiple b values, save the Cholesky factorization of A, but don't invert it.
NOTE: the answer that says to use the ZZ
command doesn't work for me on my Mavericks system, but this is probably due to something in my vim configuration because if I start with a pristine .vimrc
, the accepted answer works. My answer might work for you if the other solution doesn't.
On MacOS X, according to the crontab manpage, the crontab temporary file that gets created with crontab -e
needs to be edited in-place. Vim doesn't edit in-place by default (but it might do some special case to support crontab -e
), so if your $EDITOR
environment variable is set to vi
(the default) or vim
, editing the crontab will always fail.
To get Vim to edit the file in-place, you need to do:
:setlocal nowritebackup
That should enable you to update the crontab when you do crontab -e
with the :wq
or ZZ
commands.
You can add an autocommand in your .vimrc to make this automatically work when editing crontabs:
autocmd FileType crontab setlocal nowritebackup
Another way is to add the setlocal nowritebackup
to ~/.vim/after/ftplugin/crontab.vim
, which will be loaded by Vim automatically when you're editing a crontab file if you have the Filetype plugin enabled. You can also check for the OS if you're using your vim files across multiple platforms:
""In ~/.vim/after/ftplugin/crontab.vim
if has("mac")
setlocal nowritebackup
endif
You should add the target="_blank"
and rel="noopener noreferrer"
in the anchor tag.
For example:
<a target="_blank" rel="noopener noreferrer" href="http://your_url_here.html">Link</a>
Adding rel="noopener noreferrer"
is not mandatory, but it's a recommended security measure. More information can be found in the links below.
Source:
There is another error with the forwars=d slash.
if we get this : def get_x(r): return path/'train'/r['fname']
is the same as def get_x(r): return path + 'train' + r['fname']
If you change your inc() function to this
public static Integer inc(Integer i) {
Integer iParam = i;
i = i+1; // I think that this must be **sneakally** creating a new integer...
System.out.println(i == iParam);
return i;
}
then you will see that it always prints "false". That means that the addition creates a new instance of Integer and stores it in the local variable i ("local", because i is actually a copy of the reference that was passed), leaving the variable of the calling method untouched.
Integer is an immutable class, meaning that you cannot change it's value but must obtain a new instance. In this case you don't have to do it manually like this:
i = new Integer(i+1); //actually, you would use Integer.valueOf(i.intValue()+1);
instead, it is done by autoboxing.
The advantage to a single CSS file is transfer efficiency. Each HTTP request means a HTTP header response for each file requested, and that takes bandwidth.
I serve my CSS as a PHP file with the "text/css" mime type in the HTTP header. This way I can have multiple CSS files on the server side and use PHP includes to push them into a single file when requested by the user. Every modern browser receives the .php file with the CSS code and processes it as a .css file.
Spring boot doc 'was' wrong (they have since fixed it) :
To switch it off you can set error.whitelabel.enabled=false
should be
To switch it off you can set server.error.whitelabel.enabled=false
It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.
The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:
You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:
Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:
#toolbar=0&navpanes=0
So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.
string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);
You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.
int *array = new int[n];
It declares a pointer to a dynamic array of type int
and size n
.
A little more detailed answer: new
allocates memory of size equal to sizeof(int) * n
bytes and return the memory which is stored by the variable array
. Also, since the memory is dynamically allocated using new
, you've to deallocate it manually by writing (when you don't need anymore, of course):
delete []array;
Otherwise, your program will leak memory of at least sizeof(int) * n
bytes (possibly more, depending on the allocation strategy used by the implementation).
Instead of "w"
use "a"
(append) mode with open
function:
with open("games.txt", "a") as text_file:
Thank you. I use passing in an object as a parameter. My Android code is below
String oPerson= null;
if (CheckAddress("5556", oPerson))
{
Toast.makeText(this,
"It's Match! " + oPerson,
Toast.LENGTH_LONG).show();
}
private boolean CheckAddress(String iAddress, String oPerson)
{
Cursor cAddress = mDbHelper.getAllContacts();
String address = "";
if (cAddress.getCount() > 0) {
cAddress.moveToFirst();
while (cAddress.isAfterLast() == false) {
address = cAddress.getString(2).toString();
oPerson = cAddress.getString(1).toString();
if(iAddress.indexOf(address) != -1)
{
Toast.makeText(this,
"Person : " + oPerson,
Toast.LENGTH_LONG).show();
System.out.println(oPerson);
cAddress.close();
return true;
}
else cAddress.moveToNext();
}
}
cAddress.close();
return false;
}
The result is
Person : John
It's Match! null
Actually, "It's Match! John"
Please check my mistake.
There is a package that converts it for you and returns the svg as a string to implement into your reactJS file.
With Angular 7, I got it working by using the following without using HttpParams.
import { HttpClient } from '@angular/common/http';
export class ApiClass {
constructor(private httpClient: HttpClient) {
// use it like this in other services / components etc.
this.getDataFromServer().
then(res => {
console.log('res: ', res);
});
}
getDataFromServer() {
const params = {
param1: value1,
param2: value2
}
const url = 'https://api.example.com/list'
// { params: params } is the same as { params }
// look for es6 object literal to read more
return this.httpClient.get(url, { params }).toPromise();
}
}
The above were really close. Here's my solution:
Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
Dim i As Integer
outClone = inClone.Clone
Dim dv As DataView = inClone.Tables(0).DefaultView
dv.RowFilter = matchStr
Dim dt As New DataTable
dt = dv.ToTable
For i = 0 To dv.Count - 1
outClone.Tables(0).ImportRow(dv.Item(i).Row)
Next
End Sub
Other alternative:
JAXBElement<String> element = new JAXBElement<>(new QName("Your localPart"),
String.class, "Your message");
Then:
System.out.println(element.getValue()); // Result: Your message
Just to add that tmux
scroll buffer does not clear with clear
, reset
or printf
. You need to :clear-history
. See link.
The best way to do that is Html without substring your text and fully dynamique For example :
public static String getTextSize(String text,int size) {
return "<span style=\"size:"+size+"\" >"+text+"</span>";
}
and you can use color attribut etc... if the other hand :
size.setText(Html.fromHtml(getTextSize(ls.numProducts,100) + " " + mContext.getString(R.string.products));
Prepared Statements are the best solution, but if you really need to do it manually you could also use the StringEscapeUtils
class from the Apache Commons-Lang library. It has an escapeSql(String)
method, which you can use:
import org.apache.commons.lang.StringEscapeUtils;
…
String escapedSQL = StringEscapeUtils.escapeSql(unescapedSQL);
If your goal is output your array to a string for debbuging: you can use the print_r() function, which receives an expression parameter (your array), and an optional boolean return parameter. Normally the function is used to echo the array, but if you set the return parameter as true, it will return the array impression.
Example:
//We create a 2-dimension Array as an example
$ProductsArray = array();
$row_array['Qty'] = 20;
$row_array['Product'] = "Cars";
array_push($ProductsArray,$row_array);
$row_array2['Qty'] = 30;
$row_array2['Product'] = "Wheels";
array_push($ProductsArray,$row_array2);
//We save the Array impression into a variable using the print_r function
$ArrayString = print_r($ProductsArray, 1);
//You can echo the string
echo $ArrayString;
//or Log the string into a Log file
$date = date("Y-m-d H:i:s", time());
$LogFile = "Log.txt";
$fh = fopen($LogFile, 'a') or die("can't open file");
$stringData = "--".$date."\n".$ArrayString."\n";
fwrite($fh, $stringData);
fclose($fh);
This will be the output:
Array
(
[0] => Array
(
[Qty] => 20
[Product] => Cars
)
[1] => Array
(
[Qty] => 30
[Product] => Wheels
)
)
Try this:
SELECT ProductId, Name, Tags
FROM Product
WHERE '1,2,3,' LIKE '%' + CAST(ProductId AS VARCHAR(20)) + ',%';
As said on the last example of this link
There is a solution to this if you really need a static access to the current context. In Startup.Configure(….)
app.Use(async (httpContext, next) =>
{
CallContext.LogicalSetData("CurrentContextKey", httpContext);
try
{
await next();
}
finally
{
CallContext.FreeNamedDataSlot("CurrentContextKey");
}
});
And when you need it you can get it with :
HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;
I hope that helps. Keep in mind this workaround is when you don’t have a choice. The best practice is to use de dependency injection.
mvn clean package -DpropEnv=PROD
Then using like this in POM.xml
<properties>
<myproperty>${propEnv}</myproperty>
</properties>
If you are using Boost 1.65 or higher, you can use boost::stacktrace:
#include <boost/stacktrace.hpp>
// ... somewhere inside the bar(int) function that is called recursively:
std::cout << boost::stacktrace::stacktrace();
Here's a general example with obvious delimiters (X
and Y
):
(?<=X)(.*?)(?=Y)
Here it's used to find the string between X
and Y
. Rubular example here, or see image:
To test whether a file exists in .NET, you can use
System.IO.File.Exists (String)
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
You have to define your TASK_CAT
column first and then set foreign key on it.
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " ("
+ TASK_ID + " integer primary key autoincrement, "
+ TASK_TITLE + " text not null, "
+ TASK_NOTES + " text not null, "
+ TASK_DATE_TIME + " text not null,"
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+"("+CAT_ID+"));";
More information you can find on sqlite foreign keys doc.
One possible solution, if your situation allows it:
Create a new MyScript.ps1 that looks like:
.\TheRealMyScript.ps1 > output.txt
You mean like length
or size()
?
you can do this with css3, this blurs the whole element
div (or whatever element) {
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
Fiddle: http://jsfiddle.net/H4DU4/
// you can use this
List<Value> list = new ArrayList<Value>(map.values());
// or you may use
List<Value> list = new ArrayList<Value>();
for (Map.Entry<String, String> entry : map.entrySet())
{
list.add(entry.getValue());
}
<?php
echo date('d - m - Y',strtotime('2013-01-19 01:23:42'));
?>
Out put : 19 - 01 - 2013
If you provide 6 hex digits, that means RGB (2 hex digits for each value of red, green and blue).
If you provide 8 hex digits, it's an ARGB (2 hex digits for each value of alpha, red, green and blue respectively).
So by removing the final 55 you're changing from A=B4, R=55, G=55, B=55 (a mostly transparent grey), to R=B4, G=55, B=55 (a fully-non-transparent dusky pinky).
See the "Color" documentation for the supported formats.
I found some way to perform in on dictionary contain my custom class methods
foreach (var item in this.Values.Where(p => p.IsActive == false))
item.Refresh();
Where 'this' derived from : Dictionary<string, MyCustomClass>
class MyCustomClass
{
public void Refresh(){}
}
I like using extension methods for conversions like this, even if they just wrap standard library methods. In the case of hexadecimal conversions, I use the following hand-tuned (i.e., fast) algorithms:
public static string ToHex(this byte[] bytes)
{
char[] c = new char[bytes.Length * 2];
byte b;
for(int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx)
{
b = ((byte)(bytes[bx] >> 4));
c[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
b = ((byte)(bytes[bx] & 0x0F));
c[++cx]=(char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
}
return new string(c);
}
public static byte[] HexToBytes(this string str)
{
if (str.Length == 0 || str.Length % 2 != 0)
return new byte[0];
byte[] buffer = new byte[str.Length / 2];
char c;
for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
{
// Convert first half of byte
c = str[sx];
buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0')) << 4);
// Convert second half of byte
c = str[++sx];
buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0'));
}
return buffer;
}
It is not best practise to mix up content with style, but a solution could be
<div class="thumb" style="background-image: url('images/img.jpg')"></div>
Before starting, Make sure that USB DEBUGGING IS ENABLED in your phone settings !!!
1) BASIC STEP - Plug in device via USB, then go to device page in Android developers blog. There you can find necessary information regarding adding USB vendor ids. Add your device specific ids, and restart eclipse if needed.
2)If you were able to see the device connected(using command: 'adb devices'
) earlier, but not anymore, then just try restarting ADB. (you can use the commands: 'adb kill-server'
followed by 'adb start-server'
. adb commands need to be executed from platform tools folder in the Android SDK, if you havent exported it).
3)If neither of them works out and you are on windows machine, then check the installed usb drivers are correct. If not install proper drivers Please find more information on how to install/update drivers in http://developer.android.com/tools/extras/oem-usb.html
If this also is not working, try installing Universal ADB windows driver https://plus.google.com/103583939320326217147/posts/BQ5iYJEaaEH
4)You may also try increasing the timeout time Go to preferences-> android->DDMS in eclipse, then try increasing 'ADB connection timeout(ms)' value
Update based on newer answers:
5)Run > Run Configurations > Target. Please make sure, the option "Always prompt to pick device" is enabled.
Special case: Windows 8 and Nexus 10 (from this question: ADB No Devices Found)
Windows 8 wouldn't recognize my Nexus 10 device. Fixed by Setting the transfer mode to Camera (PTP) through the settings dialogue on the device.
Settings > Storage > Menu > USB Computer connection to "Camera (PTP)"
You can use Python 3.6's f-strings for variables inside multi-line or lengthy single-line strings. You can manually specify newline characters using \n
.
string1 = "go"
string2 = "now"
string3 = "great"
multiline_string = (f"I will {string1} there\n"
f"I will go {string2}.\n"
f"{string3}.")
print(multiline_string)
I will go there
I will go now
great
string1 = "go"
string2 = "now"
string3 = "great"
singleline_string = (f"I will {string1} there. "
f"I will go {string2}. "
f"{string3}.")
print(singleline_string)
I will go there. I will go now. great.
Alternatively, you can also create a multiline f-string with triple quotes.
multiline_string = f"""I will {string1} there.
I will go {string2}.
{string3}."""
The steps that worked for me (XCode 8.3.3/XCode 9 beta with a Swift 3.1 project
)
- Navigate to your project directory
- pod install //which then asks you to do the next step
- pod repo update //takes a while to update the repo
- pod update
- pod install
- Close Xcode session
- Open and Clean the project
- Build/Run
Also make sure you open the .xcworkspace file rather than the project file (.xcodeproj) when working with pods
. That should solve any errors with linking such as "Apple Mach -O Linker command failed"
Just simply add or die(mysqli_error($db));
at the end of your query, this will print the mysqli error.
mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));
As a side note I'd say you are at risk of mysql injection
, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.
1.Go to Windows-->Preferences-->Java-->Installed JREs-->Execution Environments
2.select the java version you are using currently in the "Execution Environments" box. So that in the "Compatible JREs" box, you are able to see as "jre1.8.0_102[perfect match]"(if your java version is 1.8). Then try to build using maven.
Since the answer above still leaves some people in the dark, here's what a complete webpack.config.js might look like:
var path = require('path');_x000D_
var config = {_x000D_
entry: path.resolve(__dirname, 'app/main.js'),_x000D_
output: {_x000D_
path: path.resolve(__dirname, 'build'),_x000D_
filename: 'bundle.js'_x000D_
},_x000D_
module: {_x000D_
loaders: [{_x000D_
test: /\.jsx?$/,_x000D_
loader: 'babel',_x000D_
query:_x000D_
{_x000D_
presets:['es2015', 'react']_x000D_
}_x000D_
}]_x000D_
},_x000D_
_x000D_
};_x000D_
_x000D_
module.exports = config;
_x000D_
You can try @Rule
annotation. Here is the example from the docs:
public static class UsesExternalResource {
Server myServer = new Server();
@Rule public ExternalResource resource = new ExternalResource() {
@Override
protected void before() throws Throwable {
myServer.connect();
};
@Override
protected void after() {
myServer.disconnect();
};
};
@Test public void testFoo() {
new Client().run(myServer);
}
}
You just need to create FileResource
class extending ExternalResource
.
Full Example
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
public class TestSomething
{
@Rule
public ResourceFile res = new ResourceFile("/res.txt");
@Test
public void test() throws Exception
{
assertTrue(res.getContent().length() > 0);
assertTrue(res.getFile().exists());
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import org.junit.rules.ExternalResource;
public class ResourceFile extends ExternalResource
{
String res;
File file = null;
InputStream stream;
public ResourceFile(String res)
{
this.res = res;
}
public File getFile() throws IOException
{
if (file == null)
{
createFile();
}
return file;
}
public InputStream getInputStream()
{
return stream;
}
public InputStream createInputStream()
{
return getClass().getResourceAsStream(res);
}
public String getContent() throws IOException
{
return getContent("utf-8");
}
public String getContent(String charSet) throws IOException
{
InputStreamReader reader = new InputStreamReader(createInputStream(),
Charset.forName(charSet));
char[] tmp = new char[4096];
StringBuilder b = new StringBuilder();
try
{
while (true)
{
int len = reader.read(tmp);
if (len < 0)
{
break;
}
b.append(tmp, 0, len);
}
reader.close();
}
finally
{
reader.close();
}
return b.toString();
}
@Override
protected void before() throws Throwable
{
super.before();
stream = getClass().getResourceAsStream(res);
}
@Override
protected void after()
{
try
{
stream.close();
}
catch (IOException e)
{
// ignore
}
if (file != null)
{
file.delete();
}
super.after();
}
private void createFile() throws IOException
{
file = new File(".",res);
InputStream stream = getClass().getResourceAsStream(res);
try
{
file.createNewFile();
FileOutputStream ostream = null;
try
{
ostream = new FileOutputStream(file);
byte[] buffer = new byte[4096];
while (true)
{
int len = stream.read(buffer);
if (len < 0)
{
break;
}
ostream.write(buffer, 0, len);
}
}
finally
{
if (ostream != null)
{
ostream.close();
}
}
}
finally
{
stream.close();
}
}
}
You can do joins as well using Hadley Wickham's awesome dplyr package.
library(dplyr)
#make sure that CustomerId cols are both type numeric
#they ARE not using the provided code in question and dplyr will complain
df1$CustomerId <- as.numeric(df1$CustomerId)
df2$CustomerId <- as.numeric(df2$CustomerId)
#inner
inner_join(df1, df2)
#left outer
left_join(df1, df2)
#right outer
right_join(df1, df2)
#alternate right outer
left_join(df2, df1)
#full join
full_join(df1, df2)
semi_join(df1, df2) #keep only observations in df1 that match in df2.
anti_join(df1, df2) #drops all observations in df1 that match in df2.
I also had this same problem.
Solution work for me:
CREATE TABLE IF NOT EXISTS `users` ( `sr_no` int(11) NOT NULL AUTO_INCREMENT, `username` VARCHAR(50) NOT NULL, `password` VARCHAR(50) NOT NULL, `dir` VARCHAR(100) NOT NULL, PRIMARY KEY (`sr_no`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
I paste this code in SQL and run, it works fine.
I've just run into this problem and solved it.
The source of the problem is that you have both XmlAccessType.FIELD and pairs of getters and setters. The solution is to remove setters and add a default constructor and a constructor that takes all fields.
You can enter the following formula in the cell where you want to see the Overdue
or Not due
result:
=IF(ISBLANK(O10),"",IF(O10<TODAY(),"Overdue","Not due"))
This formula first tests if the source cell is blank. If it is, then the result cell will be filled with the empty string. If the source is not blank, then the formula tests if the date in the source cell is before the current day. If it is, then the value is set to Overdue
, otherwise it is set to Not due
.
What about something like this?
var arr = [];
$('[id^=event]', response).each(function(){
arr.push($(this).html());
});
The [attr^=selector]
selector matches elements on which the attr
attribute starts with the given string, that way you don't care about the numbers after "event".
Using Guava
List<Object> lst ...
List<String> ls = Lists.transform(lst, Functions.toStringFunction());
You can easily achieve this with the use of jQuery .toggle().
$("#btnDisplay").click(function() {
$("#div1").toggle();
$("#div2").toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
First Div
</div>
<div id="div2" style="display: none;">
Second Div
</div>
<button id="btnDisplay">Display</button>
This method is easy and powerful.
Value is a date and "DD-MM-YYYY" is the mask of the date.
moment().diff(moment(value, "DD-MM-YYYY"), 'years');
In my case, after some refactoring in EF6, my tests were failing with the same error message as the original poster but my solution had nothing to do with the DateTime fields.
I was just missing a required field when creating the entity. Once I added the missing field, the error went away. My entity does have two DateTime? fields but they weren't the problem.
.so
files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.
.a
files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar
command -- a predecessor of tar
that's now just used for making libraries) of the original .o object files.
.la
files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?
Static and dynamic libraries each have pros and cons.
Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.
Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.
Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.
Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.
Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.
Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.
Dynamic libraries are especially useful for system libraries, like libc
. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.
I figured out an elegant, Rails-like way to do it. First, rename your .scss
file to .scss.erb
, then use syntax like this (example for highlight_js-rails4 gem CSS asset):
@import "<%= asset_path("highlight_js/github") %>";
Why you can't host the file directly via SCSS:
Doing an @import
in SCSS works fine for CSS files as long as you explicitly use the full path one way or another. In development mode, rails s
serves assets without compiling them, so a path like this works...
@import "highlight_js/github.css";
...because the hosted path is literally /assets/highlight_js/github.css
. If you right-click on the page and "view source", then click on the link for the stylesheet with the above @import
, you'll see a line in there that looks like:
@import url(highlight_js/github.css);
The SCSS engine translates "highlight_js/github.css"
to url(highlight_js/github.css)
. This will work swimmingly until you decide to try running it in production where assets are precompiled have a hash injected into the file name. The SCSS file will still resolve to a static /assets/highlight_js/github.css
that was not precompiled and doesn't exist in production.
How this solution works:
Firstly, by moving the .scss
file to .scss.erb
, we have effectively turned the SCSS into a template for Rails. Now, whenever we use <%= ... %>
template tags, the Rails template processor will replace these snippets with the output of the code (just like any other template).
Stating asset_path("highlight_js/github")
in the .scss.erb
file does two things:
rake assets:precompile
task to precompile the appropriate CSS file.This also means that the SCSS engine isn't even parsing the CSS file; it's just hosting a link to it! So there's no hokey monkey patches or gross workarounds. We're serving a CSS asset via SCSS as intended, and using a URL to said CSS asset as Rails intended. Sweet!
Javascript String objects have a split function, doesn't really need to be jQuery specific
var str = "nice.test"
var strs = str.split(".")
strs would be
["nice", "test"]
I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed
success: function(data) {
var items = JSON.parse(data)
}
Very simple. Just follow these procedure:
1. git status
2. git add {File_Name} //the file name you haven been changed
3. git status
4. git commit -m '{your_message}'
5. git push origin master
On Button click start the native video player
which will open in full screen
:
Intent intent = new Intent(Intent.ACTION_VIEW );
intent.setDataAndType(Uri.parse(path), "video/*");
startActivity(intent);
Seems like you don't have permission to the Python folder. Try sudo chown -R $USER /Library/Python/2.7
To JUST LET EMAIL APPS to resolve your intent you need to specify ACTION_SENDTO as Action and mailto as Data.
private void sendEmail(){
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:" + "[email protected]"));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "My email's subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "My email's body");
try {
startActivity(Intent.createChooser(emailIntent, "Send email using..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Activity.this, "No email clients installed.", Toast.LENGTH_SHORT).show();
}
}
I found maybe best solution for parallax effect which work on all devices.
Main thing is to set all sections with z-index greater than parallax section.
And parallax image element to set fixed with max width and height
body, html { margin: 0px; }_x000D_
section {_x000D_
position: relative; /* Important */_x000D_
z-index: 1; /* Important */_x000D_
width: 100%;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
section.blue { background-color: blue; }_x000D_
section.red { background-color: red; }_x000D_
_x000D_
section.parallax {_x000D_
z-index: 0; /* Important */_x000D_
}_x000D_
_x000D_
section.parallax .image {_x000D_
position: fixed; /* Important */_x000D_
top: 0; /* Important */_x000D_
left: 0; /* Important */_x000D_
width: 100%; /* Important */_x000D_
height: 100%; /* Important */_x000D_
background-image: url(https://www.w3schools.com/css/img_fjords.jpg);_x000D_
background-repeat: no-repeat;_x000D_
background-position: center;_x000D_
-webkit-background-size: cover;_x000D_
-moz-background-size: cover;_x000D_
-o-background-size: cover;_x000D_
background-size: cover;_x000D_
}
_x000D_
<section class="blue"></section>_x000D_
<section class="parallax">_x000D_
<div class="image"></div>_x000D_
</section>_x000D_
<section class="red"></section>
_x000D_
You simply need to upgrade your Tomcat version, to Tomcat 8.0.xx. Java8 <-> Tomcat8
This is the configuration that I have been using and it has always worked out well
This worked for me:
(I don't have enough rep to embed pictures yet -- sorry about this.)
I went into Project --> Properties --> Linker --> System.
IMG: Located here, as of Dec 2019 Visual Studio for Windows
My platform was set to Active(Win32) with the Subsystem as "Windows". I was making a console app, so I set it to "Console".
IMG: Changing "Windows" --> "Console"
Then, I switched my platform to "x64".
Declare your dim as a variant, and pull the data as you would from an array. i.e.
Dim y As Variant
y = Range("A1:B2")
Now your excel range is all 1 variable (array), y
To pull the data, call the array position in the range "A1:B2" or whatever you choose. e.g.:
Msgbox y(1, 1)
This will return the top left box in the "A1:B2" range.
No need for the specificity .navbar-default
in your CSS. Background color requires background-color:#cc333333
(or just background:#cc3333
). Finally, probably best to consolidate all your customizations into a single class, as below:
.navbar-custom {
color: #FFFFFF;
background-color: #CC3333;
}
..
<div id="menu" class="navbar navbar-default navbar-custom">
Example: http://www.bootply.com/OusJAAvFqR#
No, it is not okay to put a link
element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):
“This element defines a link. Unlike
A
, it may only appear in theHEAD
section of a document, although it may appear any number of times.”
List<User> findByUsernameContainingIgnoreCase(String username);
in order to ignore case issues
@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.
.box {_x000D_
width: 500px;_x000D_
height: 100px;_x000D_
border: solid 5px #000;_x000D_
border-color: transparent transparent #000 transparent;_x000D_
border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
hashMaps
can't have duplicate keys. That said, you can create a map with list values:
Map<Integer, List<String>>
However, using this approach will have performance implications.
In the img tag set crossorigin to Anonymous.
<img crossorigin="anonymous"></img>
When using the attribute to restrict the maximum input length for text from a form on a webpage, the StringLength seems to generate the maxlength html attribute (at least in my test with MVC 5). The one to choose then depnds on how you want to alert the user that this is the maximum text length. With the stringlength attribute, the user will simply not be able to type beyond the allowed length. The maxlength attribute doesn't add this html attribute, instead it generates data validation attributes, meaning the user can type beyond the indicated length and that preventing longer input depends on the validation in javascript when he moves to the next field or clicks submit (or if javascript is disabled, server side validation). In this case the user can be notified of the restriction by an error message.
Filestash is the perfect tool for that:
Also Filestash is open source. (Disclaimer: I am the author)
From the spring docs
Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.
The <context-param>
:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
You can then use the WebApplicationContext to get a handle on your beans.
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");
See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
#include <windows.h>
Syntax:
Sleep ( __in DWORD dwMilliseconds );
Usage:
Sleep (1000); //Sleeps for 1000 ms or 1 sec
sysexits.h has a list of standard exit codes. It seems to date back to at least 1993 and some big projects like Postfix use it, so I imagine it's the way to go.
From the OpenBSD man page:
According to style(9), it is not good practice to call exit(3) with arbi- trary values to indicate a failure condition when ending a program. In- stead, the pre-defined exit codes from sysexits should be used, so the caller of the process can get a rough estimation about the failure class without looking up the source code.
The simplest solution is:
scaleFontSize: 0
see the chart.js Document
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])
#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)
#legend
cbar = plt.colorbar(heatmap)
cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)
# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()
#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()
You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.
It seems that the setBackground() method doesn't work well on some platforms (I'm using Windows 7). I found this answer to this question helpful. However, I didn't entirely use it to solve my problem. Instead, I decided it'd be much easier and almost as aesthetic to color a panel next to the button.
Time 30 minutes later
$newTime = date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s")." +30 minutes"))
Simplest way I know:
$('input[type="checkbox"]').prop("checked", true);
If you're using vectors to represent multi-dimensional behavior, there is a performance hit.
Do 2d+ vectors cause a performance hit?
The gist is that there's a small amount of overhead with each sub-vector having size information, and there will not necessarily be serialization of data (as there is with multi-dimensional c arrays). This lack of serialization can offer greater than micro optimization opportunities. If you're doing multi-dimensional arrays, it may be best to just extend std::vector and roll your own get/set/resize bits function.
I just tried some of the suggestions here and while I was able to use the browser back button, when I clicked on a menu selection the [Authorize] token for that [ActionResult] sent me right back to the login screen.
Here is my logout code:
FormsAuthentication.SignOut();
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
HttpCookie cookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
Although the back function on the browser took me back and displayed the secured menu (I am still working on that) I was not able to do anything that was secured in the app.
Hope this helps
If you have access to the delegate method you can do this:
[20] pry(main)> class Foo
[20] pry(main)* def self.bar
[20] pry(main)* "foo bar"
[20] pry(main)* end
[20] pry(main)* delegate :bar, to: 'self.class'
[20] pry(main)* end
=> [:bar]
[21] pry(main)> Foo.new.bar
=> "foo bar"
[22] pry(main)> Foo.bar
=> "foo bar"
Alternatively, and probably cleaner if you have more then a method or two you want to delegate to class & instance:
[1] pry(main)> class Foo
[1] pry(main)* module AvailableToClassAndInstance
[1] pry(main)* def bar
[1] pry(main)* "foo bar"
[1] pry(main)* end
[1] pry(main)* end
[1] pry(main)* include AvailableToClassAndInstance
[1] pry(main)* extend AvailableToClassAndInstance
[1] pry(main)* end
=> Foo
[2] pry(main)> Foo.new.bar
=> "foo bar"
[3] pry(main)> Foo.bar
=> "foo bar"
A word of caution:
Don't just randomly delegate
everything that doesn't change state to class and instance because you'll start running into strange name clash issues. Do this sparingly and only after you checked nothing else is squashed.
This is also possible with Notepad++:
Check Bookmark line (if there is no Mark tab update to the current version).
Enter your search term and click Mark All
Now go to the menu Search → Bookmark → Remove Bookmarked lines
Done.
I can't think of another way to compare values, but if you use the element of the set as the key, you can set the value to anything other than nil. Then you get fast lookups without having to search the entire table.
You have to resolve the conflict manually (copying the file over) and then commit the file (no matter if you copied it over or used the local version) like this
git commit -a -m "Fix merge conflict in test.foo"
Git normally autocommits after merging, but when it detects conflicts it cannot solve by itself, it applies all patches it figured out and leaves the rest for you to resolve and commit manually. The Git Merge Man Page, the Git-SVN Crash Course or this blog entry might shed some light on how it's supposed to work.
Edit: See the post below, you don't actually have to copy the files yourself, but can use
git checkout --ours -- path/to/file.txt
git checkout --theirs -- path/to/file.txt
to select the version of the file you want. Copying / editing the file will only be necessary if you want a mix of both versions.
Please mark mipadis answer as the correct one.
Try setting a Windows System Environment variable called _JAVA_OPTIONS
with the heap size you want. Java should be able to find it and act accordingly.
For (2), Guava provides exactly what you want as Int.asList(). There is an equivalent for each primitive type in the associated class, e.g., Booleans
for boolean
, etc.
int[] arr={1,2,3};
for(Integer i : Ints.asList(arr)) {
System.out.println(i);
}
CREATE PROCEDURE AddBrand
@BrandName nvarchar(50) = null,
@CategoryID int = null
AS
BEGIN
DECLARE @BrandID int = null
SELECT @BrandID = BrandID FROM tblBrand
WHERE BrandName = @BrandName
INSERT INTO tblBrandinCategory (CategoryID, BrandID)
VALUES (@CategoryID, @BrandID)
END
EXEC AddBrand @BrandName = 'BMW', @CategoryId = 1
The DataGrid has an XAML property IsReadOnly
that you can set to true
:
<my:DataGrid
IsReadOnly="True"
/>
You could do like this:
SELECT city FROM user WHERE (firstName, lastName) IN (('a', 'b'), ('c', 'd'));
String strOut = str.substring(0, 8) + "...";
Bdizzle,
I would recommend that you read this link
You will see that Newsletters can have different widths, There seems to be no major standard, What is recommended is that the width will be about 95% of the page width, as different browsers use the extra margins differently. You will also find that email readers have problems when reading css so applying the guide lines in this tutorial might help you save some time and trouble-shooting down the road.
Be happy, Julian
I don't know what your exact problem is, but if you're receiving XML and want to return JSON (or something) you could also look at JAX-B. This is a standard for marshalling/unmarshalling Java POJO's to XML and/or Json. There are multiple libraries that implement JAX-B, for example Apache's CXF.
You can simply make the top div fixed:
#top { position: fixed; top: 20px; left: 20px; }
Check this example how we could implement this.
public class HoverableDropdownTest {
private WebDriver driver;
private Actions action;
//Edit: there may have been a typo in the '- >' expression (I don't really want to add this comment but SO insist on ">6 chars edit"...
Consumer < By > hover = (By by) -> {
action.moveToElement(driver.findElement(by))
.perform();
};
@Test
public void hoverTest() {
driver.get("https://www.bootply.com/render/6FC76YQ4Nh");
hover.accept(By.linkText("Dropdown"));
hover.accept(By.linkText("Dropdown Link 5"));
hover.accept(By.linkText("Dropdown Submenu Link 5.4"));
hover.accept(By.linkText("Dropdown Submenu Link 5.4.1"));
}
@BeforeTest
public void setupDriver() {
driver = new FirefoxDriver();
action = new Actions(driver);
}
@AfterTest
public void teardownDriver() {
driver.quit();
}
}
For detailed answer, check here - http://www.testautomationguru.com/selenium-webdriver-automating-hoverable-multilevel-dropdowns/
' i modify the code for Datatable
For Each c as DataColumn in dt.Columns
For j=0 To _dataTable.Columns.Count-1
xlWorksheet.Cells (i+1, j+1) = _dataTable.Columns(j).ColumnName
Next
Next
Hope this could be help!
An update if somebody still reaches this page, wondering why the ie targeting doesnt work. IE 10 and onward no longer support conditional comments. From the MS official website:
Support for conditional comments has been removed in Internet Explorer 10 standards and quirks modes for improved interoperability and compliance with HTML5.
Please see here for more details: http://msdn.microsoft.com/en-us/library/ie/hh801214(v=vs.85).aspx
If you desperately need to target ie, you can use this jquery code to add a ie class to and then use .ie class in your css to target ie browsers.
if ($.browser.msie) {
$("html").addClass("ie");
}
Update: $.browser is not available after jQuery 1.9. If you upgrade to jQuery above 1.9 or you already use it, you can include jQuery migration script after jQuery so that it adds missing parts: jQuery Migrate Plugin
Alternatively, please check this thread for possible workarounds: browser.msie error after update to jQuery 1.9.1
This behaviour is terminal-specific and specified by the terminal emulator you use (e.g. xterm
) and the semantics of terminal that it provides. The terminal behaviour has been very stable for the last 20 years, and you can reasonably rely on the semantics of \b
.
This is a chained solution from all others, for example, when realpath
fails, either because it is not installed or because it exits with error code, then, the next solution is attempted until it get the path right.
#!/bin/bash
function getabsolutepath() {
local target;
local changedir;
local basedir;
local firstattempt;
target="${1}";
if [ "$target" == "." ];
then
printf "%s" "$(pwd)";
elif [ "$target" == ".." ];
then
printf "%s" "$(dirname "$(pwd)")";
else
changedir="$(dirname "${target}")" && basedir="$(basename "${target}")" && firstattempt="$(cd "${changedir}" && pwd)" && printf "%s/%s" "${firstattempt}" "${basedir}" && return 0;
firstattempt="$(readlink -f "${target}")" && printf "%s" "${firstattempt}" && return 0;
firstattempt="$(realpath "${target}")" && printf "%s" "${firstattempt}" && return 0;
# If everything fails... TRHOW PYTHON ON IT!!!
local fullpath;
local pythoninterpreter;
local pythonexecutables;
local pythonlocations;
pythoninterpreter="python";
declare -a pythonlocations=("/usr/bin" "/bin");
declare -a pythonexecutables=("python" "python2" "python3");
for path in "${pythonlocations[@]}";
do
for executable in "${pythonexecutables[@]}";
do
fullpath="${path}/${executable}";
if [[ -f "${fullpath}" ]];
then
# printf "Found ${fullpath}\\n";
pythoninterpreter="${fullpath}";
break;
fi;
done;
if [[ "${pythoninterpreter}" != "python" ]];
then
# printf "Breaking... ${pythoninterpreter}\\n"
break;
fi;
done;
firstattempt="$(${pythoninterpreter} -c "import os, sys; print( os.path.abspath( sys.argv[1] ) );" "${target}")" && printf "%s" "${firstattempt}" && return 0;
# printf "Error: Could not determine the absolute path!\\n";
return 1;
fi
}
printf "\\nResults:\\n%s\\nExit: %s\\n" "$(getabsolutepath "./asdfasdf/ asdfasdf")" "${?}"
You can try, (filtering with 1 object like a list or a set of values)
ds = ds.filter(functions.col(COL_NAME).isin(myList));
or as @Tony Fraser suggested, you can try, (with a Seq of objects)
ds = ds.filter(functions.col(COL_NAME).isin(mySeq));
All the answers are correct but most of them do not represent a good coding style. Also, you should always consider the variable length of arguments for the future, even though they are static at a certain point in time.
From the first Google hit for "PHP object to assoc array" we have this:
function object_to_array($data)
{
if (is_array($data) || is_object($data))
{
$result = array();
foreach ($data as $key => $value)
{
$result[$key] = object_to_array($value);
}
return $result;
}
return $data;
}
The source is at codesnippets.joyent.com.
The second method is preferred because of the encapsulation. You can certainly have the readonly field be public, but that goes against C# idioms in which you have data access occur through properties and not fields.
The reasoning behind this is that the property defines a public interface and if the backing implementation to that property changes, you don't end up breaking the rest of the code because the implementation is hidden behind an interface.
My main idea is creating a tempDiv above the view which we want to scroll to. It work well without lagging in my project.
scrollToView = (element, offset) => {
var rect = element.getBoundingClientRect();
var targetY = rect.y + window.scrollY - offset;
var tempDiv;
tempDiv = document.getElementById("tempDiv");
if (tempDiv) {
tempDiv.style.top = targetY + "px";
} else {
tempDiv = document.createElement('div');
tempDiv.id = "tempDiv";
tempDiv.style.background = "#F00";
tempDiv.style.width = "10px";
tempDiv.style.height = "10px";
tempDiv.style.position = "absolute";
tempDiv.style.top = targetY + "px";
document.body.appendChild(tempDiv);
}
tempDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
Example using
onContactUsClick = () => {
this.scrollToView(document.getElementById("contact-us"), 48);
}
Hope it help
Put the Text in a Center:
Container(
height: 45,
color: Colors.black,
child: Center(
child: Text(
'test',
style: TextStyle(color: Colors.white),
),
),
);
1) Dependency
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.8.8'
2) Annotation with date-time format.
public class RestObject {
private LocalDateTime timestamp;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public LocalDateTime getTimestamp() {
return timestamp;
}
}
3) Spring Config.
@Configuration
public class JacksonConfig {
@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
System.out.println("Config is starting.");
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
}
Or how about this?
with some_birthdays as
(
select date '1968-06-09' d from dual union all
select date '1970-06-10' from dual union all
select date '1972-06-11' from dual union all
select date '1974-12-11' from dual union all
select date '1976-09-17' from dual
)
select trunc(sysdate) today
, d birth_date
, floor(months_between(trunc(sysdate),d)/12) age
from some_birthdays;
Warning: this answer covers only ReactRouter versions before 1.0
I will update this answer with 1.0.0-rc1 use cases after!
You can do this without mixins too.
let Authentication = React.createClass({
contextTypes: {
router: React.PropTypes.func
},
handleClick(e) {
e.preventDefault();
this.context.router.transitionTo('/');
},
render(){
return (<div onClick={this.handleClick}>Click me!</div>);
}
});
The gotcha with contexts is that it is not accessible unless you define the contextTypes
on the class.
As for what is context, it is an object, like props, that are passed down from parent to child, but it is passed down implicitly, without having to redeclare props each time. See https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html
Bit counter-intuitive, but you must first setup a SDK for Java projects. On the bottom right of the IntelliJ welcome screen, select 'Configure > Project Defaults > Project Structure'.
The Project tab on the left will show that you have no SDK selected:
Therefore, you must click the 'New...' button on the right hand side of the dropdown and point it to your JDK. After that, you can go back to the import screen and it should be populated with your JAVA_HOME variable, providing you have this set.
On Windows 2008 R2 servers you have two means of viewing what files are open and closing those connections.
Via Share and Storage Management
Server Manager > Roles > File Services > Share and Storage Management > right-click on SaSM > Manage Open File
Via OpenFiles
CMD > Openfiles.exe /query /s SERVERNAME
See http://technet.microsoft.com/en-us/library/bb490961.aspx.
For MacOS chromedriver upgrade did the trick:
brew cask upgrade chromedriver
let suppose we create a table Transactions using SQl server management studio
txn_id int,
txn_type_id varchar(200),
Account_id int,
Amount int,
tDate date
);
with date datatype we can insert values in simple format: 'yyyy-mm-dd'
INSERT INTO transactions (txn_id,txn_type_id,Account_id,Amount,tDate)
VALUES (978, 'DBT', 103, 100, '2004-01-22');
Moreover we can have differet time formats like
DATE - format YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MI:SS
SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
This worked for me:
foreach (var item in FirmNameList){
if (FirmNames != "")
{
FirmNames += ",\r\n"
}
FirmNames += item;
}
Yes You can compile and execute without main method By using static block. But after static block executed (printed) you will get an error saying no main method found.
And Latest INFO --> YOU cant Do this with JAVA 7 version. IT will not execute.
{
static
{
System.out.println("Hello World!");
System.exit(0); // prevents “main method not found” error
}
}
But this will not execute with JAVA 7 version.
That selects the row number per country code, account, and currency. So, the rows with country code "US", account "XYZ" and currency "$USD" will each get a row number assigned from 1-n; the same goes for every other combination of those columns in the result set.
This query is kind of funny, because the order by clause does absolutely nothing. All the rows in each partition have the same country code, account, and currency, so there's no point ordering by those columns. The ultimate row numbers assigned in this particular query will therefore be unpredictable.
Hope that helps...
The problems with calling Thread.Sleep
are explained quite succinctly here:
Thread.Sleep
has its use: simulating lengthy operations while testing/debugging on an MTA thread. In .NET there's no other reason to use it.
Thread.Sleep(n)
means block the current thread for at least the number of timeslices (or thread quantums) that can occur withinn
milliseconds. The length of a timeslice is different on different versions/types of Windows and different processors and generally ranges from 15 to 30 milliseconds. This means the thread is almost guaranteed to block for more thann
milliseconds. The likelihood that your thread will re-awaken exactly aftern
milliseconds is about as impossible as impossible can be. So,Thread.Sleep
is pointless for timing.Threads are a limited resource, they take approximately 200,000 cycles to create and about 100,000 cycles to destroy. By default they reserve 1 megabyte of virtual memory for its stack and use 2,000-8,000 cycles for each context switch. This makes any waiting thread a huge waste.
The preferred solution: WaitHandles
The most-made-mistake is using Thread.Sleep
with a while-construct (demo and answer, nice blog-entry)
EDIT:
I would like to enhance my answer:
We have 2 different use-cases:
We are waiting because we know a specific timespan when we should continue (use
Thread.Sleep
,System.Threading.Timer
or alikes)We are waiting because some condition changes some time ... keyword(s) is/are some time! if the condition-check is in our code-domain, we should use WaitHandles - otherwise the external component should provide some kind of hooks ... if it doesn't its design is bad!
My answer mainly covers use-case 2
Save your dataset in CSV file and open that file and copy the dataset and paste to the excel file. and then crtl + g will work on your file, means the excel will recognize that blank is really blank.
You can use hex colors:
your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)
In your widget's Info.plist file, don't forget to set your AllowNetworkAccess
key to true.
The jQuery function getScript can also be used to ensure that a js file is indeed loaded every time the page is loaded.
This is how I did it:
$(document).ready(function(){
$.getScript("../data/playlist.js", function(data, textStatus, jqxhr){
startProgram();
});
});
Check the function at http://api.jquery.com/jQuery.getScript/
By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested.
You could use Linq's Aggregate function:
string s = "the\nquick\tbrown\rdog,jumped;over the lazy fox.";
char[] chars = new char[] { ' ', ';', ',', '\r', '\t', '\n' };
string snew = chars.Aggregate(s, (c1, c2) => c1.Replace(c2, '\n'));
Here's the extension method:
public static string ReplaceAll(this string seed, char[] chars, char replacementCharacter)
{
return chars.Aggregate(seed, (str, cItem) => str.Replace(cItem, replacementCharacter));
}
Extension method usage example:
string snew = s.ReplaceAll(chars, '\n');
There's a free trial for 100 minutes on https://browserling.com and you can test on Safari v7.0 during the trial period.
'SELECT * FROM Employ where number = ' + parseInt(val, 10) + ';'
For example, if val
is "10"
then this will end up building the string:
"SELECT * FROM Employ where number = 10;"
<input type="number" step="1" ...
By adding the step
attribute, you restrict input to integers.
Of course you should always validate on the server as well. Except under carefully controlled conditions, everything received from a client needs to be treated as suspect.
The following code works for me:
.half {
-moz-transform:scale(0.5);
-webkit-transform:scale(0.5);
transform:scale(0.5);
}
<img class="half" src="images/myimage.png">
The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object.class
.
Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.is_a?(ClassName)
to see if object
is of type ClassName
or derived from it.
Normally type checking is not done in Ruby, but instead objects are assessed based on their ability to respond to particular methods, commonly called "Duck typing". In other words, if it responds to the methods you want, there's no reason to be particular about the type.
For example, object.is_a?(String)
is too rigid since another class might implement methods that convert it into a string, or make it behave identically to how String behaves. object.respond_to?(:to_s)
would be a better way to test that the object in question does what you want.
I also needed this and wrote a function for parsing attributes, you can get it from here:
https://gist.github.com/4153580
(Note: It doesn't use regex)
Instead of using opacity, set a background-color with rgba, where 'a' is the level of transparency.
So instead of:
background-color: rgb(0,0,255); opacity: 0.5;
use
background-color: rgba(0,0,255,0.5);
One can also break the call of methods (obj.method()
) in multiple lines.
Enclose the command in parenthesis "()
" and span multiple lines:
> res = (some_object
.apply(args)
.filter()
.values)
For instance, I find it useful on chain calling Pandas/Holoviews objects methods.
Here is a very simple jade
file that have a loop in it. Jade is very sensitive about white space. After loop definition line (for
) you should give an indent(tab) to stuff that want to go inside the loop. You can do this without {}
:
- var arr=['one', 'two', 'three'];
- var s = 'string';
doctype html
html
head
body
section= s
- for (var i=0; i<3; i++)
div= arr[i]
I basically needed a fast way to find if a long needle is within a long haystack and they are very similar except for the last characters.
Here's the code I have written which for each function (splice, substring, startsWith, etc.) tests both when they return false and true against a haystack string (nestedString
) of 1.000.0001 characters and a falsy or truthy needle string of 1.000.000 chars (testParentStringFalse
and testParentStringTrue
, respectively):
// nestedString is made of 1.000.001 '1' repeated characters.
var nestedString = '...'
// testParentStringFalse is made of 1.000.000 characters,
// all characters are repeated '1', but the last one is '2',
// so for this string the test should return false.
var testParentStringFalse = '...'
// testParentStringTrue is made of 1.000.000 '1' repeated characters,
// so for this string the test should return true.
var testParentStringTrue = '...'
// You can make these very long strings by running the following bash command
// and edit each one as needed in your editor
// (NOTE: on OS X, `pbcopy` copies the string to the clipboard buffer,
// on Linux, you would probably need to replace it with `xclip`):
//
// printf '1%.0s' {1..1000000} | pbcopy
//
function testString() {
let dateStart
let dateEnd
let avg
let count = 100000
const falseResults = []
const trueResults = []
/* slice */
console.log('========> slice')
dateStart = +new Date()
var res
for (let j = 0; j < count; j++) {
res = nestedString.slice(0, testParentStringFalse.length) === testParentStringFalse
}
dateEnd = +new Date()
avg = (dateEnd - dateStart)/count
falseResults[falseResults.length] = {
label: 'slice',
avg
}
console.log(`testString() slice = false`, res, 'avg: ' + avg + 'ms')
dateStart = +new Date()
var res
for (let j = 0; j < count; j++) {
res = nestedString.slice(0, testParentStringTrue.length) === testParentStringTrue
}
dateEnd = +new Date()
avg = (dateEnd - dateStart)/count
trueResults[trueResults.length] = {
label: 'slice',
avg
}
console.log(`testString() slice = true`, res, 'avg: ' + avg + 'ms')
console.log('<======== slice')
console.log('')
/* slice END */
/* lastIndexOf */
console.log('========> lastIndexOf')
dateStart = +new Date()
var res
for (let j = 0; j < count; j++) {
res = nestedString.lastIndexOf(testParentStringFalse, 0) === 0
}
dateEnd = +new Date()
avg = (dateEnd - dateStart)/count
falseResults[falseResults.length] = {
label: 'lastIndexOf',
avg
}
console.log(`testString() lastIndexOf = false`, res, 'avg: ' + avg + 'ms')
dateStart = +new Date()
var res
for (let j = 0; j < count; j++) {
res = nestedString.lastIndexOf(testParentStringTrue, 0) === 0
}
dateEnd = +new Date()
avg = (dateEnd - dateStart)/count
trueResults[trueResults.length] = {
label: 'lastIndexOf',
avg
}
console.log(`testString() lastIndexOf = true`, res, 'avg: ' + avg + 'ms')
console.log('<======== lastIndexOf')
console.log('')
/* lastIndexOf END */
/* indexOf */
console.log('========> indexOf')
dateStart = +new Date()
var res
for (let j = 0; j < count; j++) {
res = nestedString.indexOf(testParentStringFalse) === 0
}
dateEnd = +new Date()
avg = (dateEnd - dateStart)/count
falseResults[falseResults.length] = {
label: 'indexOf',
avg
}
console.log(`testString() indexOf = false`, res, 'avg: ' + avg + 'ms')
dateStart = +new Date()
var res
for (let j = 0; j < count; j++) {
res = nestedString.indexOf(testParentStringTrue) === 0
}
dateEnd = +new Date()
avg = (dateEnd - dateStart)/count
trueResults[trueResults.length] = {
label: 'indexOf',
avg
}
console.log(`testString() indexOf = true`, res, 'avg: ' + avg + 'ms')
console.log('<======== indexOf')
console.log('')
/* indexOf END */
/* substring */
console.log('========> substring')
dateStart = +new Date()
var res
for (let j = 0; j < count; j++) {
res = nestedString.substring(0, testParentStringFalse.length) === testParentStringFalse
}
dateEnd = +new Date()
avg = (dateEnd - dateStart)/count
falseResults[falseResults.length] = {
label: 'substring',
avg
}
console.log(`testString() substring = false`, res, 'avg: ' + avg + 'ms')
dateStart = +new Date()
var res
for (let j = 0; j < count; j++) {
res = nestedString.substring(0, testParentStringTrue.length) === testParentStringTrue
}
dateEnd = +new Date()
avg = (dateEnd - dateStart)/count
trueResults[trueResults.length] = {
label: 'substring',
avg
}
console.log(`testString() substring = true`, res, 'avg: ' + avg + 'ms')
console.log('<======== substring')
console.log('')
/* substring END */
/* startsWith */
console.log('========> startsWith')
dateStart = +new Date()
var res
for (let j = 0; j < count; j++) {
res = nestedString.startsWith(testParentStringFalse)
}
dateEnd = +new Date()
avg = (dateEnd - dateStart)/count
falseResults[falseResults.length] = {
label: 'startsWith',
avg
}
console.log(`testString() startsWith = false`, res, 'avg: ' + avg + 'ms')
dateStart = +new Date()
var res
for (let j = 0; j < count; j++) {
res = nestedString.startsWith(testParentStringTrue)
}
dateEnd = +new Date()
avg = (dateEnd - dateStart)/count
trueResults[trueResults.length] = {
label: 'startsWith',
avg
}
console.log(`testString() startsWith = true`, res, 'avg: ' + avg + 'ms')
console.log('<======== startsWith')
console.log('')
/* startsWith END */
falseResults.sort((a, b) => a.avg - b.avg)
trueResults.sort((a, b) => a.avg - b.avg)
console.log('false results from fastest to slowest avg:', falseResults)
console.log('true results from fastest to slowest avg:', trueResults)
}
I runned this benchmark test on Chrome 75, Firefox 67, Safari 12 and Opera 62.
I haven't included Edge and IE because I do not have them on this machine, but if someone of you wants to run the script against Edge and at least IE 9 and share the output here I would be very curious to see the results.
Just remember that you need to recreate the 3 long strings and save the script in a file which you then open in your browser as copy/paste on the browser's console will block it as each string's length is >= 1.000.000).
Here are the outputs:
Chrome 75 (substring
wins):
false results from fastest to slowest avg:
1) {"label":"substring","avg":0.08271}
2) {"label":"slice","avg":0.08615}
3) {"label":"lastIndexOf","avg":0.77025}
4) {"label":"indexOf","avg":1.64375}
5) {"label":"startsWith","avg":3.5454}
true results from fastest to slowest avg:
1) {"label":"substring","avg":0.08213}
2) {"label":"slice","avg":0.08342}
3) {"label":"lastIndexOf","avg":0.7831}
4) {"label":"indexOf","avg":0.88988}
5) {"label":"startsWith","avg":3.55448}
Firefox 67 (indexOf
wins):
false results from fastest to slowest avg
1) {"label":"indexOf","avg":0.1807}
2) {"label":"startsWith","avg":0.74621}
3) {"label":"substring","avg":0.74898}
4) {"label":"slice","avg":0.78584}
5) {"label":"lastIndexOf","avg":0.79668}
true results from fastest to slowest avg:
1) {"label":"indexOf","avg":0.09528}
2) {"label":"substring","avg":0.75468}
3) {"label":"startsWith","avg":0.76717}
4) {"label":"slice","avg":0.77222}
5) {"label":"lastIndexOf","avg":0.80527}
Safari 12 (slice
wins for false results, startsWith
wins for true results, also Safari is the fastest in terms of total time to to execute the whole test):
false results from fastest to slowest avg:
1) "{\"label\":\"slice\",\"avg\":0.0362}"
2) "{\"label\":\"startsWith\",\"avg\":0.1141}"
3) "{\"label\":\"lastIndexOf\",\"avg\":0.11512}"
4) "{\"label\":\"substring\",\"avg\":0.14751}"
5) "{\"label\":\"indexOf\",\"avg\":0.23109}"
true results from fastest to slowest avg:
1) "{\"label\":\"startsWith\",\"avg\":0.11207}"
2) "{\"label\":\"lastIndexOf\",\"avg\":0.12196}"
3) "{\"label\":\"substring\",\"avg\":0.12495}"
4) "{\"label\":\"indexOf\",\"avg\":0.33667}"
5) "{\"label\":\"slice\",\"avg\":0.49923}"
Opera 62 (substring
wins. Results are similar to Chrome and I am not surprised as Opera is based on Chromium and Blink):
false results from fastest to slowest avg:
{"label":"substring","avg":0.09321}
{"label":"slice","avg":0.09463}
{"label":"lastIndexOf","avg":0.95347}
{"label":"indexOf","avg":1.6337}
{"label":"startsWith","avg":3.61454}
true results from fastest to slowest avg:
1) {"label":"substring","avg":0.08855}
2) {"label":"slice","avg":0.12227}
3) {"label":"indexOf","avg":0.79914}
4) {"label":"lastIndexOf","avg":1.05086}
5) {"label":"startsWith","avg":3.70808}
It turns out every browser has its own implementation details (apart Opera, which is based on Chrome's Chromium and Blink).
Of course, further test with different use cases could and should be performed (e.g. when needle is really short compared to haystack, when haystack is shorter than needle, etc...), but in my case I needed to compare very long strings and wanted to share it here.
Manifest.MF contains information about the files contained in the JAR file.
Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:
Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)
These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.
Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,
Main-Class: {fully qualified classname}
The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.
Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,
Class-Path: {jar1-name jar2-name directory-name/jar3-name}
This header can be used to specify the external JAR files on the same local network and not inside the current JAR.
Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:
Headers in a manifest
Header | Definition
-------------------------------------------------------------------
Name | The name of the specification.
Specification-Title | The title of the specification.
Specification-Version | The version of the specification.
Specification-Vendor | The vendor of the specification.
Implementation-Title | The title of the implementation.
Implementation-Version | The build number of the implementation.
Implementation-Vendor | The vendor of the implementation.
Package sealing related headers:
We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,
Name: {package/some-package/} Sealed:true
Here, the package name must end with ‘/’.
Enhancing security with manifest files:
We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.
META-INF folder:
This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.
Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
$(.surrounding_div_class).on( 'click', '.test', function () {
alert( 'WORKS!' );
});
Will only work if the DIV with the class .surrounding_div_class is the immediate parent to the object .test
If there is another object in the div that will be filled it wont work.
I'm sure Scott's solution worked at one point,
But it's a good argument for not using reflection to peek at private apis. It's broken now.
I was able to set out parameters using a delegate
delegate void MockOutDelegate(string s, out int value);
public void SomeMethod()
{
....
int value;
myMock.Setup(x => x.TryDoSomething(It.IsAny<string>(), out value))
.Callback(new MockOutDelegate((string s, out int output) => output = userId))
.Returns(true);
}
Use RVM (Ruby Version Manager) to install and manage any versions of Ruby. You can have multiple versions of Ruby installed on the machine and you can easily select the one you want.
To install RVM type into terminal:
\curl -sSL https://get.rvm.io | bash -s stable
And let it work. After that you will have RVM along with Ruby installed.
Source: RVM Site
You can also use Python! To get the number of physical cores:
$ python -c "import psutil; print(psutil.cpu_count(logical=False))"
4
To get the number of hyperthreaded cores:
$ python -c "import psutil; print(psutil.cpu_count(logical=True))"
8
For me using solution provided by codedom did not worked. Here we can only changed compatibility version of exiting database.
But actual problem lies that, internal database version which do not matches due to changes in there storage format.
Check out more details about SQL Server version and their internal db version & Db compatibility level here So it would be good if you create your database using SQL Server 2012 Express version or below. Or start using Visual Studio 2015 Preview.
$("#news_gallery li .over").click(function() {
article = $("#news-article .news-article");
});
Do you want to look for strings that include an escape character? For instance you want this:
select * from table where myfield like '%10%%'.
Where you want to search for all fields with 10%? If that is the case then you may use the ESCAPE clause to specify an escape character and escape the wildcard character.
select * from table where myfield like '%10!%%' ESCAPE '!'
Use the with statement.
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
I can't imply the code in first paragraph in this answer. Maybe the template language had deprecated the old format.
checkout: window.print() not working in IE
Working sample: http://jsfiddle.net/Q5Xc9/1/
Because like many have said here, references are not objects. they are simply aliases. True some compilers might implement them as pointers, but the standard does not force/specify that. And because references are not objects, you cannot point to them. Storing elements in an array means there is some kind of index address (i.e., pointing to elements at a certain index); and that is why you cannot have arrays of references, because you cannot point to them.
Use boost::reference_wrapper, or boost::tuple instead; or just pointers.
I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.
Function FileNameFromPath(strFullPath As String) As String
FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, "\"))
End Function
http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.
This problem occurs in the Response.Redirect
and Server.Transfer
methods, because both methods call Response.End
internally.
The solution for this problem is as follows.
For Server.Transfer
, use the Server.Execute
method instead.
Visit this link for download an example.
I love the answers from Kiril V. Lyadvinsky and CC. but my problem was a little more specific than just case-insensitivity; I needed a lazy Unicode-supported command-line argument parser that could eliminate false-positives/negatives when dealing with alphanumeric string searches that could have special characters in the base string used to format alphanum keywords I was searching against, e.g., Wolfjäger
shouldn't match jäger
but <jäger>
should.
It's basically just Kiril/CC's answer with extra handling for alphanumeric exact-length matches.
/* Undefined behavior when a non-alpha-num substring parameter is used. */
bool find_alphanum_string_CI(const std::wstring& baseString, const std::wstring& subString)
{
/* Fail fast if the base string was smaller than what we're looking for */
if (subString.length() > baseString.length())
return false;
auto it = std::search(
baseString.begin(), baseString.end(), subString.begin(), subString.end(),
[](char ch1, char ch2)
{
return std::toupper(ch1) == std::toupper(ch2);
}
);
if(it == baseString.end())
return false;
size_t match_start_offset = it - baseString.begin();
std::wstring match_start = baseString.substr(match_start_offset, std::wstring::npos);
/* Typical special characters and whitespace to split the substring up. */
size_t match_end_pos = match_start.find_first_of(L" ,<.>;:/?\'\"[{]}=+-_)(*&^%$#@!~`");
/* Pass fast if the remainder of the base string where
the match started is the same length as the substring. */
if (match_end_pos == std::wstring::npos && match_start.length() == subString.length())
return true;
std::wstring extracted_match = match_start.substr(0, match_end_pos);
return (extracted_match.length() == subString.length());
}
This worked for me:
import re
text = 'how are u? umberella u! u. U. U@ U# u '
rex = re.compile(r'\bu\b', re.IGNORECASE)
print(rex.sub('you', text))
It pre-compiles the regular expression and makes use of re.IGNORECASE so that we don't have to worry about case in our regular expression! BTW, I love the funky spelling of umbrella! :-)
For Http Request Default Port number is 80
For Https Default Port Number is 443
For Sql Server Default Port Number is 1433
I would say that when you have a language like Lisp with its support for macros, then you can build you own domain-specific abstractions, abstractions which often are much better than the general idiom solutions.
There is no function overloading in Python, meaning that you can't have multiple functions with the same name but different arguments.
In your code example, you're not overloading __init__()
. What happens is that the second definition rebinds the name __init__
to the new method, rendering the first method inaccessible.
As to your general question about constructors, Wikipedia is a good starting point. For Python-specific stuff, I highly recommend the Python docs.
If you can switch the ENGINE and use MyISAM instead of InnoDB, that should help:
ENGINE=MyISAM
There are two caveats with MyISAM (arguably more):
_CodeSigned
folderembedded.mobileprovision
file with the new provision profileExecute the below mentioned command:
/usr/bin/codesign -f -s "iPhone Distribution: Certificate Name" --resource-rules "Payload/Application.app/ResourceRules.plist" "Payload/Application.app"
Now zip the Payload folder again and change the .zip extension with .ipa
Hope this helpful.
For reference follow below mentioned link: http://www.modelmetrics.com/tomgersic/codesign-re-signing-an-ipa-between-apple-accounts/
There actually is now a GAC Utility for .NET 4.0. It is found in the Microsoft Windows 7 and .NET 4.0 SDK (the SDK supports multiple OSs -- not just Windows 7 -- so if you are using a later OS from Microsoft the odds are good that it's supported).
This is the SDK. You can download the ISO or do a Web install. Kind-of overkill to download the entire thing if all you want is the GAC Util; however, it does work.
Here this very usefull For Bootstrap Toggle Button . Example in code snippet!! and jsfiddle below.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">_x000D_
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">_x000D_
<input id="toggle-trigger" type="checkbox" checked data-toggle="toggle">_x000D_
<button class="btn btn-success" onclick="toggleOn()">On by API</button>_x000D_
<button class="btn btn-danger" onclick="toggleOff()">Off by API</button>_x000D_
<button class="btn btn-primary" onclick="getValue()">Get Value</button>_x000D_
<script>_x000D_
//If you want to change it dynamically_x000D_
function toggleOn() {_x000D_
$('#toggle-trigger').bootstrapToggle('on')_x000D_
}_x000D_
function toggleOff() {_x000D_
$('#toggle-trigger').bootstrapToggle('off') _x000D_
}_x000D_
//if you want get value_x000D_
function getValue()_x000D_
{_x000D_
var value=$('#toggle-trigger').bootstrapToggle().prop('checked');_x000D_
console.log(value);_x000D_
}_x000D_
</script>
_x000D_
Update 2020 For Bootstrap 4
I recommended bootstrap4-toggle in 2020.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>_x000D_
_x000D_
<link href="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/css/bootstrap4-toggle.min.css" rel="stylesheet">_x000D_
<script src="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/js/bootstrap4-toggle.min.js"></script>_x000D_
_x000D_
<input id="toggle-trigger" type="checkbox" checked data-toggle="toggle" data-onstyle="success">_x000D_
<button class="btn btn-success" onclick="toggleOn()">On by API</button>_x000D_
<button class="btn btn-danger" onclick="toggleOff()">Off by API</button>_x000D_
<button class="btn btn-primary" onclick="getValue()">Get Value</button>_x000D_
_x000D_
<script>_x000D_
//If you want to change it dynamically_x000D_
function toggleOn() {_x000D_
$('#toggle-trigger').bootstrapToggle('on')_x000D_
}_x000D_
function toggleOff() {_x000D_
$('#toggle-trigger').bootstrapToggle('off') _x000D_
}_x000D_
//if you want get value_x000D_
function getValue()_x000D_
{_x000D_
var value=$('#toggle-trigger').bootstrapToggle().prop('checked');_x000D_
console.log(value);_x000D_
}_x000D_
</script>
_x000D_
If, one day, someone else have to deal with this code as "legacy code", then that person will be grateful if you write a less exoteric code, such as
grep -q -F 'include "/configs/projectname.conf"' lighttpd.conf
if [ $? -ne 0 ]; then
echo 'include "/configs/projectname.conf"' >> lighttpd.conf
fi
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_id:
//Your Code....
item.setEnabled(false);
break;
}
return super.onOptionsItemSelected(item);
}
Here is way to to unset the hover effect.
.table-hover > tbody > tr.hidden-table:hover > td {
background-color: unset !important;
color: unset !important;
}
Here is another method using String.Format
DateTime todaysDate = DateTime.UtcNow;
string dateString = String.Format("{0:dd/MM/yyyy}", todaysDate);
Console.WriteLine("Date with Time: "+ todaysDate.ToString());
Console.WriteLine("Date Only : " + dateString);
Output:
Date with Time: 9/4/2016 11:42:16 AM
Date Only : 04/09/2016
This also works if the Date Time is stored in database.
For More Date and Time formatting check these links:
Hope helps.
The short answer is: No. The only way to post images is through the mobile app.
From the Instagram API documentation: http://instagram.com/developer/endpoints/media/
At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons:
- Instagram is about your life on the go – we hope to encourage photos from within the app. However, in the future we may give whitelist access to individual apps on a case by case basis.
- We want to fight spam & low quality photos. Once we allow uploading from other sources, it's harder to control what comes into the Instagram ecosystem.
All this being said, we're working on ways to ensure users have a consistent and high-quality experience on our platform.
Consider a simple shopping cart application that uses a CartContents class to keep track of the items in the shopping cart and an Order class for processing a purchase. The Order needs to determine the total value of the contents in the cart, it might do that like so:
Tightly Coupled Example:
public class CartEntry
{
public float Price;
public int Quantity;
}
public class CartContents
{
public CartEntry[] items;
}
public class Order
{
private CartContents cart;
private float salesTax;
public Order(CartContents cart, float salesTax)
{
this.cart = cart;
this.salesTax = salesTax;
}
public float OrderTotal()
{
float cartTotal = 0;
for (int i = 0; i < cart.items.Length; i++)
{
cartTotal += cart.items[i].Price * cart.items[i].Quantity;
}
cartTotal += cartTotal*salesTax;
return cartTotal;
}
}
Notice how the OrderTotal method (and thus the Order class) depends on the implementation details of the CartContents and the CartEntry classes. If we were to try to change this logic to allow for discounts, we'd likely have to change all 3 classes. Also, if we change to using a List collection to keep track of the items we'd have to change the Order class as well.
Now here's a slightly better way to do the same thing:
Less Coupled Example:
public class CartEntry
{
public float Price;
public int Quantity;
public float GetLineItemTotal()
{
return Price * Quantity;
}
}
public class CartContents
{
public CartEntry[] items;
public float GetCartItemsTotal()
{
float cartTotal = 0;
foreach (CartEntry item in items)
{
cartTotal += item.GetLineItemTotal();
}
return cartTotal;
}
}
public class Order
{
private CartContents cart;
private float salesTax;
public Order(CartContents cart, float salesTax)
{
this.cart = cart;
this.salesTax = salesTax;
}
public float OrderTotal()
{
return cart.GetCartItemsTotal() * (1.0f + salesTax);
}
}
The logic that is specific to the implementation of the cart line item or the cart collection or the order is restricted to just that class. So we could change the implementation of any of these classes without having to change the other classes. We could take this decoupling yet further by improving the design, introducing interfaces, etc, but I think you see the point.
If we split it up, the mess is equal to:
++[[]][+[]]
+
[+[]]
In JavaScript, it is true that +[] === 0
. +
converts something into a number, and in this case it will come down to +""
or 0
(see specification details below).
Therefore, we can simplify it (++
has precendence over +
):
++[[]][0]
+
[0]
Because [[]][0]
means: get the first element from [[]]
, it is true that:
[[]][0]
returns the inner array ([]
). Due to references it's wrong to say [[]][0] === []
, but let's call the inner array A
to avoid the wrong notation.
++
before its operand means “increment by one and return the incremented result”. So ++[[]][0]
is equivalent to Number(A) + 1
(or +A + 1
).
Again, we can simplify the mess into something more legible. Let's substitute []
back for A
:
(+[] + 1)
+
[0]
Before +[]
can coerce the array into the number 0
, it needs to be coerced into a string first, which is ""
, again. Finally, 1
is added, which results in 1
.
(+[] + 1) === (+"" + 1)
(+"" + 1) === (0 + 1)
(0 + 1) === 1
Let's simplify it even more:
1
+
[0]
Also, this is true in JavaScript: [0] == "0"
, because it's joining an array with one element. Joining will concatenate the elements separated by ,
. With one element, you can deduce that this logic will result in the first element itself.
In this case, +
sees two operands: a number and an array. It’s now trying to coerce the two into the same type. First, the array is coerced into the string "0"
, next, the number is coerced into a string ("1"
). Number +
String ===
String.
"1" + "0" === "10" // Yay!
Specification details for +[]
:
This is quite a maze, but to do +[]
, first it is being converted to a string because that's what +
says:
11.4.6 Unary + Operator
The unary + operator converts its operand to Number type.
The production UnaryExpression : + UnaryExpression is evaluated as follows:
Let expr be the result of evaluating UnaryExpression.
Return ToNumber(GetValue(expr)).
ToNumber()
says:
Object
Apply the following steps:
Let primValue be ToPrimitive(input argument, hint String).
Return ToString(primValue).
ToPrimitive()
says:
Object
Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.
[[DefaultValue]]
says:
8.12.8 [[DefaultValue]] (hint)
When the [[DefaultValue]] internal method of O is called with hint String, the following steps are taken:
Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".
If IsCallable(toString) is true then,
a. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.
b. If str is a primitive value, return str.
The .toString
of an array says:
15.4.4.2 Array.prototype.toString ( )
When the toString method is called, the following steps are taken:
Let array be the result of calling ToObject on the this value.
Let func be the result of calling the [[Get]] internal method of array with argument "join".
If IsCallable(func) is false, then let func be the standard built-in method Object.prototype.toString (15.2.4.2).
Return the result of calling the [[Call]] internal method of func providing array as the this value and an empty arguments list.
So +[]
comes down to +""
, because [].join() === ""
.
Again, the +
is defined as:
11.4.6 Unary + Operator
The unary + operator converts its operand to Number type.
The production UnaryExpression : + UnaryExpression is evaluated as follows:
Let expr be the result of evaluating UnaryExpression.
Return ToNumber(GetValue(expr)).
ToNumber
is defined for ""
as:
The MV of StringNumericLiteral ::: [empty] is 0.
So +"" === 0
, and thus +[] === 0
.