Before answering, I would like to give you some data from Wiki
Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.
When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.
To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}sSampleStruct;
sizeof(sSampleStruct)
will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:
typedef struct
{
char Data1;
//3-Bytes Added here.
int Data2;
unsigned short Data3;
char Data4;
//1-byte Added here.
}sSampleStruct;
We can use __attribute__((packed, aligned(X)))
to insist particular(X) sized padding. X should be powers of two. Refer here
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}__attribute__((packed, aligned(1))) sSampleStruct;
so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.
If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma
#pragma pack(push, 1)
//Structure 1
......
//Structure 2
......
#pragma pack(pop)
They are lists because you type them as lists in the dictionary:
bikes = {
# Bike designed for children"
"Trike": ["Trike", 20, 100],
# Bike designed for everyone"
"Kruzer": ["Kruzer", 50, 165]
}
You should use the bike-class instead:
bikes = {
# Bike designed for children"
"Trike": Bike("Trike", 20, 100),
# Bike designed for everyone"
"Kruzer": Bike("Kruzer", 50, 165)
}
This will allow you to get the cost of the bikes with bike.cost as you were trying to.
for bike in bikes.values():
profit = bike.cost * margin
print(bike.name + " : " + str(profit))
This will now print:
Kruzer : 33.0
Trike : 20.0
Looks like what you're trying to do is access property '0' of an undefined value in your 'data' array. If you look at your while statement, it appears this is happening because you are incrementing 'i' by 1 for each loop. Thus, the first time through, you will access, 'data[1]', but on the next loop, you'll access 'data[2]' and so on and so forth, regardless of the length of the array. This will cause you to eventually hit an array element which is undefined, if you never find an item in your array with property '0' which is equal to 'name'.
Ammend your while statement to this...
for(var iIndex = 1; iIndex <= data.length; iIndex++){
if (data[iIndex][0] === name){
break;
};
Logger.log(data[i][0]);
};
You can do like:
a="""xyz"""
g="abcd " & a
Or:
a=chr(34) & "xyz" & chr(34)
g="abcd " & a
First:
chmod 777 ./MigrateNshell.sh
Then:
./MigrateNshell.sh
Or, add your program to a directory recognized in your $PATH variable. Example: Path Variable Example
Which will then allow you to call your program without ./
My solutions in one of my own sites, with a table:
$.getJSON("sections/view_numbers_update.php", function(data) {
$.each(data, function(index, objNumber) {
$('#tr_' + objNumber.intID).find("td").eq(3).html(objNumber.datLastCalled);
$('#tr_' + objNumber.intID).find("td").eq(4).html(objNumber.strStatus);
$('#tr_' + objNumber.intID).find("td").eq(5).html(objNumber.intDuration);
$('#tr_' + objNumber.intID).find("td").eq(6).html(objNumber.blnWasHuman);
});
});
sections/view_numbers_update.php Returns something like:
[{"intID":"19","datLastCalled":"Thu, 10 Jan 13 08:52:20 +0000","strStatus":"Completed","intDuration":"0:04 secs","blnWasHuman":"Yes","datModified":1357807940},
{"intID":"22","datLastCalled":"Thu, 10 Jan 13 08:54:43 +0000","strStatus":"Completed","intDuration":"0:00 secs","blnWasHuman":"Yes","datModified":1357808079}]
HTML table:
<table id="table_numbers">
<tr>
<th>[...]</th>
<th>[...]</th>
<th>[...]</th>
<th>Last Call</th>
<th>Status</th>
<th>Duration</th>
<th>Human?</th>
<th>[...]</th>
</tr>
<tr id="tr_123456">
[...]
</tr>
</table>
This essentially gives every row a unique id preceding with 'tr_' to allow for other numbered element ids, at server script time. The jQuery script then just gets this TR_[id] element, and fills the correct indexed cell with the json return.
The advantage is you could get the complete array from the DB, and either foreach($array as $record) to create the table html, OR (if there is an update request) you can die(json_encode($array)) before displaying the table, all in the same page, but same display code.
if you are using sometimes playerID.stopVideo(); doesnot work, here is a trick,
function stopVideo() {
playerID.seekTo(0);
playerID.stopVideo();
}
After starting intent you can use this code :
Intent intent = new Intent(Activity1.this, Activity2.class);
overridePendingTransition(0, 0);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
If used, intent will work with no animations or transitions
As @David Heffeman indicates the recommendation is to use .yaml
when possible, and the recommendation has been that way since September 2006.
That some projects use .yml
is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).
The best way to approach this is to be rigorous when creating new files (i.e. use .yaml
) and be permissive when accepting input (i.e. allow .yml
when you encounter it), possible automatically upgrading/correcting these errors when possible.
The other recommendation I have is to document the argument(s) why you have to use .yml
, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml
has more pages than .yaml
" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml
extension instead of the correct .yaml
, but I think you will be hard pressed to do so.
Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose
used .yml
, but in later versions started to use .yaml
, although they still support .yml
). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml
instead of appveyor.yml
for building the windows wheels of my YAML parser for Python).
On the other hand:
The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.
So it seems fitting that they also use a subset of the recommended extension.
See: What is the best way to add options to a select from an array with jQuery?
$('#mySelect')
.append($('<option>', { value : key })
.text(value));
As you might already know, you can customize your indention settings in Preferences.sublime-settings
, for example:
"detect_indentation": true,
"tab_size": 4,
"translate_tabs_to_spaces": false
This will set your editor to use tabs that are 4 spaces wide and will override the default behavior that causes Sublime to match the indention of whatever file you're editing. With these settings, re-indenting the file will cause any spaces to be replaced with tabs.
As far as automatically re-indenting when opening a file, that's not quite as easy (but probably isn't a great idea since whitespace changes wreak havoc on file diffs). What might be a better course of action: you can map a shortcut for re-indention and just trigger that when you open a new file that needs fixing.
You need to set Div2 to Div1's innerHTML. Also, JavaScript is case sensitive - in your HTML, the id Div2
is DIV2
. Also, you should use document
, not Document
:
var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
Here is a JSFiddle: http://jsfiddle.net/gFN6r/.
try this
var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');
function iterate(selector)
{
var result = '';
if ($(selector))
{
$(selector).each(function ()
{
if (result == '')
{
result = $(this).html();
}
else
{
result = result + "," + $(this).html();
}
});
}
}
Here is my solution. I first create random numbers with random.uniform, format them in to string with double precision and then convert them back to float. You can adjust the precision by changing '.2f' to '.3f' etc..
import random
from decimal import Decimal
GndSpeedHigh = float(format(Decimal(random.uniform(5, 25)), '.2f'))
GndSpeedLow = float(format(Decimal(random.uniform(2, GndSpeedHigh)), '.2f'))
GndSpeedMean = float(Decimal(format(GndSpeedHigh + GndSpeedLow) / 2, '.2f')))
print(GndSpeedMean)
DateTime
is a DataType which is used to store both Date
and Time
. But it provides Properties to get the Date
Part.
You can get the Date part from Date
Property.
http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx
DateTime date1 = new DateTime(2008, 6, 1, 7, 47, 0);
Console.WriteLine(date1.ToString());
// Get date-only portion of date, without its time.
DateTime dateOnly = date1.Date;
// Display date using short date string.
Console.WriteLine(dateOnly.ToString("d"));
// Display date using 24-hour clock.
Console.WriteLine(dateOnly.ToString("g"));
Console.WriteLine(dateOnly.ToString("MM/dd/yyyy HH:mm"));
// The example displays the following output to the console:
// 6/1/2008 7:47:00 AM
// 6/1/2008
// 6/1/2008 12:00 AM
// 06/01/2008 00:00
yes we can do this using nth-child like so
div:nth-child(n + 8) {
background: red;
}
This will make the 8th div child onwards become red. Hope this helps...
Also, if someone ever says "hey, they can't be done with styled using css, use JS!!!" doubt them immediately. CSS is extremely flexible nowadays
Example :: http://jsfiddle.net/uWrLE/1/
In the example the first 7 children are blue, then 8 onwards are red...
Note: I have taken this from wordpress and it works!!
Use it like this:
echo sanitize('testing this link');
Code
//taken from wordpress
function utf8_uri_encode( $utf8_string, $length = 0 ) {
$unicode = '';
$values = array();
$num_octets = 1;
$unicode_length = 0;
$string_length = strlen( $utf8_string );
for ($i = 0; $i < $string_length; $i++ ) {
$value = ord( $utf8_string[ $i ] );
if ( $value < 128 ) {
if ( $length && ( $unicode_length >= $length ) )
break;
$unicode .= chr($value);
$unicode_length++;
} else {
if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
$values[] = $value;
if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
break;
if ( count( $values ) == $num_octets ) {
if ($num_octets == 3) {
$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
$unicode_length += 9;
} else {
$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
$unicode_length += 6;
}
$values = array();
$num_octets = 1;
}
}
}
return $unicode;
}
//taken from wordpress
function seems_utf8($str) {
$length = strlen($str);
for ($i=0; $i < $length; $i++) {
$c = ord($str[$i]);
if ($c < 0x80) $n = 0; # 0bbbbbbb
elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
else return false; # Does not match any model
for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
return false;
}
}
return true;
}
//function sanitize_title_with_dashes taken from wordpress
function sanitize($title) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 200);
}
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = str_replace('.', '-', $title);
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
The ==
operator checks to see if the two strings are exactly the same object.
The .equals()
method will check if the two strings have the same value.
If you need to do something for every element except either the first or the last and only if there is more than one element in the array, I prefer the following solution.
I know there are many solutions above and posted months/one year before mine, but this is something I feel is fairly elegant in its own right. The check every loop is also a boolean check as opposed to a numeric "i=(count-1)" check, which may allow for less overhead.
The structure of the loop may feel awkward, but you can compare it to the ordering of thead (beginning), tfoot (end), tbody (current) in HTML table tags.
$first = true;
foreach($array as $key => $value) {
if ($first) {
$first = false;
// Do what you want to do before the first element
echo "List of key, value pairs:\n";
} else {
// Do what you want to do at the end of every element
// except the last, assuming the list has more than one element
echo "\n";
}
// Do what you want to do for the current element
echo $key . ' => ' . $value;
}
For instance, in web development terms, if you want to add a border-bottom to every element except the last in an unordered list (ul), then you can instead add a border-top to every element except the first (the CSS :first-child, supported by IE7+ and Firefox/Webkit supports this logic, whereas :last-child is not supported by IE7).
You can feel free to reuse the $first variable for each and every nested loop as well and things will work just fine since every loop makes $first false during the first process of the first iteration (so breaks/exceptions won't cause issues).
$first = true;
foreach($array as $key => $subArray) {
if ($first) {
$string = "List of key => value array pairs:\n";
$first = false;
} else {
echo "\n";
}
$string .= $key . '=>(';
$first = true;
foreach($subArray as $key => $value) {
if ($first) {
$first = false;
} else {
$string .= ', ';
}
$string .= $key . '=>' . $value;
}
$string .= ')';
}
echo $string;
Example output:
List of key => value array pairs:
key1=>(v1_key1=>v1_val1, v1_key2=>v1_val2)
key2=>(v2_key1=>v2_val1, v2_key2=>v2_val2, v2_key3=>v2_val3)
key3=>(v3_key1=>v3_val1)
After you write to the MemoryStream
and before you read it back, you need to Seek
back to the beginning of the MemoryStream
so you're not reading from the end.
UPDATE
After seeing your update, I think there's a more reliable way to build the stream:
UnicodeEncoding uniEncoding = new UnicodeEncoding();
String message = "Message";
// You might not want to use the outer using statement that I have
// I wasn't sure how long you would need the MemoryStream object
using(MemoryStream ms = new MemoryStream())
{
var sw = new StreamWriter(ms, uniEncoding);
try
{
sw.Write(message);
sw.Flush();//otherwise you are risking empty stream
ms.Seek(0, SeekOrigin.Begin);
// Test and work with the stream here.
// If you need to start back at the beginning, be sure to Seek again.
}
finally
{
sw.Dispose();
}
}
As you can see, this code uses a StreamWriter to write the entire string (with proper encoding) out to the MemoryStream
. This takes the hassle out of ensuring the entire byte array for the string is written.
Update: I stepped into issue with empty stream several time. It's enough to call Flush right after you've finished writing.
In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.
The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.
DECLARE
PROD_ROW_ID VARCHAR (10) := NULL;
VIS_ROW_ID NUMBER;
DSC VARCHAR (512);
BEGIN
SELECT ROW_ID
INTO VIS_ROW_ID
FROM SIEBEL.S_PROD_INT
WHERE PART_NUM = 'S0146404';
BEGIN
SELECT RTRIM (VIS.SERIAL_NUM)
|| ','
|| RTRIM (PLANID.DESC_TEXT)
|| ','
|| CASE
WHEN PLANID.HIGH = 'TEST123'
THEN
CASE
WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
THEN
'Y'
ELSE
'N'
END
ELSE
'N'
END
|| ','
|| 'GB'
|| ','
|| RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
INTO DSC
FROM SIEBEL.S_LST_OF_VAL PLANID
INNER JOIN SIEBEL.S_PROD_INT PROD
ON PROD.PART_NUM = PLANID.VAL
INNER JOIN SIEBEL.S_ASSET NETFLIX
ON PROD.PROD_ID = PROD.ROW_ID
INNER JOIN SIEBEL.S_ASSET VIS
ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
INNER JOIN SIEBEL.S_PROD_INT VISPROD
ON VIS.PROD_ID = VISPROD.ROW_ID
WHERE PLANID.TYPE = 'Test Plan'
AND PLANID.ACTIVE_FLG = 'Y'
AND VISPROD.PART_NUM = VIS_ROW_ID
AND PROD.STATUS_CD = 'Active'
AND VIS.SERIAL_NUM IS NOT NULL;
END;
END;
/
References
http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/
ROWS UNBOUNDED PRECEDING
is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY
it defines the window on which the result is calculated.
Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.
Starting and ending rows might be fixed or relative to the current row based on the following keywords:
Possible kinds of calculation include:
So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING)
results in a Cumulative Sum or Running Total
11 -> 11
2 -> 11 + 2 = 13
3 -> 13 + 3 (or 11+2+3) = 16
44 -> 16 + 44 (or 11+2+3+44) = 60
Thanks it working
here i am done with this by qty field is zero means it shown that cells are in red color
int count = 0;
foreach (DataGridViewRow row in ItemDg.Rows)
{
int qtyEntered = Convert.ToInt16(row.Cells[1].Value);
if (qtyEntered <= 0)
{
ItemDg[0, count].Style.BackColor = Color.Red;//to color the row
ItemDg[1, count].Style.BackColor = Color.Red;
ItemDg[0, count].ReadOnly = true;//qty should not be enter for 0 inventory
}
ItemDg[0, count].Value = "0";//assign a default value to quantity enter
count++;
}
}
Does WHERE-clause can be actually used with INSERT-INTO-VALUES in any case?
The answer is definitively no.
Adding a WHERE clause after INSERT INTO ... VALUES ... is just invalid SQL, and will not parse.
The error returned by MySQL is:
mysql> INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id = 1' at line 1
The most important part of the error message is
... syntax to use near 'WHERE id = 1' ...
which shows the specific part the parser did not expect to find here: the WHERE clause.
You don't necessarily need to have the parameters inside the URL.
For instance, with:
$stateProvider
.state('home', {
url: '/',
views: {
'': {
templateUrl: 'home.html',
controller: 'MainRootCtrl'
},
},
params: {
foo: null,
bar: null
}
})
You will be able to send parameters to the state, using either:
$state.go('home', {foo: true, bar: 1});
// or
<a ui-sref="home({foo: true, bar: 1})">Go!</a>
Of course, if you reload the page once on the home
state, you will loose the state parameters, as they are not stored anywhere.
A full description of this behavior is documented here, under the params
row in the state(name, stateConfig)
section.
Interesting/funny way to do this using parameter expansion (requires bash 4.4
or newer):
${parameter@operator} - P operator
The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string.
$ show_time() { local format='\D{%Y%m%d%H%M%S}'; echo "${format@P}"; }
$ show_time
20180724003251
private void PictureBox1_Click(object sender, EventArgs e)
{
MessageBox.Show("Click Succes");
}
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
PictureBox1_Click(sender, e); //or try this one "this.PictureBox1_Click(sender, AcceptButton);"
}
}
A DTU is a unit of measure for the performance of a service tier and is a summary of several database characteristics. Each service tier has a certain number of DTUs assigned to it as an easy way to compare the performance level of one tier versus another.
Database Throughput Unit (DTU): DTUs provide a way to describe the relative capacity of a performance level of Basic, Standard, and Premium databases. DTUs are based on a blended measure of CPU, memory, reads, and writes. As DTUs increase, the power offered by the performance level increases. For example, a performance level with 5 DTUs has five times more power than a performance level with 1 DTU. A maximum DTU quota applies to each server.
The DTU Quota applies to the server, not the individual databases and each server has a maximum of 1600 DTUs. The DTU% is the percentage of units your particular database is using and it seems that this number can go over 100% of the DTU rating of the service tier (I assume to the limit of the server). This percentage number is designed to help you choose the appropriate service tier.
From down toward the bottom of this announcement:
For example, if your DTU consumption shows a value of 80%, it indicates it is consuming DTU at the rate of 80% of the limit an S2 database would have. If you see values greater than 100% in this view it means that you need a performance tier larger than S2.
As an example, let’s say you see a percentage value of 300%. This tells you that you are using three times more resources than would be available in an S2. To determine a reasonable starting size, compare the DTUs available in an S2 (50 DTUs) with the next higher sizes (P1 = 100 DTUs, or 200% of S2, P2 = 200 DTUs or 400% of S2). Because you are at 300% of S2 you would want to start with a P2 and re-test.
On the server-side:
Alternative solution: the select element is in your case (only guessing) a single-choice form control and you could use a group of radio buttons instead. These you could then style with better control. If you have a select[@multiple] you could do the same with a group of checkboxes instead as they can both be seen as a multiple-choice form control.
Can be done easily with $.map()
:
var len = $.map(a, function(n, i) { return i; }).length;
I also had the error message "TypeError: cannot concatenate 'str' and 'int' objects". It turns out that I only just forgot to add str() around a variable when printing it. Here is my code:
def main():_x000D_
rolling = True; import random_x000D_
while rolling:_x000D_
roll = input("ENTER = roll; Q = quit ")_x000D_
if roll.lower() != 'q':_x000D_
num = (random.randint(1,6))_x000D_
print("----------------------"); print("you rolled " + str(num))_x000D_
else:_x000D_
rolling = False_x000D_
main()
_x000D_
I know, it was a stupid mistake but for beginners who are very new to python such as myself, it happens.
Nowadays you can get the FileVersionInfo from Get-Item or Get-ChildItem, but it will show the original FileVersion from the shipped product, and not the updated version. For instance:
(Get-Item C:\Windows\System32\Lsasrv.dll).VersionInfo.FileVersion
Interestingly, you can get the updated (patched) ProductVersion by using this:
(Get-Command C:\Windows\System32\Lsasrv.dll).Version
The distinction I'm making between "original" and "patched" is basically due to the way the FileVersion is calculated (see the docs here). Basically ever since Vista, the Windows API GetFileVersionInfo is querying part of the version information from the language neutral file (exe/dll) and the non-fixed part from a language-specific mui file (which isn't updated every time the files change).
So with a file like lsasrv (which got replaced due to security problems in SSL/TLS/RDS in November 2014) the versions reported by these two commands (at least for a while after that date) were different, and the second one is the more "correct" version.
However, although it's correct in LSASrv, it's possible for the ProductVersion and FileVersion to be different (it's common, in fact). So the only way to get the updated Fileversion straight from the assembly file is to build it up yourself from the parts, something like this:
Get-Item C:\Windows\System32\Lsasrv.dll | ft FileName, File*Part
Or by pulling the data from this:
[System.Diagnostics.FileVersionInfo]::GetVersionInfo($this.FullName)
You can easily add this to all FileInfo objects by updating the TypeData in PowerShell:
Update-TypeData -TypeName System.IO.FileInfo -MemberName FileVersion -MemberType ScriptProperty -Value {
[System.Diagnostics.FileVersionInfo]::GetVersionInfo($this.FullName) | % {
[Version](($_.FileMajorPart, $_.FileMinorPart, $_.FileBuildPart, $_.FilePrivatePart)-join".")
}
}
Now every time you do Get-ChildItem
or Get-Item
you'll have a FileVersion
property that shows the updated FileVersion ...
router.route('/product/name/:name')
.get(function(req, res) {
var regex = new RegExp(req.params.name, "i")
, query = { description: regex };
Product.find(query, function(err, products) {
if (err) {
res.json(err);
}
res.json(products);
});
});
A Java list is a collection of objects ... the elements of a list. The size of the list is the number of elements in that list. If you want that size to be fixed, that means that you cannot either add or remove elements, because adding or removing elements would violate your "fixed size" constraint.
The simplest way to implement a "fixed sized" list (if that is really what you want!) is to put the elements into an array and then Arrays.asList(array)
to create the list wrapper. The wrapper will allow you to do operations like get
and set
, but the add
and remove
operations will throw exceptions.
And if you want to create a fixed-sized wrapper for an existing list, then you could use the Apache commons FixedSizeList
class. But note that this wrapper can't stop something else changing the size of the original list, and if that happens the wrapped list will presumably reflect those changes.
On the other hand, if you really want a list type with a fixed limit (or limits) on its size, then you'll need to create your own List class to implement this. For example, you could create a wrapper class that implements the relevant checks in the various add
/ addAll
and remove
/ removeAll
/ retainAll
operations. (And in the iterator remove
methods if they are supported.)
So why doesn't the Java Collections framework implement these? Here's why I think so:
Collections.sort
.Use count(d.ertek)
or count(d.id)
instead of count(d)
. This can be happen when you have composite primary key at your entity.
You can use:
@foreach (var item in Model)
{
...
@Html.DisplayFor(modelItem => item.address + " " + item.city)
...
None of the solutions above worked for me, I had to uninstall coacoapods, then installed a specific version before everything worked for me
sudo gem uninstall cocoapods
then
sudo gem install cocoapods -v 1.7.5
now even verbose shows progress
$ pod setup --verbose
Setting up CocoaPods master repo
Cloning spec repo `master` from `https://github.com/CocoaPods/Specs.git` (branch `master`)
$ /usr/bin/git clone https://github.com/CocoaPods/Specs.git --progress -- master
Cloning into 'master'...
remote: Enumerating objects: 295, done.
remote: Counting objects: 100% (295/295), done.
remote: Compressing objects: 100% (283/283), done.
Receiving objects: 20% (744493/3722462), 132.93 MiB | 567.00 KiB/s
Step For Windows
now command prompt will be open.
after the type cd filepath of file. ex(cd C:\Users\user\Desktop\ ) then hit the enter.
C:\Users\user\Desktop>node app.js
value_counts work only for series. It won't work for entire DataFrame. Try selecting only one column and using this attribute. For example:
df['accepted'].value_counts()
It also won't work if you have duplicate columns. This is because when you select a particular column, it will also represent the duplicate column and will return dataframe instead of series. At that time remove duplicate column by using
df = df.loc[:,~df.columns.duplicated()]
df['accepted'].value_counts()
Worked by lowering the spring boot starter parent to 1.5.13
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.13.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
:w
- Write a file.
!sudo
- Call shell sudo command.
tee
- The output of write (vim :w) command redirected using tee. The % is nothing but current file name i.e. /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself):
Hypothetically, if search landed you on this question then you probably want this:
doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));
Why? Because like me you value time and you are not going to implement .equals
just for the sake of the single test scenario.
And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null
at all costs, use Optional
or move to Kotlin. This implies that verify
does not need to be used that often and ArgumentCaptors are just too tedious to write.
Log4Jdbc plugin would be best for your requirement. It shows following-
1. Complete SQL query being hit to the db
2. Parameter values being passed to the query
3. Execution time taken by each query
Refer below link to configure Log4Jdbc-
https://code.google.com/p/log4jdbc/
Sometimes file names are numbered, where the index may be at the beginning or the end. So I wanted to shorten from the center of the string:
function stringTruncateFromCenter(str, maxLength) {
const midChar = "…"; // character to insert into the center of the result
var left, right;
if (str.length <= maxLength) return str;
// length of beginning part
left = Math.ceil(maxLength / 2);
// start index of ending part
right = str.length - Math.floor(maxLength / 2) + 1;
return str.substr(0, left) + midChar + str.substring(right);
}
Be aware that I used a fill character here with more than 1 byte in UTF-8.
Yes, there's str_to_date
mysql> select str_to_date("03/02/2009","%d/%m/%Y");
+--------------------------------------+
| str_to_date("03/02/2009","%d/%m/%Y") |
+--------------------------------------+
| 2009-02-03 |
+--------------------------------------+
1 row in set (0.00 sec)
I created an Interface and a <options>
tag helper for this. So I didn't have to convert the IEnumerable<T>
items into IEnumerable<SelectListItem>
every time I have to populate the <select>
control.
And I think it works beautifully...
The usage is something like:
<select asp-for="EmployeeId">
<option value="">Please select...</option>
<options asp-items="@Model.EmployeesList" />
</select>
And to make it work with the tag helper you have to implement that interface in your class:
public class Employee : IIntegerListItem
{
public int Id { get; set; }
public string FullName { get; set; }
public int Value { return Id; }
public string Text{ return FullName ; }
}
These are the needed codes:
The interface:
public interface IIntegerListItem
{
int Value { get; }
string Text { get; }
}
The <options>
tag helper:
[HtmlTargetElement("options", Attributes = "asp-items")]
public class OptionsTagHelper : TagHelper
{
public OptionsTagHelper(IHtmlGenerator generator)
{
Generator = generator;
}
[HtmlAttributeNotBound]
public IHtmlGenerator Generator { get; set; }
[HtmlAttributeName("asp-items")]
public object Items { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.SuppressOutput();
// Is this <options /> element a child of a <select/> element the SelectTagHelper targeted?
object formDataEntry;
context.Items.TryGetValue(typeof(SelectTagHelper), out formDataEntry);
var selectedValues = formDataEntry as ICollection<string>;
var encodedValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (selectedValues != null && selectedValues.Count != 0)
{
foreach (var selectedValue in selectedValues)
{
encodedValues.Add(Generator.Encode(selectedValue));
}
}
IEnumerable<SelectListItem> items = null;
if (Items != null)
{
if (Items is IEnumerable)
{
var enumerable = Items as IEnumerable;
if (Items is IEnumerable<SelectListItem>)
items = Items as IEnumerable<SelectListItem>;
else if (Items is IEnumerable<IIntegerListItem>)
items = ((IEnumerable<IIntegerListItem>)Items).Select(x => new SelectListItem() { Selected = false, Value = ((IIntegerListItem)x).Value.ToString(), Text = ((IIntegerListItem)x).Text });
else
throw new InvalidOperationException(string.Format("The {2} was unable to provide metadata about '{1}' expression value '{3}' for <options>.",
"<options>",
"ForAttributeName",
nameof(IModelMetadataProvider),
"For.Name"));
}
else
{
throw new InvalidOperationException("Invalid items for <options>");
}
foreach (var item in items)
{
bool selected = (selectedValues != null && selectedValues.Contains(item.Value)) || encodedValues.Contains(item.Value);
var selectedAttr = selected ? "selected='selected'" : "";
if (item.Value != null)
output.Content.AppendHtml($"<option value='{item.Value}' {selectedAttr}>{item.Text}</option>");
else
output.Content.AppendHtml($"<option>{item.Text}</option>");
}
}
}
}
There may be some typo but the aim is clear I think. I had to edit a little bit.
Objective-C Implementation :
-(NSString*)getColumnName:(int)n {
NSString *name = @"";
while (n>0) {
n--;
char c = (char)('A' + n%26);
name = [NSString stringWithFormat:@"%c%@",c,name];
n = n/26;
}
return name;
}
SWIFT Implementation:
func getColumnName(n:Int)->String{
var columnName = ""
var index = n
while index>0 {
index--
let char = Character(UnicodeScalar(65 + index%26))
columnName = "\(char)\(columnName)"
index = index / 26
}
return columnName
}
The answer is based on :https://stackoverflow.com/a/4532562/2231118
If there is only 1 occurrence, the answer of ivanovic is the best way I guess. But if there are many occurrences, you should use regexp:
\[(.*?)\]
this is your pattern. And in each group(1)
will get you your string.
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(input);
while(m.find())
{
m.group(1); //is your string. do what you want
}
Try this way:
select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE()
Use Range("A1").Text
instead of .Value
post comment edit:
Why?
Because the .Text
property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92
then <- Text
will return exactly what it in the cell including any formatting.
The .Value
and .Value2
properties return what's stored in the cell under the hood excluding formatting. Specially .Value2
for date types, it will return the decimal representation.
If you want to dig deeper into the meaning and performance, I just found this article
which seems like a good guide
another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
now,
paste this code in a module
Sub main()
Dim ws As Worksheet, i&, j&
Set ws = Sheets(1)
For i = 3 To 7
For j = 1 To 4
Debug.Print _
"row " & i & vbTab & vbTab & _
Cells(i, j).Text & vbTab & _
Cells(i, j).Value & vbTab & _
Cells(i, j).Value2
Next j
Next i
End Sub
and Analyse
the output! Its really easy and there isn't much more i can do to help :)
.TEXT .VALUE .VALUE2
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 4 1 1 1
row 4 1 1 1
row 4 01/01/1900 31/12/1899 1
row 4 1.00% 0.01 0.01
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 6 63 63 63
row 6 =7*9 =7*9 =7*9
row 6 03/03/1900 03/03/1900 63
row 6 6300.00% 63 63
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013 29/05/2013 29/05/2013
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013% 29/05/2013% 29/05/2013%
You should NOT use ::ng-deep
, it is deprecated. In Angular, the proper way to change the style of children's component from the parent is to use encapsulation
(read the warning below to understand the implications):
import { ViewEncapsulation } from '@angular/core';
@Component({
....
encapsulation: ViewEncapsulation.None
})
And then, you will be able to modify the css form your component without a need from ::ng-deep
.mat-sort-header-container {
display: flex;
justify-content: center;
}
WARNING: Doing this will make all css rules you write for this component to be global.
In order to limit the scope of your css to this component and his child only, add a css class to the top tag of your component and put your css "inside" this tag:
template:
<div class='my-component'>
<child-component class="first">First</child>
</div>,
Scss file:
.my-component {
// All your css goes in there in order not to be global
}
Using callback plugins, you can have the stdout of your commands output in readable form with the play: gist: human_log.py
Edit for example output:
_____________________________________
< TASK: common | install apt packages >
-------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
changed: [10.76.71.167] => (item=htop,vim-tiny,curl,git,unzip,update-motd,ssh-askpass,gcc,python-dev,libxml2,libxml2-dev,libxslt-dev,python-lxml,python-pip)
stdout:
Reading package lists...
Building dependency tree...
Reading state information...
libxslt1-dev is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 24 not upgraded.
stderr:
start:
2015-03-27 17:12:22.132237
end:
2015-03-27 17:12:22.136859
If the variable ax.xaxis._autolabelpos = True, matplotlib sets the label position in function _update_label_position in axis.py according to (some excerpts):
bboxes, bboxes2 = self._get_tick_bboxes(ticks_to_draw, renderer)
bbox = mtransforms.Bbox.union(bboxes)
bottom = bbox.y0
x, y = self.label.get_position()
self.label.set_position((x, bottom - self.labelpad * self.figure.dpi / 72.0))
You can set the label position independently of the ticks by using:
ax.xaxis.set_label_coords(x0, y0)
that sets _autolabelpos to False or as mentioned above by changing the labelpad parameter.
There is now a php artisan view:clear
command for this task since Laravel 5.1
You can also get stack trace as string via ExceptionUtils.getStackTrace
.
See: ExceptionUtils.java
I use it only for log.debug
, to keep log.error
simple.
You could try checking to see if this method returns a null:
if (ddlCustomerNumber.Items.FindByText(GetCustomerNumberCookie().ToString()) != null)
ddlCustomerNumber.SelectedIndex = 0;
My short answer is:
function display_two_array {_x000D_
local arr1=$1_x000D_
local arr2=$2_x000D_
for i in $arr1_x000D_
do_x000D_
"arrary1: $i"_x000D_
done_x000D_
_x000D_
for i in $arr2_x000D_
do_x000D_
"arrary2: $i"_x000D_
done_x000D_
}_x000D_
_x000D_
test_array=(1 2 3 4 5)_x000D_
test_array2=(7 8 9 10 11)_x000D_
_x000D_
display_two_array "${test_array[*]}" "${test_array2[*]}"
_x000D_
${test_array[*]}
and ${test_array2[*]}
should be surrounded by "", otherwise you'll fail.
Replace void *disconnectFunc;
with void (*disconnectFunc)();
to declare function pointer type variable. Or even better use a typedef
:
typedef void (*func_t)(); // pointer to function with no args and void return
...
func_t fptr; // variable of pointer to function
...
void D::setDisconnectFunc( func_t func )
{
fptr = func;
}
void D::disconnected()
{
fptr();
connected = false;
}
const things = [
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"},
{place:"there",name:"morestuff"}
];
const filteredArr = things.reduce((thing, current) => {
const x = thing.find(item => item.place === current.place);
if (!x) {
return thing.concat([current]);
} else {
return thing;
}
}, []);
console.log(filteredArr)
_x000D_
Solution Via Set
Object | According to the data type
const seen = new Set();
const things = [
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"},
{place:"there",name:"morestuff"}
];
const filteredArr = things.filter(el => {
const duplicate = seen.has(el.place);
seen.add(el.place);
return !duplicate;
});
console.log(filteredArr)
_x000D_
Set
Object Feature
Each value in the Set Object has to be unique, the value equality will be checked
The Purpose of Set object storing unique values according to the Data type , whether primitive values or object references.it has very useful four Instance methods add
, clear
, has
& delete
.
Unique & data Type feature:..
add
method
it's push unique data into collection by default also preserve data type .. that means it prevent to push duplicate item into collection also it will check data type by default...
has
method
sometime needs to check data item exist into the collection and . it's handy method for the collection to cheek unique id or item and data type..
delete
method
it will remove specific item from the collection by identifying data type..
clear
method
it will remove all collection items from one specific variable and set as empty object
Set
object has also Iteration methods & more feature..
Better Read from Here : Set - JavaScript | MDN
To use Python EasyInstall (which is what I think you're wanting to use), is super easy!
sudo easy_install pip
so then with pip to install Pyserial you would do:
pip install pyserial
herein a simple way to count 0 or more arguments of VA_ARGS, my exemple assumes a maximum of 5 variables, but you can add more if you want.
#define VA_ARGS_NUM_PRIV(P1, P2, P3, P4, P5, P6, Pn, ...) Pn
#define VA_ARGS_NUM(...) VA_ARGS_NUM_PRIV(-1, ##__VA_ARGS__, 5, 4, 3, 2, 1, 0)
VA_ARGS_NUM() ==> 0
VA_ARGS_NUM(19) ==> 1
VA_ARGS_NUM(9, 10) ==> 2
...
Update for 2018:
Now there's no need for jQuery and it's been a while since document.querySelector
or document.querySelectorAll
(for multiple elements) do almost exactly same job as $, plus more explicit ones getElementById
, getElementsByClassName
, getElementsByTagName
Disabling one field of "input-checkbox" class
document.querySelector('.input-checkbox').disabled = true;
or multiple elements
document.querySelectorAll('.input-checkbox').forEach(el => el.disabled = true);
Just use z-index
CSS property as described in the highest liked answer and the nav bar will stick to the top.
Example:
<div class="navigation">
<nav>
<ul>
<li>Home</li>
<li>Contact</li>
</ul>
</nav>
.navigation {
/* fixed keyword is fine too */
position: sticky;
top: 0;
z-index: 100;
/* z-index works pretty much like a layer:
the higher the z-index value, the greater
it will allow the navigation tag to stay on top
of other tags */
}
What you need are character classes. In that, you've only to worry about the ]
, \
and -
characters (and ^
if you're placing it straight after the beginning of the character class "[
" ).
Syntax: [
characters]
where characters is a list with characters.
Example:
var cleanString = dirtyString.replace(/[|&;$%@"<>()+,]/g, "");
REST doesn't have a recommended date format. Really it boils down to what works best for your end user and your system. Personally, I would want to stick to a standard like you have for ISO 8601 (url encoded).
If not having ugly URI is a concern (e.g. not including the url encoded version of :
, -
, in you URI) and (human) addressability is not as important, you could also consider epoch time (e.g.
http://example.com/start/1331162374
). The URL looks a little cleaner, but you certainly lose readability.
The /2012/03/07
is another format you see a lot. You could expand upon that I suppose. If you go this route, just make sure you're either always in GMT time (and make that clear in your documentation) or you might also want to include some sort of timezone indicator.
Ultimately it boils down to what works for your API and your end user. Your API should work for you, not you for it ;-).
Note that neither DBCC DROPCLEANBUFFERS;
nor DBCC FREEPROCCACHE;
is supported in SQL Azure / SQL Data Warehouse.
However, if you need to reset the plan cache in SQL Azure, you can alter one of the tables in the query (for instance, just add then remove a column), this will have the side-effect of removing the plan from the cache.
I personally do this as a way of testing query performance without having to deal with cached plans.
I wrote my own library to achieve the intended behaviour in ios Maps app. It is a protocol oriented solution. So you don't need to inherit any base class instead create a sheet controller and configure as you wish. It also supports inner navigation/presentation with or without UINavigationController.
See below link for more details.
If you need time stamp as a string.
time_t result = time(NULL);
NSString *timeStampString = [@(result) stringValue];
Basic Availability: The database appears to work most of the time.
Soft State: Stores don’t have to be write-consistent or mutually consistent all the time.
Eventual consistency: Data should always be consistent, with regards how any number of changes are performed.
yes you need to call repaint(); revalidate(); when you call removeAll() then you have to call repaint() and revalidate()
Before you call setContentView()
, call setTheme(android.R.style...)
and just replace the ... with the theme that you want(Theme, Theme_NoTitleBar, etc.).
Or if your theme is a custom theme, then replace the entire thing, so you get setTheme(yourThemesResouceId)
If you want a specific order, then you must use an array, not an object. Objects do not have a defined order.
For example, using an array, you could do this:
var myobj = [{"A":["B"]}, {"B": ["C"]}];
var firstItem = myobj[0];
Then, you can use myobj[0] to get the first object in the array.
Or, depending upon what you're trying to do:
var myobj = [{key: "A", val:["B"]}, {key: "B", val:["C"]}];
var firstKey = myobj[0].key; // "A"
var firstValue = myobj[0].val; // "["B"]
Put them in an arrayList in your first class like:
import java.util.ArrayList;
public class numbers {
private int number1 = 50;
private int number2 = 100;
public ArrayList<int> getNumberList() {
ArrayList<int> numbersList= new ArrayList<int>();
numbersList.add(number1);
numberList.add(number2);
....
return numberList;
}
}
Then, in your test class you can call numbers.getNumberList() to get your arrayList. In addition, you might want to create methods like addToList / removeFromList in your numbers class so you can handle it the way you need it.
You can also access a variable declared in one class from another simply like
numbers.numberList;
if you have it declared there as public.
But it isn't such a good practice in my opinion, since you probably need to modify this list in your code later. Note that you have to add your class to the import list.
If you can tell me what your app requirements are, i'll be able tell you more precise what i think it's best to do.
Just show file name extension from Windows Explorer, after applying the below steps, create a new file, and type your extension as .json
Open Folder Options by clicking the Start button Picture of the Start button, clicking Control Panel, clicking Appearance and Personalization, and then clicking Folder Options.
Click the View tab, and then, under Advanced settings, clear the Hide extensions for known file types check box, and then click OK
Bootstrap 4.4:
Show a choose file
bar. After a file is chosen show the file name along with its extension
<div class="custom-file">
<input type="file" class="custom-file-input" id="idEditUploadVideo"
onchange="$('#idFileName').html(this.files[0].name)">
<label class="custom-file-label" id="idFileName" for="idEditUploadVideo">Choose file</label>
</div>
In case you're looking for a javascript library - out of the box solution, jquery-fileinput works fine.
<-
does assignment in the current environment.
When you're inside a function R creates a new environment for you. By default it includes everything from the environment in which it was created so you can use those variables as well but anything new you create will not get written to the global environment.
In most cases <<-
will assign to variables already in the global environment or create a variable in the global environment even if you're inside a function. However, it isn't quite as straightforward as that. What it does is checks the parent environment for a variable with the name of interest. If it doesn't find it in your parent environment it goes to the parent of the parent environment (at the time the function was created) and looks there. It continues upward to the global environment and if it isn't found in the global environment it will assign the variable in the global environment.
This might illustrate what is going on.
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
bar <- "in baz - before <<-"
bar <<- "in baz - after <<-"
print(bar)
}
print(bar)
baz()
print(bar)
}
> bar
[1] "global"
> foo()
[1] "in foo"
[1] "in baz - before <<-"
[1] "in baz - after <<-"
> bar
[1] "global"
The first time we print bar we haven't called foo
yet so it should still be global - this makes sense. The second time we print it's inside of foo
before calling baz
so the value "in foo" makes sense. The following is where we see what <<-
is actually doing. The next value printed is "in baz - before <<-" even though the print statement comes after the <<-
. This is because <<-
doesn't look in the current environment (unless you're in the global environment in which case <<-
acts like <-
). So inside of baz
the value of bar stays as "in baz - before <<-". Once we call baz
the copy of bar inside of foo
gets changed to "in baz" but as we can see the global bar
is unchanged. This is because the copy of bar
that is defined inside of foo
is in the parent environment when we created baz
so this is the first copy of bar
that <<-
sees and thus the copy it assigns to. So <<-
isn't just directly assigning to the global environment.
<<-
is tricky and I wouldn't recommend using it if you can avoid it. If you really want to assign to the global environment you can use the assign function and tell it explicitly that you want to assign globally.
Now I change the <<-
to an assign statement and we can see what effect that has:
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
assign("bar", "in baz", envir = .GlobalEnv)
}
print(bar)
baz()
print(bar)
}
bar
#[1] "global"
foo()
#[1] "in foo"
#[1] "in foo"
bar
#[1] "in baz"
So both times we print bar inside of foo
the value is "in foo" even after calling baz
. This is because assign
never even considered the copy of bar
inside of foo because we told it exactly where to look. However, this time the value of bar in the global environment was changed because we explicitly assigned there.
Now you also asked about creating local variables and you can do that fairly easily as well without creating a function... We just need to use the local
function.
bar <- "global"
# local will create a new environment for us to play in
local({
bar <- "local"
print(bar)
})
#[1] "local"
bar
#[1] "global"
Replying to this 4 year old post, because this seems overcomplicated to me, at least if you're hosting on IIS.
Here's how I solved it:
using System;
using System.Net;
using System.Web;
using System.Web.Http;
...
[HttpPost]
[Route("ContactForm")]
public IHttpActionResult PostContactForm([FromBody] ContactForm contactForm)
{
var hostname = HttpContext.Current.Request.UserHostAddress;
IPAddress ipAddress = IPAddress.Parse(hostname);
IPHostEntry ipHostEntry = Dns.GetHostEntry(ipAddress);
...
Unlike OP, this gives me the client IP and client hostname, not the server. Perhaps they've fixed the bug since then?
Have a look at this jQuery plugin: jquery.confirm.
<a href="home" class="confirm">Go to home</a>
and then:
$(".confirm").confirm();
This will show a confirmation popup before proceeding to following the link.
There's a demo here: http://myclabs.github.com/jquery.confirm/
The <figcaption>
tag in HTML5 allows you to enter text to your image for example:
<figcaption>
Your text here
</figcaption>.
You can then use CSS to position the text where it should be on the image.
There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.
Here is what you can do:
#include <algorithm>
int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);
However, in C++0x, you can do this:
std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};
Of course, if you choose to use std::vector
instead of raw array.
Your controller method should be like this:
@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
Person person = personService.getCurrentlyAuthenticatedUser();
int id = 2323; // Currently passing static values for testing
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
return "note";
}
Use the id
in your code, call the controller method from your JSP as:
/{your mapping}/{your id}
UPDATE:
Change your jsp code to:
<c:forEach items="${listNotes}" var="notices" varStatus="status">
<tr>
<td>${notices.noticesid}</td>
<td>${notices.notetext}</td>
<td>${notices.notetag}</td>
<td>${notices.notecolor}</td>
<td>${notices.sectionid}</td>
<td>${notices.canvasid}</td>
<td>${notices.canvasnName}</td>
<td>${notices.personid}</td>
<td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
<td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
</tr>
</c:forEach>
The Maven manual says to do this:
mvn install:install-file -Dfile=non-maven-proj.jar -DgroupId=some.group -DartifactId=non-maven-proj -Dversion=1 -Dpackaging=jar
VS 2012 has different project type support based on what you install at setup time and which edition you have. Certain options are available, e.g. web development tools, database development tools, etc. So if you're trying to open a web project but the web development tools weren't installed, it complains with this message.
This can happen if you create the project on another machine and try to open it on a new one. I figured it out trying to open an MVC project after I accidentally uninstalled the web tools.
If you have a form as such:
<form id="myform">
...
</form>
You can use the following jQuery code to do something before the form is submitted:
$('#myform').submit(function() {
// DO STUFF...
return true; // return false to cancel form action
});
Install PAR::Packer
. Example for *nix:
sudo cpan -i PAR::Packer
For Strawberry Perl for Windows or for ActivePerl and MSVC installed:
cpan -i PAR::Packer
Pack it with pp
. It will create an executable named "example" or "example.exe" on Windows.
pp -o example example.pl
This would work only on the OS where it was built.
P.S. It is really hard to find a Unix clone without Perl. Did you mean Windows?
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)
}
I had a similar error. The answers here helped me figure out what to do.
index.html
<!--The div element for the map -->
<div id="map"></div>
<!--The link to external javascript file that has initMap() function-->
<script src="main.js">
<!--Google api, this calls initMap() function-->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEYWY&callback=initMap">
</script>
main.js // This gives error
// The initMap function has not been executed
const initMap = () => {
const mapDisplayElement = document.getElementById('map');
// The address is Uluru
const address = {lat: -25.344, lng: 131.036};
// The zoom property specifies the zoom level for the map. Zoom: 0 is the lowest zoom,and displays the entire earth.
const map = new google.maps.Map(mapDisplayElement, { zoom: 4, center: address });
const marker = new google.maps.Marker({ position: address, map });
};
The answers here helped me figure out a solution. I used an immediately invoked the function (IIFE ) to work around it.
The error is as at the time of calling the google maps api the initMap() function has not executed.
main.js // This works
const mapDisplayElement = document.getElementById('map');
// The address is Uluru
// Run the initMap() function imidiately,
(initMap = () => {
const address = {lat: -25.344, lng: 131.036};
// The zoom property specifies the zoom level for the map. Zoom: 0 is the lowest zoom,and displays the entire earth.
const map = new google.maps.Map(mapDisplayElement, { zoom: 4, center: address });
const marker = new google.maps.Marker({ position: address, map });
})();
window.location.assign(url)
this fixs the window.open(url)
issue in ios devices
You have specified the ajax call response dataType as:
'json'
where as the actual ajax response is not a valid JSON and as a result the JSON parser is throwing an error.
The best approach that I would recommend is to change the dataType to:
'text'
and within the success callback validate whether a valid JSON is being returned or not, and if JSON validation fails, alert it on the screen so that its obvious for what purpose the ajax call is actually failing. Have a look at this:
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'text',
data: {viewID: $("#view").val()},
success: function (data) {
try {
var output = JSON.parse(data);
alert(output);
} catch (e) {
alert("Output is not valid JSON: " + data);
}
}, error: function (request, error) {
alert("AJAX Call Error: " + error);
}
});
Try this more succinct code:
Sub LoopOverEachColumn()
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
ResizeColumns WS
Next WS
End Sub
Private Sub ResizeColumns(WS As Worksheet)
Dim StrSize As String
Dim ColIter As Long
StrSize = "20.14;9.71;35.86;30.57;23.57;21.43;18.43;23.86;27.43;36.71;30.29;31.14;31;41.14;33.86"
For ColIter = 1 To 15
WS.Columns(ColIter).ColumnWidth = Split(StrSize, ";")(ColIter - 1)
Next ColIter
End Sub
If you want additional columns, just change 1 to 15
to 1 to X
where X
is the column index of the column you want, and append the column size you want to StrSize
.
For example, if you want P:P
to have a width of 25
, just add ;25
to StrSize
and change ColIter...
to ColIter = 1 to 16
.
Hope this helps.
I think you want SYSDATE
, not GETDATE()
. Try it:
UPDATE TableName SET LastModifiedDate = (SELECT SYSDATE FROM DUAL);
Adding a small variation to estani's excellent answer
Local to ISO 8601 with TimeZone and no microsecond info (Python 3):
import datetime, time
utc_offset_sec = time.altzone if time.localtime().tm_isdst else time.timezone
utc_offset = datetime.timedelta(seconds=-utc_offset_sec)
datetime.datetime.now().replace(microsecond=0, tzinfo=datetime.timezone(offset=utc_offset)).isoformat()
Sample Output:
'2019-11-06T12:12:06-08:00'
Tested that this output can be parsed by both Javascript Date
and C# DateTime
/DateTimeOffset
You can add a callback function to your DatePicker to tell it to blur the input field before showing the DatePicker.
$('.selector').datepicker({
beforeShow: function(){$('input').blur();}
});
Note: The iOS keyboard will appear for a fraction of a second and then hide.
Craiglist is pretty stingy with their data , they even go out of their way to block scraping. If you use ruby here is a gem I wrote to help scrape craiglist data you can search through multiple cities , calculate average price ect...
CSS supports text input for colors (i.e. "black" = #000000 "white" = #ffffff) So I think the helpful solution we are looking for here is how can one have PHP take the output from an HTML form text input box and have it tell CSS to use this line of text for background color.
So that when a a user types "blue" into the text field titled "what is your favorite color", they are returned a page with a blue background, or whatever color they happen to type in so long as it is recognized by CSS.
I believe Dan is on the right track, but may need to elaborate for use PHP newbies, when I try this I am returned a green screen no matter what is typed in (I even set this up as an elseif to display a white background if no data is entered in the text field, still green?
There are many problems associated with this, as other have seemed to partially address:
Whether the properties others have mentioned are internal or not, you can still obtain information from them via reflection if permission allows.
var x = obj.GetType().GetProperty("Name", BindingFlags.NonPublic | BindingFlags.Instance);
You could pinvoke Win32 code for Snapshot or you can use WMI which is slower.
HANDLE CreateToolhelp32Snapshot(
DWORD dwFlags,
DWORD th32ProcessID
);
Another option would be to OpenProcess / CloseProcess, but you will still run into the same issues with exceptions being thrown same as before.
For WMI - OnNewEvent.Properties["?"]:
What you're talking about is becoming a payment service provider. I have been there and done that. It was a lot easier about 10 years ago than it is now, but if you have a phenomenal amount of time, money and patience available, it is still possible.
You will need to contact an acquiring bank. You didnt say what region of the world you are in, but by this I dont mean a local bank branch. Each major bank will generally have a separate card acquiring arm. So here in the UK we have (eg) Natwest bank, which uses Streamline (or Worldpay) as its acquiring arm. In total even though we have scores of major banks, they all end up using one of five or so card acquirers.
Happily, all UK card acquirers use a standard protocol for communication of authorisation requests, and end of day settlement. You will find minor quirks where some acquiring banks support some features and have slightly different syntax, but the differences are fairly minor. The UK standards are published by the Association for Payment Clearing Services (APACS) (which is now known as the UKPA). The standards are still commonly referred to as APACS 30 (authorization) and APACS 29 (settlement), but are now formally known as APACS 70 (books 1 through 7).
Although the APACS standard is widely supported across the UK (Amex and Discover accept messages in this format too) it is not used in other countries - each country has it's own - for example: Carte Bancaire in France, CartaSi in Italy, Sistema 4B in Spain, Dankort in Denmark etc. An effort is under way to unify the protocols across Europe - see EPAS.org
Communicating with the acquiring bank can be done a number of ways. Again though, it will depend on your region. In the UK (and most of Europe) we have one communications gateway that provides connectivity to all the major acquirers, they are called TNS and there are dozens of ways of communicating through them to the acquiring bank, from dialup 9600 baud modems, ISDN, HTTPS, VPN or dedicated line. Ultimately the authorisation request will be converted to X25 protocol, which is the protocol used by these acquiring banks when communicating with each other.
In summary then: it all depends on your region.
Once you are registered and accredited you'll then be able to accept customers and set up merchant accounts on behalf of the bank/s you're accredited against (bearing in mind that each acquirer will generally support multiple banks). Rinse and repeat with other acquirers as you see necessary.
Beyond that you have lots of other issues, mainly dealing with PCI-DSS. Thats a whole other topic and there are already some q&a's on this site regarding that. Like I say, its a phenomenal undertaking - most likely a multi-year project even for a reasonably sized team, but its certainly possible.
just had the same question, and answered this way, if this could help.
select *
from table
where start_date between '2012-01-01' and '2012-04-13'
or end_date between '2012-01-01' and '2012-04-13'
I found that HotSpot lists all the VM arguments in the management bean except for -client and -server. Thus, if you infer the -client/-server argument from the VM name and add this to the runtime management bean's list, you get the full list of arguments.
Here's the SSCCE:
import java.util.*;
import java.lang.management.ManagementFactory;
class main {
public static void main(final String[] args) {
System.out.println(fullVMArguments());
}
static String fullVMArguments() {
String name = javaVmName();
return (contains(name, "Server") ? "-server "
: contains(name, "Client") ? "-client " : "")
+ joinWithSpace(vmArguments());
}
static List<String> vmArguments() {
return ManagementFactory.getRuntimeMXBean().getInputArguments();
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static String javaVmName() {
return System.getProperty("java.vm.name");
}
static String joinWithSpace(Collection<String> c) {
return join(" ", c);
}
public static String join(String glue, Iterable<String> strings) {
if (strings == null) return "";
StringBuilder buf = new StringBuilder();
Iterator<String> i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
}
Could be made shorter if you want the arguments in a List<String>
.
Final note: We might also want to extend this to handle the rare case of having spaces within command line arguments.
MY FAVORITE WAY TO DO IT
1. Open info.plist
2. Click this button to add a new key
3. Scroll down to find Privacy - Photo Library Usage Description
4. Select it, then add your description on the right
ajax:
$(document).on('click','#mv_secure_page',function(e) {
var data = $("#m_form1").serialize();
$.ajax({
data: data,
type: "post",
url: "adapter.php",
success: function(data){
alert("Data: " + data);
}
});
});
php code:
<?php
/**
* Created by PhpStorm.
* User: Engg Amjad
* Date: 11/9/16
* Time: 1:28 PM
*/
if(isset($_REQUEST)){
include_once('inc/system.php');
$full_name=$_POST['full_name'];
$business_name=$_POST['business_name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$message=$_POST['message'];
$sql="INSERT INTO mars (f_n,b_n,em,p_n,msg) values('$full_name','$business_name','$email','$phone','$message') ";
$sql_result=mysqli_query($con,$sql);
if($sql_result){
echo "inserted successfully";
}else{
echo "Query failed".mysqli_error($con);
}
}
?>
I use year 2000 instead of Epoch Time in my calculus. Working with smaller numbers is easy to store and transport and is JSON friendly.
Year 2000 was at second 946684800 of epoch time.
Year 2000 was at second 63082281600 from 1-st of Jan 0001.
DateTime.UtcNow Ticks starts from 1-st of Jan 0001
Seconds from year 2000:
DateTime.UtcNow.Ticks/10000000-63082281600
Seconds from Unix Time:
DateTime.UtcNow.Ticks/10000000-946684800
For example year 2020 is:
var year2020 = (new DateTime()).AddYears(2019).Ticks; // Because DateTime starts already at year 1
637134336000000000 Ticks since 1-st of Jan 0001
63713433600 Seconds since 1-st of Jan 0001
1577836800 Seconds since Epoch Time
631152000 Seconds since year 2000
References:
Epoch Time converter: https://www.epochconverter.com
Year 1 converter: https://www.epochconverter.com/seconds-days-since-y0
<properties>
<!-- Use the latest version whenever possible. -->
<jackson.version>2.4.4</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
you have a ObjectMapper (from Jackson Databind package) handy. if so, you can do:
JsonFactory factory = objectMapper.getFactory();
Source: https://github.com/FasterXML/jackson-core
So, the 3 "fasterxml" dependencies which you already have in u'r pom are enough for ObjectMapper as it includes jackson-databind.
OP is asking for a "save" function, which is more than just preserving data across executions of the program (which you must do for the app to be worth anything.)
I recommend saving the data in a file on the sdcard which allows you to not only recall it later, but allows the user to mount the device as an external drive on their own computer and grab the data for use in other places.
So you really need a multi-point system:
1) Implement onSaveInstanceState()
. In this method, you're passed a Bundle, which is basically like a dictionary. Store as much information in the bundle as would be needed to restart the app exactly where it left off. In your onCreate()
method, check for the passed-in bundle to be non-null, and if so, restore the state from the bundle.
2) Implement onPause()
. In this method, create a SharedPreferences editor and use it to save whatever state you need to start the app up next time. This mainly consists of the users' preferences (hence the name), but anything else relavent to the app's start-up state should go here as well. I would not store scores here, just the stuff you need to restart the app. Then, in onCreate()
, whenever there's no bundle object, use the SharedPreferences interface to recall those settings.
3a) As for things like scores, you could follow Mathias's advice above and store the scores in the directory returned in getFilesDir()
, using openFileOutput()
, etc. I think this directory is private to the app and lives in main storage, meaning that other apps and the user would not be able to access the data. If that's ok with you, then this is probably the way to go.
3b) If you do want other apps or the user to have direct access to the data, or if the data is going to be very large, then the sdcard is the way to go. Pick a directory name like com/user1446371/basketballapp/ to avoid collisions with other applications (unless you're sure that your app name is reasonably unique) and create that directory on the sdcard. As Mathias pointed out, you should first confirm that the sdcard is mounted.
File sdcard = Environment.getExternalStorageDirectory();
if( sdcard == null || !sdcard.isDirectory()) {
fail("sdcard not available");
}
File datadir = new File(sdcard, "com/user1446371/basketballapp/");
if( !datadir.exists() && !datadir.mkdirs() ) {
fail("unable to create data directory");
}
if( !datadir.isDirectory() ) {
fail("exists, but is not a directory");
}
// Now use regular java I/O to read and write files to data directory
I recommend simple CSV files for your data, so that other applications can read them easily.
Obviously, you'll have to write activities that allow "save" and "open" dialogs. I generally just make calls to the openintents file manager and let it do the work. This requires that your users install the openintents file manager to make use of these features, however.
When the text is a number with leading zeros, then do: (Cuando el texto es un número que empieza por ceros, hacer)
$objPHPExcel->getActiveSheet()->setCellValueExplicit('A1', $val,PHPExcel_Cell_DataType::TYPE_STRING);
With your example:
<input type="checkbox" id="c2" name="c2" value="DE039230952"/>
Replace $$ with document.querySelectorAll in the examples:
$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230
Use the examples directly with:
const $$ = document.querySelectorAll.bind(document);
Some additions:
$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()
https://superuser.com/questions/749283/change-rstudio-library-path-at-home-directory
Edit ~/.Renviron
R_LIBS_USER=/some/path
Firstly, you start Activities and Services with an intent, you start fragments with fragment transactions. Secondly, your transaction isnt doing anything. Change it to something like:
FragmentTransaction transaction = getFragmentManager();
transaction.beginTransaction()
.replace(R.layout.container, newFragment) //<---replace a view in your layout (id: container) with the newFragment
.commit();
Sometimes plain arrays are preferred to Generic Lists, since they are more convenient (Better performance for costly computation -Numerical Algebra Applications for example, or for exchanging Data with Statistics software like R or Matlab)
In this case you may use the ToArray() method after initiating your List dynamically
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
string[] array = list.ToArray();
Of course, this has sense only if the size of the array is never known nor fixed ex-ante. if you already know the size of your array at some point of the program it is better to initiate it as a fixed length array. (If you retrieve data from a ResultSet for example, you could count its size and initiate an array of that size, dynamically)
If you are interested in getting an array of either numbers or strings, you could define a type that will take an array of either
type Tuple = Array<number | string>
const example: Tuple = [1, "message"]
const example2: Tuple = ["message", 1]
If you expect an array of a specific order (i.e. number and a string)
type Tuple = [number, string]
const example: Tuple = [1, "message"]
const example2: Tuple = ["messsage", 1] // Type 'string' is not assignable to type 'number'.
You need to install gcc-c++
package.
yum install gcc-c++
More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:
Delete this folder after every few days interval. Most of the time, it occupy huge space!
~/Library/Developer/Xcode/DerivedData
All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.
~/Library/Developer/Xcode/Archives
iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.
~/Library/Developer/Xcode/iOS DeviceSupport
Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.
~/Library/Developer/CoreSimulator
(Here's a handy shell command for step 5: xcrun simctl delete unavailable
)
Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!
~/Library/Caches/com.apple.dt.Xcode
Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.
~/Library/Application Support/MobileSync/Backup
Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac
I got back about 40GB!
Assuming you're using Java, you can:
Create a .properties
file in (most commonly) your src/main/resources
directory (but in step 4 you could tell it to look elsewhere).
Set the value of some property in your .properties
file using the standard Maven property for project version:
foo.bar=${project.version}
In your Java code, load the value from the properties file as a resource from the classpath (google for copious examples of how to do this, but here's an example for starters).
In Maven, enable resource filtering. This will cause Maven to copy that file into your output classes and translate the resource during that copy, interpreting the property. You can find some info here but you mostly just do this in your pom:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
You can also get to other standard properties like project.name
, project.description
, or even arbitrary properties you put in your pom <properties>
, etc. Resource filtering, combined with Maven profiles, can give you variable build behavior at build time. When you specify a profile at runtime with -PmyProfile
, that can enable properties that then can show up in your build.
not bad .. but try this one ... (should works for all but ist just -webkit included)
<br>
<input type="text" style="
background: transparent;
border-bottom: 1px solid #B5D5FF;
border-left: 1px solid;
border-right: 1px solid;
border-left-color: #B5D5FF;
border-image: -webkit-linear-gradient(top, #fff 50%, #B5D5FF 0%) 1 repeat;
">
//Feel free to edit and add all other browser..
for (String key : Collections.list(e))
System.out.println(key);
There's a short overview at MinGW-w64 Wiki:
Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?
The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.
The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.
GCC GNU about Exception Handling:
GCC supports two methods for exception handling (EH):
- DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
- A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.
[...]
Structured Exception Handling (SEH)
Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]
See also:
I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.
I'm omitting the com port settings here:
>>>import serial
>>>ser = serial.Serial(5)
>>>ser.close()
>>>ser.open()
>>>ser.write("1".encode())
1
>>>
There's a promising javascript library called Arrive that looks like a great way to start taking advantage of the mutation observers once the browser support becomes commonplace.
JSON in any HTML tag except <script>
tag would be a mere text. Thus it's like you add a story to your HTML page.
However, about formatting, that's another matter. I guess you should change the title of your question.
ToInt32 rounds. Casting to int just throws away the non-integer component.
All these tips will work, but a simpler way might be to include your stylesheet after the Bootstrap styles.
If you include your css (site-specific.css
) after Bootstrap's (bootstrap.css
), you can override rules by redefining them.
For example, if this is how you include CSS in your <head>
<link rel="stylesheet" href="css/bootstrap.css" />
<link rel="stylesheet" href="css/site-specific.css" />
You can simply move the sidebar to the right by writing (in your site-specific.css
file):
.sidebar {
float: right;
}
Forgive the lack of HAML and SASS, I do not know them well enough to write tutorials in them.
Using: IntelliJ IDEA 2017.1.4 Build #IU-171.4694.23
Changing the language level via the Project Settings / Project tab didn't do anything. Instead hitting Alt + Enter and selecting "Set language level to 8 - Lambdas, type annotations etc." and it resolved automatically.
You can use \1
(refer to http://www.grymoire.com/Unix/Sed.html#uh-4):
echo "Hello is a String" | sed 's/Hello\(.*\)String/\1/g'
The contents that is inside the brackets will be stored as \1
.
I'm experiencing some problems using apply() instead commit(). As stated before in other responses, the apply() is asynchronous. I'm getting the problem that the changes formed to a "string set" preference are never written to the persistent memory.
It happens if you "force detention" of the program or, in the ROM that I have installed on my device with Android 4.1, when the process is killed by the system due to memory necessities.
I recommend to use "commit()" instead "apply()" if you want your preferences alive.
Pointing out that all of the Entity Framework < 6.0 suggestions generate some awkward SQL. See second example for "clean" fix.
// comparing against this...
Foo item = ...
return DataModel.Foos.FirstOrDefault(o =>
o.ProductID == item.ProductID
// ridiculous < EF 4.5 nullable comparison workaround http://stackoverflow.com/a/2541042/1037948
&& item.ProductStyleID.HasValue ? o.ProductStyleID == item.ProductStyleID : o.ProductStyleID == null
&& item.MountingID.HasValue ? o.MountingID == item.MountingID : o.MountingID == null
&& item.FrameID.HasValue ? o.FrameID == item.FrameID : o.FrameID == null
&& o.Width == w
&& o.Height == h
);
results in SQL like:
SELECT TOP (1) [Extent1].[ID] AS [ID],
[Extent1].[Name] AS [Name],
[Extent1].[DisplayName] AS [DisplayName],
[Extent1].[ProductID] AS [ProductID],
[Extent1].[ProductStyleID] AS [ProductStyleID],
[Extent1].[MountingID] AS [MountingID],
[Extent1].[Width] AS [Width],
[Extent1].[Height] AS [Height],
[Extent1].[FrameID] AS [FrameID],
FROM [dbo].[Foos] AS [Extent1]
WHERE (CASE
WHEN (([Extent1].[ProductID] = 1 /* @p__linq__0 */)
AND (NULL /* @p__linq__1 */ IS NOT NULL)) THEN
CASE
WHEN ([Extent1].[ProductStyleID] = NULL /* @p__linq__2 */) THEN cast(1 as bit)
WHEN ([Extent1].[ProductStyleID] <> NULL /* @p__linq__2 */) THEN cast(0 as bit)
END
WHEN (([Extent1].[ProductStyleID] IS NULL)
AND (2 /* @p__linq__3 */ IS NOT NULL)) THEN
CASE
WHEN ([Extent1].[MountingID] = 2 /* @p__linq__4 */) THEN cast(1 as bit)
WHEN ([Extent1].[MountingID] <> 2 /* @p__linq__4 */) THEN cast(0 as bit)
END
WHEN (([Extent1].[MountingID] IS NULL)
AND (NULL /* @p__linq__5 */ IS NOT NULL)) THEN
CASE
WHEN ([Extent1].[FrameID] = NULL /* @p__linq__6 */) THEN cast(1 as bit)
WHEN ([Extent1].[FrameID] <> NULL /* @p__linq__6 */) THEN cast(0 as bit)
END
WHEN (([Extent1].[FrameID] IS NULL)
AND ([Extent1].[Width] = 20 /* @p__linq__7 */)
AND ([Extent1].[Height] = 16 /* @p__linq__8 */)) THEN cast(1 as bit)
WHEN (NOT (([Extent1].[FrameID] IS NULL)
AND ([Extent1].[Width] = 20 /* @p__linq__7 */)
AND ([Extent1].[Height] = 16 /* @p__linq__8 */))) THEN cast(0 as bit)
END) = 1
If you want to generate cleaner SQL, something like:
// outrageous < EF 4.5 nullable comparison workaround http://stackoverflow.com/a/2541042/1037948
Expression<Func<Foo, bool>> filterProductStyle, filterMounting, filterFrame;
if(item.ProductStyleID.HasValue) filterProductStyle = o => o.ProductStyleID == item.ProductStyleID;
else filterProductStyle = o => o.ProductStyleID == null;
if (item.MountingID.HasValue) filterMounting = o => o.MountingID == item.MountingID;
else filterMounting = o => o.MountingID == null;
if (item.FrameID.HasValue) filterFrame = o => o.FrameID == item.FrameID;
else filterFrame = o => o.FrameID == null;
return DataModel.Foos.Where(o =>
o.ProductID == item.ProductID
&& o.Width == w
&& o.Height == h
)
// continue the outrageous workaround for proper sql
.Where(filterProductStyle)
.Where(filterMounting)
.Where(filterFrame)
.FirstOrDefault()
;
results in what you wanted in the first place:
SELECT TOP (1) [Extent1].[ID] AS [ID],
[Extent1].[Name] AS [Name],
[Extent1].[DisplayName] AS [DisplayName],
[Extent1].[ProductID] AS [ProductID],
[Extent1].[ProductStyleID] AS [ProductStyleID],
[Extent1].[MountingID] AS [MountingID],
[Extent1].[Width] AS [Width],
[Extent1].[Height] AS [Height],
[Extent1].[FrameID] AS [FrameID],
FROM [dbo].[Foos] AS [Extent1]
WHERE ([Extent1].[ProductID] = 1 /* @p__linq__0 */)
AND ([Extent1].[Width] = 16 /* @p__linq__1 */)
AND ([Extent1].[Height] = 20 /* @p__linq__2 */)
AND ([Extent1].[ProductStyleID] IS NULL)
AND ([Extent1].[MountingID] = 2 /* @p__linq__3 */)
AND ([Extent1].[FrameID] IS NULL)
I don't think you can "legally" load only part of an XML file, since then it would be malformed (there would be a missing closing element somewhere).
Using LINQ-to-XML, you can do var doc = XDocument.Load("yourfilepath")
. From there its just a matter of querying the data you want, say like this:
var authors = doc.Root.Elements().Select( x => x.Element("Author") );
HTH.
EDIT:
Okay, just to make this a better sample, try this (with @JWL_'s suggested improvement):
using System;
using System.Xml.Linq;
namespace ConsoleApplication1 {
class Program {
static void Main( string[] args ) {
XDocument doc = XDocument.Load( "XMLFile1.xml" );
var authors = doc.Descendants( "Author" );
foreach ( var author in authors ) {
Console.WriteLine( author.Value );
}
Console.ReadLine();
}
}
}
You will need to adjust the path in XDocument.Load()
to point to your XML file, but the rest should work. Ask questions about which parts you don't understand.
I got this error when the chrome driver was not closed properly. Eg, if I try to find something and click it and it doesn't exist, the driver throws an exception and the thread ended there ( I did not close the driver ).
So, when I ran the same method again later where I had to reinitialize the driver, the driver didn't initialize and it threw the exception.
My solve was simply to wrap the selenium tasks in a try catch and close the driver properly
This problem has finally been fixed in Java 9: https://docs.oracle.com/javase/9/intl/internationalization-enhancements-jdk-9
Default encoding for properties files is now UTF-8.
Most existing properties files should not be affected: UTF-8 and ISO-8859-1 have the same encoding for ASCII characters, and human-readable non-ASCII ISO-8859-1 encoding is not valid UTF-8. If an invalid UTF-8 byte sequence is detected, the Java runtime automatically rereads the file in ISO-8859-1.
Note that you can also combine the two, which is pretty cool (although it looks a bit odd):
// simple interpolated verbatim string
WriteLine($@"Path ""C:\Windows\{file}"" not found.");
I feel like properties are about letting you get the overhead of writing getters and setters only when you actually need them.
Java Programming culture strongly advise to never give access to properties, and instead, go through getters and setters, and only those which are actually needed. It's a bit verbose to always write these obvious pieces of code, and notice that 70% of the time they are never replaced by some non-trivial logic.
In Python, people actually care for that kind of overhead, so that you can embrace the following practice :
@property
to implement them without changing the syntax of the rest of your code.I think there are two issues:
Explanation:
I checked one of mine, I have the pattern:
<a href="file://///server01\fshare\dir1\dir2\dir3">useful link </a>
Please note that we ended up with 5 slashes after the protocol (file:
)
Firefox will try to prevent cross site scripting. My solution was to modify prefs.js in the profile directory. You will add two lines:
user_pref("capability.policy.localfilelinks.checkloaduri.enabled", "allAccess");
user_pref("capability.policy.localfilelinks.sites", "http://mysite.company.org");
That's the easiest I could think of (TESTED) and it works!!
char message[50];
fgets(message, 50, stdin);
for( i = 0, j = 0; i < strlen(message); i++){
message[i-j] = message[i];
if(message[i] == ' ')
j++;
}
message[i] = '\0';
One way to do this is to insert a dummy column with the sums in order to sort:
In [10]: sum_B_over_A = df.groupby('A').sum().B
In [11]: sum_B_over_A
Out[11]:
A
bar 0.253652
baz -2.829711
foo 0.551376
Name: B
in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)
In [13]: df
Out[13]:
A B C sum_B_over_A
0 foo 1.624345 False 0.551376
1 bar -0.611756 True 0.253652
2 baz -0.528172 False -2.829711
3 foo -1.072969 True 0.551376
4 bar 0.865408 False 0.253652
5 baz -2.301539 True -2.829711
In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]:
A B C sum_B_over_A
5 baz -2.301539 True -2.829711
2 baz -0.528172 False -2.829711
1 bar -0.611756 True 0.253652
4 bar 0.865408 False 0.253652
3 foo -1.072969 True 0.551376
0 foo 1.624345 False 0.551376
and maybe you would drop the dummy row:
In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
Here are more approaches for doing this by using numpy.ravel()
, numpy.array()
, utilizing the fact that 1D arrays can be unpacked into plain elements:
# we'll utilize the concept of unpacking
In [15]: (*a, *b)
Out[15]: (1, 2, 3, 5, 6)
# using `numpy.ravel()`
In [14]: np.ravel((*a, *b))
Out[14]: array([1, 2, 3, 5, 6])
# wrap the unpacked elements in `numpy.array()`
In [16]: np.array((*a, *b))
Out[16]: array([1, 2, 3, 5, 6])
PHP stores error logs in /var/log/apache2
if PHP is an apache2 module.
Shared hosts are often storing log files in your root directory /log
subfolder.
But...if you have access to a php.ini
file you can do this:
error_log = /var/log/php-scripts.log
According to rinogo's comment: If you're using cPanel, the master log file you're probably looking for is stored (by default) at
/usr/local/apache/logs/error_log
If all else fails you can check the location of the log file using
<?php phpinfo(); ?>
Given that commonly 1 = true
and 0 = false
, all you need to do is count the number of rows, and cast to a boolean
.
Hence, your posted code only needs a COUNT()
function added:
SELECT CAST(COUNT(1) AS BIT) AS Expr1
FROM [User]
WHERE (UserID = 20070022)
I would write my own util class with the method like below
public class NumberFormatUtils {
public static String longToBinString(long val) {
char[] buffer = new char[64];
Arrays.fill(buffer, '0');
for (int i = 0; i < 64; ++i) {
long mask = 1L << i;
if ((val & mask) == mask) {
buffer[63 - i] = '1';
}
}
return new String(buffer);
}
public static void main(String... args) {
long value = 0b0000000000000000000000000000000000000000000000000000000000000101L;
System.out.println(value);
System.out.println(Long.toBinaryString(value));
System.out.println(NumberFormatUtils.longToBinString(value));
}
}
Output:
5 101 0000000000000000000000000000000000000000000000000000000000000101
The same approach could be applied to any integral types. Pay attention to the type of mask
long mask = 1L << i;
I think the usual use case is to call it when no exception was thrown in a negative test.
Something like the following pseudo-code:
test_addNilThrowsNullPointerException()
{
try {
foo.add(NIL); // we expect a NullPointerException here
fail("No NullPointerException"); // cause the test to fail if we reach this
} catch (NullNullPointerException e) {
// OK got the expected exception
}
}
Having just struggled with this - I'll explain my situation.
I have my tabs within a bootstrap modal and set the following on load (pre the modal being triggered):
$('#subMenu li:first-child a').tab('show');
Whilst the tab was selected the actual pane wasn't visible. As such you need to add active
class to the pane as well:
$('#profile').addClass('active');
In my case the pane had #profile
(but this could have easily been .pane:first-child
) which then displayed the correct pane.
Calculating AUC with Metrics package is very easy and straightforward:
library(Metrics)
actual <- c(0, 0, 1, 1)
predicted <- c(.1, .3, .3, .9)
auc(actual, predicted)
0.875
below command worked in my debain 10
box!
root@debian:/home/arun# readlink -f $(which java)
/usr/lib/jvm/java-11-openjdk-amd64/bin/java
Simply speaking, closure is a trick about scope, lambda is an anonymous function. We can realize closure with lambda more elegantly and lambda is often used as a parameter passed to a higher function
As far as I can remember, the first versions of C only allowed to return a value that could fit into a processor register, which means that you could only return a pointer to a struct. The same restriction applied to function arguments.
More recent versions allow to pass around larger data objects like structs. I think this feature was already common during the eighties or early nineties.
Arrays, however, can still be passed and returned only as pointers.
Select * from
(
Select ROW_NUMBER() OVER ( order by Id) as 'Row_Number', *
from tbl_Contact_Us
) as tbl
Where tbl.Row_Number = 5
super late entry but GAAP is a good rule of thumb..
If your application needs to handle money values up to a trillion then this should work: 13,2 If you need to comply with GAAP (Generally Accepted Accounting Principles) then use: 13,4
Usually you should sum your money values at 13,4 before rounding of the output to 13,2.
Assuming there are a few ignore directories, why not use "git status node/logs/" which will tell you what files are to be added? In the directory I have a text file that is not part of status output, e.g.:
On branch master
Your branch is up-to-date with 'origin/master'.
Untracked files:
(use "git add ..." to include in what will be committed)
node/logs/.gitignore
.gitignore is:
*
!.gitignore
In my case, I was creating an object declared and initialized together. I just initialized in the constructor or what you can initialize the object when required.
For me the shortest and my favorite oneliner for accessing to the parent directory is:
sys.path.append(os.path.dirname(os.getcwd()))
or:
sys.path.insert(1, os.path.dirname(os.getcwd()))
os.getcwd() returns the name of the current working directory, os.path.dirname(directory_name) returns the directory name for the passed one.
Actually, in my opinion Python project architecture should be done the way where no one module from child directory will use any module from the parent directory. If something like this happens it is worth to rethink about the project tree.
Another way is to add parent directory to PYTHONPATH system environment variable.
I would go with the file system approach. As noted by a few others, most web servers are built to send images from a file path. You'll have much higher performance if you don't have to write or stream out BLOB fields from the database. Having filesystem storage for the images makes it easier to setup static pages when the content isn't changing or you want limit the load on the database.
My Favourite Method is to create a clearfix class in my css / scss document as below
.clearfix{
clear:both
}
And then call it in my html document as shown below
<html>
<div class="div-number-one">
Some Content before the clearfix
</div>
<!-- Let's say we need to clearfix Here between these two divs --->
<div class="clearfix"></div>
<div class="div-number-two">
Some more content after the clearfix
</div>
</html>
Use the wc utility with the print the byte counts (-c
) option:
$ SO="stackoverflow"
$ echo -n "$SO" | wc -c
13
You'll have to use the do not output the trailing newline (-n
) option for echo
. Otherwise, the newline character will also be counted.
To activate the installRelease
task, you simply need a signingConfig
. That is all.
From http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Android-tasks:
Finally, the plugin creates install/uninstall tasks for all build types (debug, release, test), as long as they can be installed (which requires signing).
Install tasks
-------------
installDebug - Installs the Debug build
installDebugTest - Installs the Test build for the Debug build
installRelease - Installs the Release build
uninstallAll - Uninstall all applications.
uninstallDebug - Uninstalls the Debug build
uninstallDebugTest - Uninstalls the Test build for the Debug build
uninstallRelease - Uninstalls the Release build <--- release
installRelease
task:Example build.gradle
:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.3'
}
}
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion '22.0.1'
defaultConfig {
applicationId 'demo'
minSdkVersion 15
targetSdkVersion 22
versionCode 1
versionName '1.0'
}
signingConfigs {
release {
storeFile <file>
storePassword <password>
keyAlias <alias>
keyPassword <password>
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
}
This function is using yield:
function a($items) {
foreach ($items as $item) {
yield $item + 1;
}
}
It is almost the same as this one without:
function b($items) {
$result = [];
foreach ($items as $item) {
$result[] = $item + 1;
}
return $result;
}
The only one difference is that a()
returns a generator and b()
just a simple array. You can iterate on both.
Also, the first one does not allocate a full array and is therefore less memory-demanding.
This is more narrowly-tailored. When I do this I usually have a comma-delimited list of unique ids (INT or BIGINT), which I want to cast as a table to use as an inner join to another table that has a primary key of INT or BIGINT. I want an in-line table-valued function returned so that I have the most efficient join possible.
Sample usage would be:
DECLARE @IDs VARCHAR(1000);
SET @IDs = ',99,206,124,8967,1,7,3,45234,2,889,987979,';
SELECT me.Value
FROM dbo.MyEnum me
INNER JOIN dbo.GetIntIdsTableFromDelimitedString(@IDs) ids ON me.PrimaryKey = ids.ID
I stole the idea from http://sqlrecords.blogspot.com/2012/11/converting-delimited-list-to-table.html, changing it to be in-line table-valued and cast as INT.
create function dbo.GetIntIDTableFromDelimitedString
(
@IDs VARCHAR(1000) --this parameter must start and end with a comma, eg ',123,456,'
--all items in list must be perfectly formatted or function will error
)
RETURNS TABLE AS
RETURN
SELECT
CAST(SUBSTRING(@IDs,Nums.number + 1,CHARINDEX(',',@IDs,(Nums.number+2)) - Nums.number - 1) AS INT) AS ID
FROM
[master].[dbo].[spt_values] Nums
WHERE Nums.Type = 'P'
AND Nums.number BETWEEN 1 AND DATALENGTH(@IDs)
AND SUBSTRING(@IDs,Nums.number,1) = ','
AND CHARINDEX(',',@IDs,(Nums.number+1)) > Nums.number;
GO
It's not difficult and actually documented:
import youtube_dl
ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s.%(ext)s'})
with ydl:
result = ydl.extract_info(
'http://www.youtube.com/watch?v=BaW_jenozKc',
download=False # We just want to extract the info
)
if 'entries' in result:
# Can be a playlist or a list of videos
video = result['entries'][0]
else:
# Just a video
video = result
print(video)
video_url = video['url']
print(video_url)
On button click you can try the following.
protected void button1_Click(object sender, EventArgs e)
{
Response.Redirect("~/Admin/Admin.aspx");
}
And on PageLoad you can check whether the loading is coming from that button then increase the count.
protected void Page_Load(object sender, EventArgs e)
{
StackTrace stackTrace = new StackTrace();
string eventName = stackTrace.GetFrame(1).GetMethod().Name; // this will the event name.
if (eventName == "button1_Click")
{
// code to increase the count;
}
}
Thanks
Why don't you just type:
seachstr
In the terminal.
The shell will say somehing like
seacrhstr: command not found
EDIT:
Ok, I take the downvote, because the answer is stupid, I just want to know: What's wrong with this answer!!! The asker said:
and see if a command is available.
Typing the command will tell you if it is available!.
Probably he/she meant "with out executing the command" or "to include it in a script" but I cannot read his mind ( is not that I can't regularly it is just that he's wearing a mind reading deflector )
Because of old version I got this error. Then I changed to this version n error gone Using maven my pom.xml
<properties>
...
<jackson.version>2.5.2</jackson.version>
</properties>
<dependencies>
...
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
my old version was '2.2.3'
If both strings are of the same known locale, you may want to use Intl.Collator
object like this:
function equalIgnoreCase(s1: string, s2: string) {
return new Intl.Collator("en-US", { sensitivity: "base" }).compare(s1, s2) === 0;
}
Obviously, you may want to cache the Collator
for better efficiency.
The advantages of this approach is that it should be much faster than using RegExps and is based on an extremely customizable (see description of locales
and options
constructor parameters in the article above) set of ready-to-use collators.
You can use any selector with not
p:not(:first-child){}
p:not(:first-of-type){}
p:not(:checked){}
p:not(:last-child){}
p:not(:last-of-type){}
p:not(:first-of-type){}
p:not(:nth-last-of-type(2)){}
p:not(nth-last-child(2)){}
p:not(:nth-child(2)){}
When working with Swift, you can use the enum
UIUserInterfaceIdiom
, defined as:
enum UIUserInterfaceIdiom : Int {
case unspecified
case phone // iPhone and iPod touch style UI
case pad // iPad style UI (also includes macOS Catalyst)
}
So you can use it as:
UIDevice.current.userInterfaceIdiom == .pad
UIDevice.current.userInterfaceIdiom == .phone
UIDevice.current.userInterfaceIdiom == .unspecified
Or with a Switch statement:
switch UIDevice.current.userInterfaceIdiom {
case .phone:
// It's an iPhone
case .pad:
// It's an iPad (or macOS Catalyst)
@unknown default:
// Uh, oh! What could it be?
}
UI_USER_INTERFACE_IDIOM()
is an Objective-C macro, which is defined as:
#define UI_USER_INTERFACE_IDIOM() \ ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? \ [[UIDevice currentDevice] userInterfaceIdiom] : \ UIUserInterfaceIdiomPhone)
Also, note that even when working with Objective-C, the UI_USER_INTERFACE_IDIOM()
macro is only required when targeting iOS 3.2 and below. When deploying to iOS 3.2 and up, you can use [UIDevice userInterfaceIdiom]
directly.
To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all')
. It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.
More simply, this is what works for me:
MY_DIR=`dirname $0`
source $MY_DIR/_inc_db.sh
As explained in below code: Execute below queries and verify yourself.
CREATE TABLE `table_name` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`tele` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
Insert a record:
INSERT INTO table_name (name, address, tele)
SELECT * FROM (SELECT 'Nazir', 'Kolkata', '033') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_name WHERE name = 'Nazir'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `table_name`;
+----+--------+-----------+------+
| id | name | address | tele |
+----+--------+-----------+------+
| 1 | Nazir | Kolkata | 033 |
+----+--------+-----------+------+
Now, try to insert the same record again:
INSERT INTO table_name (name, address, tele)
SELECT * FROM (SELECT 'Nazir', 'Kolkata', '033') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_name WHERE name = 'Nazir'
) LIMIT 1;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
+----+--------+-----------+------+
| id | name | address | tele |
+----+--------+-----------+------+
| 1 | Nazir | Kolkata | 033 |
+----+--------+-----------+------+
Insert a different record:
INSERT INTO table_name (name, address, tele)
SELECT * FROM (SELECT 'Santosh', 'Kestopur', '044') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_name WHERE name = 'Santosh'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `table_name`;
+----+--------+-----------+------+
| id | name | address | tele |
+----+--------+-----------+------+
| 1 | Nazir | Kolkata | 033 |
| 2 | Santosh| Kestopur | 044 |
+----+--------+-----------+------+
Just in case you want to store the selected values in single column seperated by ,
then you can use below approach
string selectedItems = String.Join(",", CBLGold.Items.OfType<ListItem>().Where(r => r.Selected).Select(r => r.Value));
if you want to store Text not values then Change the r.Value to r.Text
This means that you must declare strict mode by writing "use strict"
at the beginning of the file or the function to use block-scope declarations.
EX:
function test(){
"use strict";
let a = 1;
}
As the more recent MySQL documentation on view restrictions says:
Before MySQL 5.7.7, subqueries cannot be used in the FROM clause of a view.
This means, that choosing a MySQL v5.7.7 or newer or upgrading the existing MySQL instance to such a version, would remove this restriction on views completely.
However, if you have a current production MySQL version that is earlier than v5.7.7, then the removal of this restriction on views should only be one of the criteria being assessed while making a decision as to upgrade or not. Using the workaround techniques described in the other answers may be a more viable solution - at least on the shorter run.
There's a super small section in the DOCs that shows how to find/find_all direct children.
https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-recursive-argument
In your case as you want link1 which is first direct child:
# for only first direct child
soup.find("li", { "class" : "test" }).find("a", recursive=False)
If you want all direct children:
# for all direct children
soup.find("li", { "class" : "test" }).findAll("a", recursive=False)
Here's some options that keep the file self-contained without retastering the image:
div
tags<div style="width:300px; height:200px">
![Image](path/to/image)
</div>
---
title: test
output: html_document
css: test.css
---
## Page with an image {#myImagePage}
![Image](path/to/image)
#myImagePage img {
width: 400px;
height: 200px;
}
If you have more than one image you might need to use the nth-child pseudo-selector for this second option.
In my case after files with names containing those characters were uploaded, they were not even visible with Filezilla! In Cpanel filemanager they were shown with ? (under black background). And this combination made it shown correctly on the browser (HTML document is Western-encoded):
$dspFileName = utf8_decode(htmlspecialchars(iconv(mb_internal_encoding(), 'utf-8', basename($thisFile['path']))) );
If you really want to generate a debug APK (for testing purpose) that can run without the development server, Here is the link to my answer to another similar post which may help you.
https://stackoverflow.com/a/65762142/7755579
All you've to do is:
android/app/build.gradle
project.ext.react = [
...
bundleInDebug: true, // add this line
]
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
gradlew assembleDebug
inside /android
folderIn my first gson application I avoided using additional classes to catch values mainly because I use json for config matters
despite the lack of information (even gson page), that's what I found and used:
starting from
Map jsonJavaRootObject = new Gson().fromJson("{/*whatever your mega complex object*/}", Map.class)
Each time gson sees a {}, it creates a Map (actually a gson StringMap )
Each time gson sees a '', it creates a String
Each time gson sees a number, it creates a Double
Each time gson sees a [], it creates an ArrayList
You can use this facts (combined) to your advantage
Finally this is the code that makes the thing
Map<String, Object> javaRootMapObject = new Gson().fromJson(jsonLine, Map.class);
System.out.println(
(
(Map)
(
(List)
(
(Map)
(
javaRootMapObject.get("data")
)
).get("translations")
).get(0)
).get("translatedText")
);
select @@servername
i find that this works for me
db.getCollection('collectionName').findOne({"fieldName" : {$ne: null}})
I think a more reliable way of closing a connection is to tell the sever explicitly to close it in a way compliant with HTTP specification:
HTTP/1.1 defines the "close" connection option for the sender to signal that the connection will be closed after completion of the response. For example,
Connection: close
in either the request or the response header fields indicates that the connection SHOULD NOT be considered `persistent' (section 8.1) after the current request/response is complete.
The Connection: close
header is added to the actual request:
r = requests.post(url=url, data=body, headers={'Connection':'close'})
This code sums both the variables! Put it into your function
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = (y +z);
document.getElementById("demo").innerHTML = x;`
It hides the intention of the code.
It's two single tilde operators, so it does a bitwise complement (bitwise not) twice. The operations take out each other, so the only remaining effect is the conversion that is done before the first operator is applied, i.e. converting the value to an integer number.
Some use it as a faster alternative to Math.floor
, but the speed difference is not that dramatic, and in most cases it's just micro optimisation. Unless you have a piece of code that really needs to be optimised, you should use code that descibes what it does instead of code that uses a side effect of a non-operation.
With optimisation of the JavaScript engine in browsers, the performance for operators and functions change. With current browsers, using ~~
instead of Math.floor
is somewhat faster in some browsers, and not faster at all in some browsers. If you really need that extra bit of performance, you would need to write different optimised code for each browser.
See: tilde vs floor
This is one example where using prepared statements really saves you some trouble.
In MySQL, in order to insert a null value, you must specify it at INSERT
time or leave the field out which requires additional branching:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', NULL);
However, if you want to insert a value in that field, you must now branch your code to add the single quotes:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', 'String Value');
Prepared statements automatically do that for you. They know the difference between string(0) ""
and null
and write your query appropriately:
$stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)");
$stmt->bind_param('ss', $field1, $field2);
$field1 = "String Value";
$field2 = null;
$stmt->execute();
It escapes your fields for you, makes sure that you don't forget to bind a parameter. There is no reason to stay with the mysql
extension. Use mysqli
and it's prepared statements instead. You'll save yourself a world of pain.
The Python standard library comes with an e-mail parsing function: email.utils.parseaddr()
.
It returns a two-tuple containing the real name and the actual address parts of the e-mail:
>>> from email.utils import parseaddr
>>> parseaddr('[email protected]')
('', '[email protected]')
>>> parseaddr('Full Name <[email protected]>')
('Full Name', '[email protected]')
>>> parseaddr('"Full Name with quotes and <[email protected]>" <[email protected]>')
('Full Name with quotes and <[email protected]>', '[email protected]')
And if the parsing is unsuccessful, it returns a two-tuple of empty strings:
>>> parseaddr('[invalid!email]')
('', '')
An issue with this parser is that it's accepting of anything that is considered as a valid e-mail address for RFC-822 and friends, including many things that are clearly not addressable on the wide Internet:
>>> parseaddr('invalid@example,com') # notice the comma
('', 'invalid@example')
>>> parseaddr('invalid-email')
('', 'invalid-email')
So, as @TokenMacGuy put it, the only definitive way of checking an e-mail address is to send an e-mail to the expected address and wait for the user to act on the information inside the message.
However, you might want to check for, at least, the presence of an @-sign on the second tuple element, as @bvukelic suggests:
>>> '@' in parseaddr("invalid-email")[1]
False
If you want to go a step further, you can install the dnspython project and resolve the mail servers for the e-mail domain (the part after the '@'), only trying to send an e-mail if there are actual MX
servers:
>>> from dns.resolver import query
>>> domain = 'foo@[email protected]'.rsplit('@', 1)[-1]
>>> bool(query(domain, 'MX'))
True
>>> query('example.com', 'MX')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
[...]
dns.resolver.NoAnswer
>>> query('not-a-domain', 'MX')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
[...]
dns.resolver.NXDOMAIN
You can catch both NoAnswer
and NXDOMAIN
by catching dns.exception.DNSException
.
And Yes, foo@[email protected]
is a syntactically valid address. Only the last @
should be considered for detecting where the domain part starts.
As @user786653 suggested, use the xxd(1)
program:
xxd -r -p input.txt output.bin
Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.
In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:
CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
one int;
two int;
BEGIN
one := 1;
two := 2;
RETURN one + two;
END
$$;
SELECT somefuncname();
The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.
An explanation of why the approach in the question doesn't work:
let products = [
{ name: "laptop", price: 800 },
{ name: "phone", price:200},
{ name: "tv", price: 1200}
];
products.sort( (a, b) => {
{let value= a.name - b.name; console.log(value); return value}
});
> 2 NaN
Subtraction between strings returns NaN.
Echoing @Alejadro's answer, the right approach is--
products.sort( (a,b) => a.name > b.name ? 1 : -1 )
After reading the w3.org spec. I found the sandbox property.
You can set sandbox=""
, which prevents the iframe from redirecting. That being said it won't redirect the iframe either. You will lose the click essentially.
Example here: http://jsfiddle.net/ppkzS/1/
Example without sandbox: http://jsfiddle.net/ppkzS/
I had to:
\\127.0.0.1\SSRSFileShare
simply copy and paste the image into res>drawable and it ask you destination folder which you want to pate resolution image for more help please look for Android Studio drawable folders
I recomend use this code for stable work, it optimized for nested fragments in tab (for example nested MapFragment) and tested on "do not keep activities": https://stackoverflow.com/a/23150258/2765497
If you are not seeing the certificate under General->About->Certificate Trust Settings, then you probably do not have the ROOT CA installed. Very important -- needs to be a ROOT CA, not an intermediary CA.
I just answered a question here explaining how to obtain the ROOT CA and get things to show up: How to install self-signed certificates in iOS 11
Same problem for me today, with "ARCHIVE FAILED". None of the solutions above worked for me, but watching closer, the error refers the path of module cordova-plugin-inappbrowser, so i removed the plugin, then added it again, and it finally works...
ionic cordova plugin remove cordova-plugin-inappbrowser
ionic cordova plugin add cordova-plugin-inappbrowser
stack :
Ionic cli 6.2.2
Ionic1 1.3.2
Cordova cli 9.0.0
Cordova platform ios 5.1.1
cordova-plugin-inappbrowser 3.2.0
If you really mean small caps, then no, that is not possible – just as it isn’t possible to convert text to bold or italic in any text editor (as opposed to word processor). If you want to convert text to lowercase, create a visual block and press u
(or U
to convert to uppercase). Tilde (~
) in command mode reverses case of the character under the cursor.
If you want to see all text in Vim in small caps, you might want to look at the guifont
option, or type :set guifont=*
if your Vim flavour supports GUI font chooser.
My program with two arguments, args[0] and args[1]:
public static void main(String[] args) throws Exception {
System.out.println(args);
String host = args[0];
System.out.println(host);
int port = Integer.parseInt(args[1]);
my build.gradle
run {
if ( project.hasProperty("appArgsWhatEverIWant") ) {
args Eval.me(appArgsWhatEverIWant)
}
}
my terminal prompt:
gradle run -PappArgsWhatEverIWant="['localhost','8080']"
First of all, you would have to allocate memory:
char * S = new char[R.length() + 1];
then you can use strcpy
with S
and R.c_str()
:
std::strcpy(S,R.c_str());
You can also use R.c_str()
if the string doesn't get changed or the c string is only used once. However, if S
is going to be modified, you should copy the string, as writing to R.c_str()
results in undefined behavior.
Note: Instead of strcpy
you can also use str::copy
.
As cephus mentioned android:drawablePadding
will only force padding between the text and the drawable if the button is small enough.
When laying out larger buttons you can use android:drawablePadding
in conjunction with android:paddingLeft
and android:paddingRight
to force the text and drawable inward towards the center of the button. By adjusting the left and right padding separately you can make very detailed adjustments to the layout.
Here's an example button that uses padding to push the text and icon closer together than they would be by default:
<Button android:text="@string/button_label"
android:id="@+id/buttonId"
android:layout_width="160dip"
android:layout_height="60dip"
android:layout_gravity="center"
android:textSize="13dip"
android:drawableLeft="@drawable/button_icon"
android:drawablePadding="2dip"
android:paddingLeft="30dip"
android:paddingRight="26dip"
android:singleLine="true"
android:gravity="center" />
Optional.map()
:Takes every element and if the value exists, it is passed to the function:
Optional<T> optionalValue = ...;
Optional<Boolean> added = optionalValue.map(results::add);
Now added has one of three values: true
or false
wrapped into an Optional , if optionalValue
was present, or an empty Optional otherwise.
If you don't need to process the result you can simply use ifPresent()
, it doesn't have return value:
optionalValue.ifPresent(results::add);
Optional.flatMap()
:Works similar to the same method of streams. Flattens out the stream of streams. With the difference that if the value is presented it is applied to function. Otherwise, an empty optional is returned.
You can use it for composing optional value functions calls.
Suppose we have methods:
public static Optional<Double> inverse(Double x) {
return x == 0 ? Optional.empty() : Optional.of(1 / x);
}
public static Optional<Double> squareRoot(Double x) {
return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
}
Then you can compute the square root of the inverse, like:
Optional<Double> result = inverse(-4.0).flatMap(MyMath::squareRoot);
or, if you prefer:
Optional<Double> result = Optional.of(-4.0).flatMap(MyMath::inverse).flatMap(MyMath::squareRoot);
If either the inverse()
or the squareRoot()
returns Optional.empty()
, the result is empty.
Enabling Access to External Schema
You need to enable the IDE and the GlassFish Server to access external schema to parse the WSDL file of the web service. To enable access you need to modify the configuration files of the IDE and the GlassFish Server. For more details, see the FAQ How to enable parsing of WSDL with an external schema? Configuring the IDE
To generate a web service client in the IDE from a web service or WSDL file you need to modify the IDE configuration file (netbeans.conf) to add the following switch to netbeans_default_options.
-J-Djavax.xml.accessExternalSchema=all
For more about locating and modifying the netbeans.conf configuration file, see Netbeans Conf FAQ. Configuring the GlassFish Server
If you are deploying to the GlassFish Server you need to modify the configuration file of the GlassFish Server (domain.xml) to enable the server to access external schemas to parse the wsdl file and generate the test client. To enable access to external schemas, open the GlassFish configuration file (GLASSFISH_INSTALL/glassfish/domains/domain1/config/domain.xml) and add the following JVM option element (in bold). You will need to restart the server for the change to take effect.
</java-config>
...
<jvm-options>-Djavax.xml.accessExternalSchema=all</jvm-options>
</java-config>
Yes by using spring-boot with hibernate configuration files we can persist the data to the database. keep hibernating .cfg.xml in your src/main/resources folder for reading the configurations related to database.
Because that syntax simply isn't defined? Besides, x < y
evaluates as a bool, so what does bool < int
mean? It isn't really an overhead; besides, you could write a utility method if you really want - isBetween(10,x,20)
- I wouldn't myself, but hey...
I ended up with this because other answers either lose resolution or work with UIImageView, not UIImage, or contain unnecessary actions:
Swift 3
extension UIImage {
public func mask(with color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context = UIGraphicsGetCurrentContext()!
let rect = CGRect(origin: CGPoint.zero, size: size)
color.setFill()
self.draw(in: rect)
context.setBlendMode(.sourceIn)
context.fill(rect)
let resultImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return resultImage
}
}