Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.
When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.
An example of a DATE subtraction resulting in a positive integer difference:
select date '2009-08-07' - date '2008-08-08' from dual;
Results in:
DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
364
select dump(date '2009-08-07' - date '2008-08-08') from dual;
DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0
Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.
An example of a DATE subtraction resulting in a negative integer difference:
select date '1000-08-07' - date '2008-08-08' from dual;
Results in:
DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
-368160
select dump(date '1000-08-07' - date '2008-08-08') from dual;
DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0
Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.
An example of a DATE subtraction resulting in a decimal difference:
select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;
TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
.25
The difference between those 2 dates is 0.25 days or 6 hours.
select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;
DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0
Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.
Hope this helps anyone who was wondering how a DATE subtraction is actually stored.
You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:
SQL> SELECT DUMP(SYSDATE - start_date) from test;
DUMP(SYSDATE-START_DATE)
--------------------------------------
Typ=14 Len=8: 188,10,0,0,223,65,1,0
You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function
For example:
SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;
(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000
SQL> SELECT (SYSDATE - start_date) from test;
(SYSDATE-START_DATE)
--------------------
2748.9515
SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;
NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000
SQL>
Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.
This, works for me:
var getBaseUrl = function (url) {_x000D_
if (url) {_x000D_
var parts = url.split('://');_x000D_
_x000D_
if (parts.length > 1) {_x000D_
return parts[0] + '://' + parts[1].split('/')[0] + '/';_x000D_
} else {_x000D_
return parts[0].split('/')[0] + '/';_x000D_
}_x000D_
}_x000D_
};
_x000D_
You could do below:
select
iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20,
iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30,
iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40,
50 ) ) ) as commission
from table
Add the following CSS;
.modal .modal-dialog .modal-content{ background-color: #d4c484; }
<div class="modal fade">
<div class="modal-dialog" role="document">
<div class="modal-content">
...
...
if you want capitalize each word from string (in progress -> In Progress), you can use array like this.
.filter('capitalize', function() {
return function(input) {
return (!!input) ? input.split(' ').map(function(wrd){return wrd.charAt(0).toUpperCase() + wrd.substr(1).toLowerCase();}).join(' ') : '';
}
});
Try this:
String sMillis = "10997195233";
double dMillis = 0;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
int millis = 0;
String sTime;
try {
dMillis = Double.parseDouble(sMillis);
} catch (Exception e) {
System.out.println(e.getMessage());
}
seconds = (int)(dMillis / 1000) % 60;
millis = (int)(dMillis % 1000);
if (seconds > 0) {
minutes = (int)(dMillis / 1000 / 60) % 60;
if (minutes > 0) {
hours = (int)(dMillis / 1000 / 60 / 60) % 24;
if (hours > 0) {
days = (int)(dMillis / 1000 / 60 / 60 / 24);
if (days > 0) {
sTime = days + " days " + hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
} else {
sTime = hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
}
} else {
sTime = minutes + " min " + seconds + " sec " + millis + " millisec";
}
} else {
sTime = seconds + " sec " + millis + " millisec";
}
} else {
sTime = dMillis + " millisec";
}
System.out.println("time: " + sTime);
I managed to fix this by adding:
android:layout_marginTop="?android:attr/actionBarSize"
to the FrameLayout like so:
<FrameLayout
android:id="@+id/content"
android:layout_marginTop="?android:attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
The way it's often done is as follows:
I find that this pattern comes up pretty frequently.
What's interesting about this method is that it allows one to insert N
elements into an empty array one-by-one in amortized O(N)
time without knowing N
in advance.
$("ul[data-group='Companies'] li[data-company='Microsoft']") //Get all elements with data-company="Microsoft" below "Companies"
$("ul[data-group='Companies'] li:not([data-company='Microsoft'])") //get all elements with data-company!="Microsoft" below "Companies"
Look in to jQuery Selectors :contains is a selector
here is info on the :contains selector
The best way to do this (that I've seen) is
var str = new Array(len + 1).join( character );
That creates an array with the given length, and then joins it with the given string to repeat. The .join()
function honors the array length regardless of whether the elements have values assigned, and undefined values are rendered as empty strings.
You have to add 1 to the desired length because the separator string goes between the array elements.
We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
So it's better to use the AJAX to parse the JavaScript value into the php Code.
Or alternatively we can make this done with the help of COOKIES in our code.
Thanks & Cheers.
From code you can use process.exit([errorcode])
where [errorcode]
is an optional integer (0
is the default to indicate success).
If you're using the Read Eval Print Loop (REPL), you can use Ctrl + D, or type .exit
Alternatively, on Windows or Linux you can use Ctrl + C, Ctrl + C
On Mac the command is Ctrl + Z, Ctrl + Z
The content
property states:
Authors may include newlines in the generated content by writing the "\A" escape sequence in one of the strings after the 'content' property. This inserted line break is still subject to the 'white-space' property. See "Strings" and "Characters and case" for more information on the "\A" escape sequence.
So you can use:
#headerAgentInfoDetailsPhone:after {
content:"Office: XXXXX \A Mobile: YYYYY ";
white-space: pre; /* or pre-wrap */
}
When escaping arbitrary strings, however, it's advisable to use \00000a
instead of \A
, because any number or [a-f]
character followed by the new line may give unpredictable results:
function addTextToStyle(id, text) {
return `#${id}::after { content: "${text.replace(/"/g, '\\"').replace(/\n/g, '\\00000a')} }"`;
}
If you want logs in a separate file other than the console: Double click on the server--> Open Launch Configuration--> Arguments --> add -Dlog.dir = "Path where you want to store this file" and restart the server.
Tip: Make sure that the server is not running when you are trying to add the argument. You should have log4j or similar logging framework in place.
./
refers to the current working directory, except in the require()
function. When using require()
, it translates ./
to the directory of the current file called. __dirname
is always the directory of the current file.
For example, with the following file structure
/home/user/dir/files/config.json
{
"hello": "world"
}
/home/user/dir/files/somefile.txt
text file
/home/user/dir/dir.js
var fs = require('fs');
console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));
If I cd
into /home/user/dir
and run node dir.js
I will get
{ hello: 'world' }
text file
But when I run the same script from /home/user/
I get
{ hello: 'world' }
Error: ENOENT, no such file or directory './files/somefile.txt'
at Object.openSync (fs.js:228:18)
at Object.readFileSync (fs.js:119:15)
at Object.<anonymous> (/home/user/dir/dir.js:4:16)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)
Using ./
worked with require
but not for fs.readFileSync
. That's because for fs.readFileSync
, ./
translates into the cwd (in this case /home/user/
). And /home/user/files/somefile.txt
does not exist.
The actual best answer for this problem depends on your environment, specifically what encoding your terminal expects.
The quickest one-line solution is to encode everything you print to ASCII, which your terminal is almost certain to accept, while discarding characters that you cannot print:
print ch #fails
print ch.encode('ascii', 'ignore')
The better solution is to change your terminal's encoding to utf-8, and encode everything as utf-8 before printing. You should get in the habit of thinking about your unicode encoding EVERY time you print or read a string.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_marginTop="16dp"
android:textSize="18sp"
android:textStyle="bold"
android:padding="4dp"
android:textColor="#EA80FC"
android:fontFamily="sans-serif-medium"
android:text="@string/team_a"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/team_a_score"
android:text="@string/_0"
android:textSize="56sp"
android:padding="4dp"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/team_a_fouls"
android:text="@string/fouls"
android:padding="4dp"
android:textSize="26sp"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="@string/_1_points"
android:layout_width="match_parent"
android:onClick="addOnePointTeamA"
android:textColor="#fff"
android:layout_margin="6dp"
android:layout_height="wrap_content" />
<Button
android:text="@string/_2_points"
android:textColor="#fff"
android:onClick="addTwoPointTeamA"
android:layout_width="match_parent"
android:layout_margin="6dp"
android:layout_height="wrap_content" />
<Button
android:text="@string/_3_points"
android:textColor="#fff"
android:onClick="addThreePointTeamA"
android:layout_margin="6dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="@string/_1_point_foul"
android:textColor="#fff"
android:layout_width="match_parent"
android:onClick="addOnePointFoulTeamA"
android:layout_margin="6dp"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:text="@string/team_b"
android:textColor="#EA80FC"
android:textStyle="bold"
android:padding="4dp"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif-medium"
android:textSize="18sp"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/team_b_score"
android:text="0"
android:padding="4dp"
android:textSize="56sp"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/team_b_fouls"
android:text="Fouls"
android:padding="4dp"
android:textSize="26sp"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="@string/_1_points"
android:textColor="#fff"
android:fontFamily="sans-serif-medium"
android:layout_width="match_parent"
android:onClick="addOnePointTeamB"
android:layout_margin="6dp"
android:layout_height="wrap_content" />
<Button
android:text="@string/_2_points"
android:layout_margin="6dp"
android:fontFamily="sans-serif-medium"
android:textColor="#fff"
android:onClick="addTwoPointTeamB"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="@string/_3_points"
android:fontFamily="sans-serif-medium"
android:textColor="#fff"
android:onClick="addThreePointTeamB"
android:layout_margin="6dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="@string/_1_point_foul"
android:textColor="#fff"
android:onClick="addOnePointFoulTeamB"
android:layout_width="match_parent"
android:layout_margin="6dp"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
<Button
android:text="@string/reset"
android:layout_marginBottom="25dp"
android:onClick="resetScore"
android:textColor="#fff"
android:fontFamily="sans-serif-medium"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
The solution is fairly straight forward. To ensure that we don't impact the width of the cells in the table, we'll turn off white-space. To ensure we get a horizontal scroll bar, we'll turn on overflow-x. And that's pretty much it:
.container {
width: 30em;
overflow-x: auto;
white-space: nowrap;
}
You can see the end-result here, or in the animation below. If the table determines the height of your container, you should not need to explicitly set overflow-y
to hidden
. But understand that is also an option.
Is there a reason you didn't just use this?
<select id="animal" name="animal">
<option value="0">--Select Animal--</option>
<option value="Cat">Cat</option>
<option value="Dog">Dog</option>
<option value="Cow">Cow</option>
</select>
if($_POST['submit'] && $_POST['submit'] != 0)
{
$animal=$_POST['animal'];
}
If you have this in your CSS file:
.myApp
{
border-bottom-color:#FF0000;
}
and a div for instance of:
<div id="myDiv">test text</div>
you can use:
$("#myDiv").addClass('myApp');// to add the style
$("#myDiv").removeClass('myApp');// to remove the style
or you can just use
$("#myDiv").css( 'border-bottom-color','#FF0000');
I prefer the first example, keeping all the CSS related items in the CSS files.
One possible explanation is a database trigger that fires for each DROP TABLE
statement. To find the trigger, query the _TRIGGERS
dictionary views:
select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')
disable any suspicious trigger with
alter trigger <trigger_name> disable;
and try re-running your DROP TABLE
statement
For Swift 4.0, it's now changed as:
tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.gray], for: .normal)
tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.blue], for: .selected)
You don't have to subclass the UITabBarItem if your requirement is only to change the text color. Just put the above code inside your view controller's viewDidLoad
function.
For global settings change tabBarItem
to UITabBarItem.appearance()
.
This is a very simple solution, but it works for me:
<!--TEXT-AREA-->_x000D_
<textarea id="textBox1" name="content" TextMode="MultiLine" onkeyup="setHeight('textBox1');" onkeydown="setHeight('textBox1');">Hello World</textarea>_x000D_
_x000D_
<!--JAVASCRIPT-->_x000D_
<script type="text/javascript">_x000D_
function setHeight(fieldId){_x000D_
document.getElementById(fieldId).style.height = document.getElementById(fieldId).scrollHeight+'px';_x000D_
}_x000D_
setHeight('textBox1');_x000D_
</script>
_x000D_
If you want to interpolate in console.log
output, then just
console.log("Eruption 1: %s", eruption1);
^^
Here, %s
is what is called a "format specifier". console.log
has this sort of interpolation support built-in.
There's one really important difference which is not mentioned anywhere.
take(1) emits 1, completes, unsubscribes
first() emits 1, completes, but doesn't unsubscribe.
It means that your upstream observable will still be hot after first() which is probably not expected behavior.
UPD: This referes to RxJS 5.2.0. This issue might be already fixed.
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
new object[] { param1, param2, param3 });
//Or
using(var context = new MyDataContext())
{
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
new object[] { param1, param2, param3 }).ToList();
}
//Or
using(var context = new MyDataContext())
{
object[] parameters = { param1, param2, param3 };
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
parameters).ToList();
}
//Or
using(var context = new MyDataContext())
{
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
param1, param2, param3).ToList();
}
Yes, it's possible to do. Consider the code below:
public class Test
{
public static void main (String[] args)
{
int v = 0;
if ((v=dostuff())!=0)
{
System.out.printf("HOWDY\n");
}
}
public static int dostuff()
{
//dosomething
return 1;
}
}
I hope this will satisfy your question.
I liked the approach used by Joel S, but I also love the simplicity of document.activeElement
. I used jQuery and combined the two. Older browsers that don't support document.activeElement
will use jQuery.data()
to store the value of 'hasFocus'. Newer browsers will use document.activeElement
. I assume that document.activeElement
will have better performance.
(function($) {
var settings;
$.fn.focusTracker = function(options) {
settings = $.extend({}, $.focusTracker.defaults, options);
if (!document.activeElement) {
this.each(function() {
var $this = $(this).data('hasFocus', false);
$this.focus(function(event) {
$this.data('hasFocus', true);
});
$this.blur(function(event) {
$this.data('hasFocus', false);
});
});
}
return this;
};
$.fn.hasFocus = function() {
if (this.length === 0) { return false; }
if (document.activeElement) {
return this.get(0) === document.activeElement;
}
return this.data('hasFocus');
};
$.focusTracker = {
defaults: {
context: 'body'
},
focusedElement: function(context) {
var focused;
if (!context) { context = settings.context; }
if (document.activeElement) {
if ($(document.activeElement).closest(context).length > 0) {
focused = document.activeElement;
}
} else {
$(':visible:enabled', context).each(function() {
if ($(this).data('hasFocus')) {
focused = this;
return false;
}
});
}
return $(focused);
}
};
})(jQuery);
I have hard time when trying to
So I made 2020 answer here
My directory looks like this
+-- docker-compose.yml
+-- mongo-entrypoint
+-- entrypoint.js
My docker-compose.yml
looks like this
version: '3.4'
services:
mongo-container:
# If you need to connect to your db from outside this container
network_mode: host
image: mongo:4.2
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=pass
ports:
- "27017:27017"
volumes:
- "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
command: mongod
Please change admin
and pass
with your need.
Inside mongo-entrypoint
, I have entrypoint.js
file with this content:
var db = connect("mongodb://admin:pass@localhost:27017/admin");
db = db.getSiblingDB('new_db'); // we can not use "use" statement here to switch db
db.createUser(
{
user: "user",
pwd: "pass",
roles: [ { role: "readWrite", db: "new_db"} ],
passwordDigestor: "server",
}
)
Here again you need to change admin:pass
to your root mongo credentials in your docker-compose.yml
that you stated before. In additional you need to change new_db
, user
, pass
to your new database name and credentials that you need.
Now you can:
docker-compose up -d
And connect to this db from localhost, please note that I already have mongo cli, you can install it or you can exec to the container above to use mongo
command:
mongo new_db -u user -p pass
Or you can connect from other computer
mongo host:27017/new_db -u user -p pass
My git repository: https://github.com/sexydevops/docker-compose-mongo
Hope it can help someone, I lost my afternoon for this ;)
Here is the MD5 code inserted in an Excel Module with the name "module_md5":
Private Const BITS_TO_A_BYTE = 8
Private Const BYTES_TO_A_WORD = 4
Private Const BITS_TO_A_WORD = 32
Private m_lOnBits(30)
Private m_l2Power(30)
Sub SetUpArrays()
m_lOnBits(0) = CLng(1)
m_lOnBits(1) = CLng(3)
m_lOnBits(2) = CLng(7)
m_lOnBits(3) = CLng(15)
m_lOnBits(4) = CLng(31)
m_lOnBits(5) = CLng(63)
m_lOnBits(6) = CLng(127)
m_lOnBits(7) = CLng(255)
m_lOnBits(8) = CLng(511)
m_lOnBits(9) = CLng(1023)
m_lOnBits(10) = CLng(2047)
m_lOnBits(11) = CLng(4095)
m_lOnBits(12) = CLng(8191)
m_lOnBits(13) = CLng(16383)
m_lOnBits(14) = CLng(32767)
m_lOnBits(15) = CLng(65535)
m_lOnBits(16) = CLng(131071)
m_lOnBits(17) = CLng(262143)
m_lOnBits(18) = CLng(524287)
m_lOnBits(19) = CLng(1048575)
m_lOnBits(20) = CLng(2097151)
m_lOnBits(21) = CLng(4194303)
m_lOnBits(22) = CLng(8388607)
m_lOnBits(23) = CLng(16777215)
m_lOnBits(24) = CLng(33554431)
m_lOnBits(25) = CLng(67108863)
m_lOnBits(26) = CLng(134217727)
m_lOnBits(27) = CLng(268435455)
m_lOnBits(28) = CLng(536870911)
m_lOnBits(29) = CLng(1073741823)
m_lOnBits(30) = CLng(2147483647)
m_l2Power(0) = CLng(1)
m_l2Power(1) = CLng(2)
m_l2Power(2) = CLng(4)
m_l2Power(3) = CLng(8)
m_l2Power(4) = CLng(16)
m_l2Power(5) = CLng(32)
m_l2Power(6) = CLng(64)
m_l2Power(7) = CLng(128)
m_l2Power(8) = CLng(256)
m_l2Power(9) = CLng(512)
m_l2Power(10) = CLng(1024)
m_l2Power(11) = CLng(2048)
m_l2Power(12) = CLng(4096)
m_l2Power(13) = CLng(8192)
m_l2Power(14) = CLng(16384)
m_l2Power(15) = CLng(32768)
m_l2Power(16) = CLng(65536)
m_l2Power(17) = CLng(131072)
m_l2Power(18) = CLng(262144)
m_l2Power(19) = CLng(524288)
m_l2Power(20) = CLng(1048576)
m_l2Power(21) = CLng(2097152)
m_l2Power(22) = CLng(4194304)
m_l2Power(23) = CLng(8388608)
m_l2Power(24) = CLng(16777216)
m_l2Power(25) = CLng(33554432)
m_l2Power(26) = CLng(67108864)
m_l2Power(27) = CLng(134217728)
m_l2Power(28) = CLng(268435456)
m_l2Power(29) = CLng(536870912)
m_l2Power(30) = CLng(1073741824)
End Sub
Private Function LShift(lValue, iShiftBits)
If iShiftBits = 0 Then
LShift = lValue
Exit Function
ElseIf iShiftBits = 31 Then
If lValue And 1 Then
LShift = &H80000000
Else
LShift = 0
End If
Exit Function
ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
Err.Raise 6
End If
If (lValue And m_l2Power(31 - iShiftBits)) Then
LShift = ((lValue And m_lOnBits(31 - (iShiftBits + 1))) * m_l2Power(iShiftBits)) Or &H80000000
Else
LShift = ((lValue And m_lOnBits(31 - iShiftBits)) * m_l2Power(iShiftBits))
End If
End Function
Private Function RShift(lValue, iShiftBits)
If iShiftBits = 0 Then
RShift = lValue
Exit Function
ElseIf iShiftBits = 31 Then
If lValue And &H80000000 Then
RShift = 1
Else
RShift = 0
End If
Exit Function
ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
Err.Raise 6
End If
RShift = (lValue And &H7FFFFFFE) \ m_l2Power(iShiftBits)
If (lValue And &H80000000) Then
RShift = (RShift Or (&H40000000 \ m_l2Power(iShiftBits - 1)))
End If
End Function
Private Function RotateLeft(lValue, iShiftBits)
RotateLeft = LShift(lValue, iShiftBits) Or RShift(lValue, (32 - iShiftBits))
End Function
Private Function AddUnsigned(lX, lY)
Dim lX4
Dim lY4
Dim lX8
Dim lY8
Dim lResult
lX8 = lX And &H80000000
lY8 = lY And &H80000000
lX4 = lX And &H40000000
lY4 = lY And &H40000000
lResult = (lX And &H3FFFFFFF) + (lY And &H3FFFFFFF)
If lX4 And lY4 Then
lResult = lResult Xor &H80000000 Xor lX8 Xor lY8
ElseIf lX4 Or lY4 Then
If lResult And &H40000000 Then
lResult = lResult Xor &HC0000000 Xor lX8 Xor lY8
Else
lResult = lResult Xor &H40000000 Xor lX8 Xor lY8
End If
Else
lResult = lResult Xor lX8 Xor lY8
End If
AddUnsigned = lResult
End Function
Private Function F(x, y, z)
F = (x And y) Or ((Not x) And z)
End Function
Private Function G(x, y, z)
G = (x And z) Or (y And (Not z))
End Function
Private Function H(x, y, z)
H = (x Xor y Xor z)
End Function
Private Function I(x, y, z)
I = (y Xor (x Or (Not z)))
End Function
Private Sub FF(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub GG(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub HH(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub II(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Function ConvertToWordArray(sMessage)
Dim lMessageLength
Dim lNumberOfWords
Dim lWordArray()
Dim lBytePosition
Dim lByteCount
Dim lWordCount
Const MODULUS_BITS = 512
Const CONGRUENT_BITS = 448
lMessageLength = Len(sMessage)
lNumberOfWords = (((lMessageLength + ((MODULUS_BITS - CONGRUENT_BITS) \ BITS_TO_A_BYTE)) \ (MODULUS_BITS \ BITS_TO_A_BYTE)) + 1) * (MODULUS_BITS \ BITS_TO_A_WORD)
ReDim lWordArray(lNumberOfWords - 1)
lBytePosition = 0
lByteCount = 0
Do Until lByteCount >= lMessageLength
lWordCount = lByteCount \ BYTES_TO_A_WORD
lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(Asc(Mid(sMessage, lByteCount + 1, 1)), lBytePosition)
lByteCount = lByteCount + 1
Loop
lWordCount = lByteCount \ BYTES_TO_A_WORD
lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(&H80, lBytePosition)
lWordArray(lNumberOfWords - 2) = LShift(lMessageLength, 3)
lWordArray(lNumberOfWords - 1) = RShift(lMessageLength, 29)
ConvertToWordArray = lWordArray
End Function
Private Function WordToHex(lValue)
Dim lByte
Dim lCount
For lCount = 0 To 3
lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)
WordToHex = WordToHex & Right("0" & Hex(lByte), 2)
Next
End Function
Public Function MD5(sMessage)
module_md5.SetUpArrays
Dim x
Dim k
Dim AA
Dim BB
Dim CC
Dim DD
Dim a
Dim b
Dim c
Dim d
Const S11 = 7
Const S12 = 12
Const S13 = 17
Const S14 = 22
Const S21 = 5
Const S22 = 9
Const S23 = 14
Const S24 = 20
Const S31 = 4
Const S32 = 11
Const S33 = 16
Const S34 = 23
Const S41 = 6
Const S42 = 10
Const S43 = 15
Const S44 = 21
x = ConvertToWordArray(sMessage)
a = &H67452301
b = &HEFCDAB89
c = &H98BADCFE
d = &H10325476
For k = 0 To UBound(x) Step 16
AA = a
BB = b
CC = c
DD = d
FF a, b, c, d, x(k + 0), S11, &HD76AA478
FF d, a, b, c, x(k + 1), S12, &HE8C7B756
FF c, d, a, b, x(k + 2), S13, &H242070DB
FF b, c, d, a, x(k + 3), S14, &HC1BDCEEE
FF a, b, c, d, x(k + 4), S11, &HF57C0FAF
FF d, a, b, c, x(k + 5), S12, &H4787C62A
FF c, d, a, b, x(k + 6), S13, &HA8304613
FF b, c, d, a, x(k + 7), S14, &HFD469501
FF a, b, c, d, x(k + 8), S11, &H698098D8
FF d, a, b, c, x(k + 9), S12, &H8B44F7AF
FF c, d, a, b, x(k + 10), S13, &HFFFF5BB1
FF b, c, d, a, x(k + 11), S14, &H895CD7BE
FF a, b, c, d, x(k + 12), S11, &H6B901122
FF d, a, b, c, x(k + 13), S12, &HFD987193
FF c, d, a, b, x(k + 14), S13, &HA679438E
FF b, c, d, a, x(k + 15), S14, &H49B40821
GG a, b, c, d, x(k + 1), S21, &HF61E2562
GG d, a, b, c, x(k + 6), S22, &HC040B340
GG c, d, a, b, x(k + 11), S23, &H265E5A51
GG b, c, d, a, x(k + 0), S24, &HE9B6C7AA
GG a, b, c, d, x(k + 5), S21, &HD62F105D
GG d, a, b, c, x(k + 10), S22, &H2441453
GG c, d, a, b, x(k + 15), S23, &HD8A1E681
GG b, c, d, a, x(k + 4), S24, &HE7D3FBC8
GG a, b, c, d, x(k + 9), S21, &H21E1CDE6
GG d, a, b, c, x(k + 14), S22, &HC33707D6
GG c, d, a, b, x(k + 3), S23, &HF4D50D87
GG b, c, d, a, x(k + 8), S24, &H455A14ED
GG a, b, c, d, x(k + 13), S21, &HA9E3E905
GG d, a, b, c, x(k + 2), S22, &HFCEFA3F8
GG c, d, a, b, x(k + 7), S23, &H676F02D9
GG b, c, d, a, x(k + 12), S24, &H8D2A4C8A
HH a, b, c, d, x(k + 5), S31, &HFFFA3942
HH d, a, b, c, x(k + 8), S32, &H8771F681
HH c, d, a, b, x(k + 11), S33, &H6D9D6122
HH b, c, d, a, x(k + 14), S34, &HFDE5380C
HH a, b, c, d, x(k + 1), S31, &HA4BEEA44
HH d, a, b, c, x(k + 4), S32, &H4BDECFA9
HH c, d, a, b, x(k + 7), S33, &HF6BB4B60
HH b, c, d, a, x(k + 10), S34, &HBEBFBC70
HH a, b, c, d, x(k + 13), S31, &H289B7EC6
HH d, a, b, c, x(k + 0), S32, &HEAA127FA
HH c, d, a, b, x(k + 3), S33, &HD4EF3085
HH b, c, d, a, x(k + 6), S34, &H4881D05
HH a, b, c, d, x(k + 9), S31, &HD9D4D039
HH d, a, b, c, x(k + 12), S32, &HE6DB99E5
HH c, d, a, b, x(k + 15), S33, &H1FA27CF8
HH b, c, d, a, x(k + 2), S34, &HC4AC5665
II a, b, c, d, x(k + 0), S41, &HF4292244
II d, a, b, c, x(k + 7), S42, &H432AFF97
II c, d, a, b, x(k + 14), S43, &HAB9423A7
II b, c, d, a, x(k + 5), S44, &HFC93A039
II a, b, c, d, x(k + 12), S41, &H655B59C3
II d, a, b, c, x(k + 3), S42, &H8F0CCC92
II c, d, a, b, x(k + 10), S43, &HFFEFF47D
II b, c, d, a, x(k + 1), S44, &H85845DD1
II a, b, c, d, x(k + 8), S41, &H6FA87E4F
II d, a, b, c, x(k + 15), S42, &HFE2CE6E0
II c, d, a, b, x(k + 6), S43, &HA3014314
II b, c, d, a, x(k + 13), S44, &H4E0811A1
II a, b, c, d, x(k + 4), S41, &HF7537E82
II d, a, b, c, x(k + 11), S42, &HBD3AF235
II c, d, a, b, x(k + 2), S43, &H2AD7D2BB
II b, c, d, a, x(k + 9), S44, &HEB86D391
a = AddUnsigned(a, AA)
b = AddUnsigned(b, BB)
c = AddUnsigned(c, CC)
d = AddUnsigned(d, DD)
Next
MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))
End Function
This is the easiest solution for this problem -
{% autoescape on %}
{{ body }}
{% endautoescape %}
From this page.
For anyone else getting
Nginx 403 error: directory index of [folder] is forbidden
when using index.php
while index.html
works perfectly and having included index.php
in the index in the server block of their site config in sites-enabled
server {
listen 80;
# this path MUST be exactly as docker-compose php volumes
root /usr/share/nginx/html;
index index.php
...
}
Make sure your nginx.conf file at /etc/nginx/nginx.conf
actually loads your site config in the http
block...
http {
...
include /etc/nginx/conf.d/*.conf;
# Load our websites config
include /etc/nginx/sites-enabled/*;
}
I like the accepted answer: it is straightforward and will get the job done. I would also like to offer an alternative implementation:
def chunks(filename, buffer_size=4096):
"""Reads `filename` in chunks of `buffer_size` bytes and yields each chunk
until no more characters can be read; the last chunk will most likely have
less than `buffer_size` bytes.
:param str filename: Path to the file
:param int buffer_size: Buffer size, in bytes (default is 4096)
:return: Yields chunks of `buffer_size` size until exhausting the file
:rtype: str
"""
with open(filename, "rb") as fp:
chunk = fp.read(buffer_size)
while chunk:
yield chunk
chunk = fp.read(buffer_size)
def chars(filename, buffersize=4096):
"""Yields the contents of file `filename` character-by-character. Warning:
will only work for encodings where one character is encoded as one byte.
:param str filename: Path to the file
:param int buffer_size: Buffer size for the underlying chunks,
in bytes (default is 4096)
:return: Yields the contents of `filename` character-by-character.
:rtype: char
"""
for chunk in chunks(filename, buffersize):
for char in chunk:
yield char
def main(buffersize, filenames):
"""Reads several files character by character and redirects their contents
to `/dev/null`.
"""
for filename in filenames:
with open("/dev/null", "wb") as fp:
for char in chars(filename, buffersize):
fp.write(char)
if __name__ == "__main__":
# Try reading several files varying the buffer size
import sys
buffersize = int(sys.argv[1])
filenames = sys.argv[2:]
sys.exit(main(buffersize, filenames))
The code I suggest is essentially the same idea as your accepted answer: read a given number of bytes from the file. The difference is that it first reads a good chunk of data (4006 is a good default for X86, but you may want to try 1024, or 8192; any multiple of your page size), and then it yields the characters in that chunk one by one.
The code I present may be faster for larger files. Take, for example, the entire text of War and Peace, by Tolstoy. These are my timing results (Mac Book Pro using OS X 10.7.4; so.py is the name I gave to the code I pasted):
$ time python so.py 1 2600.txt.utf-8
python so.py 1 2600.txt.utf-8 3.79s user 0.01s system 99% cpu 3.808 total
$ time python so.py 4096 2600.txt.utf-8
python so.py 4096 2600.txt.utf-8 1.31s user 0.01s system 99% cpu 1.318 total
Now: do not take the buffer size at 4096
as a universal truth; look at the results I get for different sizes (buffer size (bytes) vs wall time (sec)):
2 2.726
4 1.948
8 1.693
16 1.534
32 1.525
64 1.398
128 1.432
256 1.377
512 1.347
1024 1.442
2048 1.316
4096 1.318
As you can see, you can start seeing gains earlier on (and my timings are likely very inaccurate); the buffer size is a trade-off between performance and memory. The default of 4096 is just a reasonable choice but, as always, measure first.
For windows users: Disable Hyper-V and its tools
If you are a windows user, the problem might simply be because of having multiple virtualization technologies in your system.
You might be having Hyper-V and its related features enabled. Just simply turning them off and rebooting your system can do you help sometimes.
Here is how you do it:
Fireup your genymotion and check to see if it works again. If there is an error prompt saying something like DHCP cant assign IP... just try restarting your genymotion application.
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
You can do some thing like this,
Initialize with empty array and assign the values later
String importRt = "23:43 43:34";
if(null != importRt) {
importArray = Arrays.stream(importRt.split(" "))
.map(String::trim)
.toArray(String[]::new);
}
System.out.println(Arrays.toString(exportImportArray));
Hope it helps..
You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo rm -rf /var/lib/mysql
I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!
<form name="theform">
<input type="text" />
<input type="text" />`enter code here`
<input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
</form>
<script type="text/javascript" language="javascript">
let txt = document.querySelectorAll('[type="text"]');
for (let i = 0; i < txt.length; i++) {
txt[i].oninput = () => {
if (!(txt[0].value == '') && !(txt[1].value == '')) {
submitbutton.removeAttribute('disabled')
}
}
}
</script>
Although all the approaches regarding the use of async: false
are not good because of its deprecation and stuck the page untill the request comes back. Thus here are 2 ways to do it:
1st: Return whole ajax response in a function and then make use of done
function to capture the response when the request is completed.(RECOMMENDED, THE BEST WAY)
function getAjax(url, data){
return $.ajax({
type: 'POST',
url : url,
data: data,
dataType: 'JSON',
//async: true, //NOT NEEDED
success: function(response) {
//Data = response;
}
});
}
CALL THE ABOVE LIKE SO:
getAjax(youUrl, yourData).done(function(response){
console.log(response);
});
FOR MULTIPLE AJAX CALLS MAKE USE OF $.when
:
$.when( getAjax(youUrl, yourData), getAjax2(yourUrl2, yourData2) ).done(function(response){
console.log(response);
});
2nd: Store the response in a cookie and then outside of the ajax call get that cookie value.(NOT RECOMMENDED)
$.ajax({
type: 'POST',
url : url,
data: data,
//async: false, // No need to use this
success: function(response) {
Cookies.set(name, response);
}
});
// Outside of the ajax call
var response = Cookies.get(name);
NOTE: In the exmple above jquery cookies
library is used.It is quite lightweight and works as snappy. Here is the link https://github.com/js-cookie/js-cookie
There is an extension called Hinterland for jupyter, which automatically displays the drop down menu when typing. There are also some other useful extensions.
In order to install extensions, you can follow the guide on this github repo. To easily activate extensions, you may want to use the extensions configurator.
swift 4
I just add this line in viewDidLoad and work fine with me.
view.removeConstraints(view.constraints)
Try this:
$("div.subtab_left li.notebook a").click(function(e) {
e.preventDefault();
});
mysql -u username -p -h localhost DATA-BASE-NAME < data.sql
look here - step 3: this way you dont need the USE statement
It's showing the backslash because you're also escaping the backslash.
Aside from double quotes, you must also escape backslashes if you want to include one in your JSON quoted string. However if you intend to use a backslash in an escape sequence, obviously you shouldn't escape it.
The M2_HOME
environment variable for the global one. See Settings Reference:
The
settings
element in thesettings.xml
file contains elements used to define values which configure Maven execution in various ways, like thepom.xml
, but should not be bundled to any specific project, or distributed to an audience. These include values such as the local repository location, alternate remote repository servers, and authentication information. There are two locations where a settings.xml file may live:
- The Maven install:
$M2_HOME/conf/settings.xml
- A user's install:
${user.home}/.m2/settings.xml
I'm unsure if this is still an issue for this individual, but I know it can be a pain for many people in general. Granted, the above solutions will work in some instances, but if you are, for example, using a CMS like WordPress, and the outlines are being generated by either a plugin or theme, you will most likely not have this issue resolved, depending on how you are adding the CSS.
I'd suggest having a separate StyleSheet (for example, use 'Lazyest StyleSheet' plugin), and enter the following CSS within it to override the existing plugin (or theme)-forced style:
a:hover,a:active,a:link {
outline: 0 !important;
text-decoration: none !important;
}
Adding '!important' to the specific rule will make this a priority to generate even if the rule may be elsewhere (whether it's in a plugin, theme, etc.).
This helps save time when developing. Sure, you can dig for the original source, but when you're working on many projects, or need to perform updates (where your changes can be overridden [not suggested!]), or add new plugins or themes, this is the best recourse to save time.
Hope this helps...Peace!
Because that gtab82 table isn't in your FROM or JOIN clause. You refer gtab82 table in these cases: gtab82.memno and gtab82.memacid
Since Sept 2020, flutter 1.22.0:
Both "RaisedButton" and "FlatButton" are deprecated.
ElevatedButton
:Code:
ElevatedButton(
child: Text("ElevatedButton"),
onPressed: () => print("it's pressed"),
style: ElevatedButton.styleFrom(
primary: Colors.red,
onPrimary: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(32.0),
),
),
)
Don't forget, there's also an .icon
constructor to add an icon easily:
ElevatedButton.icon(
icon: Icon(Icons.thumb_up),
label: Text("Like"),
onPressed: () => print("it's pressed"),
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(32.0),
),
),
)
OutlinedButton
:Code:
OutlinedButton.icon(
icon: Icon(Icons.star_outline),
label: Text("OutlinedButton"),
onPressed: () => print("it's pressed"),
style: ElevatedButton.styleFrom(
side: BorderSide(width: 2.0, color: Colors.blue),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(32.0),
),
),
)
TextButton
:You can always use TextButton
if you don't want outline or color fill.
I don't know what "milliseconds and float seconds" means, but this should give you an idea:
#include <chrono>
#include <thread>
#include <iostream>
int main()
{
auto then = std::chrono::system_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(1));
auto now = std::chrono::system_clock::now();
auto dur = now - then;
typedef std::chrono::duration<float> float_seconds;
auto secs = std::chrono::duration_cast<float_seconds>(dur);
std::cout << secs.count() << '\n';
}
Have you Disabled the VIA setting in the SQL configuration manager? If not, do disable it first (if VIA is enabled, you cannot get connected) and yes TCP must be enabled. Give it a try and it should be working fine.
Make the changes only for that's particular instance name.
Cheers!
For IE11 example (browser type=Trident version=7.0):
image.style.transform = "rotate(270deg)";
There are several sparse matrix classes in scipy.
bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Row matrix
dia_matrix(arg1[, shape, dtype, copy]) Sparse matrix with DIAgonal storage
dok_matrix(arg1[, shape, dtype, copy]) Dictionary Of Keys based sparse matrix.
lil_matrix(arg1[, shape, dtype, copy]) Row-based linked list sparse matrix
Any of them can do the conversion.
import numpy as np
from scipy import sparse
a=np.array([[1,0,1],[0,0,1]])
b=sparse.csr_matrix(a)
print(b)
(0, 0) 1
(0, 2) 1
(1, 2) 1
See http://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information .
//---- remove first and last char of str
str = str.substring(1,((keyw.length)-1));
//---- remove only first char
str = str.substring(1,(keyw.length));
//---- remove only last char
str = str.substring(0,(keyw.length));
Typing in 0%
takes you to the beginning.
100%
takes you to the end.
50%
takes you half way.
I was getting the same error, for me, it was because API was just returning a string however in fetch call I was expecting json :
response => response.json()
Returning json from API resolved the issue for me, if your API is not supposed to return json then simply don't do response.json()
Since I made such a big deal about a recursive function, here is my own version.
function objectParametize(obj, delimeter, q) {
var str = new Array();
if (!delimeter) delimeter = '&';
for (var key in obj) {
switch (typeof obj[key]) {
case 'string':
case 'number':
str[str.length] = key + '=' + obj[key];
break;
case 'object':
str[str.length] = objectParametize(obj[key], delimeter);
}
}
return (q === true ? '?' : '') + str.join(delimeter);
}
This will resolve any nested properties.
public class Environment extends PropertyPlaceholderConfigurer {
/**
* Map that hold all the properties.
*/
private Map<String, String> propertiesMap;
/**
* Iterate through all the Property keys and build a Map, resolve all the nested values before building the map.
*/
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
super.processProperties(beanFactory, props);
propertiesMap = new HashMap<String, String>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String valueStr = beanFactory.resolveEmbeddedValue(placeholderPrefix + keyStr.trim() + DEFAULT_PLACEHOLDER_SUFFIX);
propertiesMap.put(keyStr, valueStr);
}
}
/**
* This method gets the String value for a given String key for the property files.
*
* @param name - Key for which the value needs to be retrieved.
* @return Value
*/
public String getProperty(String name) {
return propertiesMap.get(name).toString();
}
Most Javascript engines do not optimize tail recursion (this might not be an issue if your JSON isn't deeply nested), but I usually err on the side of caution and do iteration instead, e.g.
function traverse(o, fn) {
const stack = [o]
while (stack.length) {
const obj = stack.shift()
Object.keys(obj).forEach((key) => {
fn(key, obj[key], obj)
if (obj[key] instanceof Object) {
stack.unshift(obj[key])
return
}
})
}
}
const o = {
name: 'Max',
legal: false,
other: {
name: 'Maxwell',
nested: {
legal: true
}
}
}
const fx = (key, value, obj) => console.log(key, value)
traverse(o, fx)
The above answer is useful but in graphs, it is difficult to distinguish between darker gradients of black. One alternative I found is to use gradients of gray colors as follows
palette(gray.colors(10, 0.9, 0.4))
plot(rep(1,10),col=1:10,pch=19,cex=3))
More info on gray scale here.
Added
When I used the code above for different colours like blue and black, the gradients were not that clear.
heat.colors()
seems more useful.
This document has more detailed information and options. pdf
In case you need possibility to hide and show scrollbars dynamically you could use
$("body").css("overflow", "hidden");
and
$("body").css("overflow", "auto");
somewhere in your code.
This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.
change it to:
$(function () {
var specialElementHandlers = {
'#editor': function (element,renderer) {
return true;
}
};
$('#cmd').click(function () {
var doc = new jsPDF();
doc.fromHTML(
$('#target').html(), 15, 15,
{ 'width': 170, 'elementHandlers': specialElementHandlers },
function(){ doc.save('sample-file.pdf'); }
);
});
});
and it will work.
If you are lucky enough to develop with Kotlin,
you can use take
to achieve your goal.
val someString = "hello"
someString.take(10) // result is "hello"
someString.take(4) // result is "hell" )))
<color name="blackColorPrimary">#000001</color> (not #000000)
<item name="android:navigationBarColor" tools:targetApi="lollipop">@color/blackColorPrimary</item>
Problem is that android higher version make trasparent for #000000
This is incorrect initialization. You interchanged row with col!
C = [[0 for row in range(len(A))] for col in range(len(B[0]))]
Correct initialization would be
C = [[0 for col in range(len(B[0]))] for row in range(len(A))]
Also I would suggest using better naming conventions. Will help you a lot in debugging. For example:
def matrixmult (A, B):
rows_A = len(A)
cols_A = len(A[0])
rows_B = len(B)
cols_B = len(B[0])
if cols_A != rows_B:
print "Cannot multiply the two matrices. Incorrect dimensions."
return
# Create the result matrix
# Dimensions would be rows_A x cols_B
C = [[0 for row in range(cols_B)] for col in range(rows_A)]
print C
for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
C[i][j] += A[i][k] * B[k][j]
return C
You can do a lot more, but you get the idea...
How about;
function keyValue(key, value){
this.Key = key;
this.Value = value;
};
keyValue.prototype.updateTo = function(newKey, newValue) {
this.Key = newKey;
this.Value = newValue;
};
array[1].updateTo("xxx", "999");
public List<DealInfo> getDealInfos(List<String> dealIds) {
String queryStr = "SELECT NEW com.admin.entity.DealInfo(deal.url, deal.url, deal.url, deal.url, deal.price, deal.value) " + "FROM Deal AS deal where deal.id in :inclList";
TypedQuery<DealInfo> query = em.createQuery(queryStr, DealInfo.class);
query.setParameter("inclList", dealIds);
return query.getResultList();
}
Works for me with JPA 2, Jboss 7.0.2
You can pass array of variables to the compact as an arguement eg:
return view('yourView', compact(['var1','var2',....'varN']));
in view: if var1 is an object you can use it something like this
@foreach($var1 as $singleVar1)
{{$singleVar1->property}}
@endforeach
incase of single variable you can simply
{{$var2}}
i have done this several times without any issues
I had the same problem when trying to deploy, tomcat failed to restart as Tomcat instance was running. Close the IDE and check TASk Manager - kill any javaw process running, that solved the problem for me.
If you are using express
you can use the cors package to allow CORS like so instead of writing your middleware;
var express = require('express')
, cors = require('cors')
, app = express();
app.use(cors());
app.get(function(req,res){
res.send('hello');
});
For the sake of completion: if you want to convert fixed point representation to its binary equivalent you can perform the following operations:
Get the integer and fractional part.
from decimal import *
a = Decimal(3.625)
a_split = (int(a//1),a%1)
Convert the fractional part in its binary representation. To achieve this multiply successively by 2.
fr = a_split[1]
str(int(fr*2)) + str(int(2*(fr*2)%1)) + ...
You can read the explanation here.
And why don't you try with this ??? :
var itemsMax = items.Where(x => x.Height == items.Max(y => y.Height));
OR more optimise :
var itemMaxHeight = items.Max(y => y.Height);
var itemsMax = items.Where(x => x.Height == itemMaxHeight);
mmm ?
I came up with a rock-solid solution for these issues that conforms with the 'Android Way' of things. I have all my long-running operations using the IntentService pattern.
That is, my activities broadcast intents, the IntentService does the work, saves the data in the DB and then broadcasts sticky intents. The sticky part is important, such that even if the Activity was paused during during the time after the user initiated the work and misses the real time broadcast from the IntentService we can still respond and pick up the data from the calling Activity. ProgressDialog
s can work with this pattern quite nicely with onSaveInstanceState()
.
Basically, you need to save a flag that you have a progress dialog running in the saved instance bundle. Do not save the progress dialog object because this will leak the entire Activity. To have a persistent handle to the progress dialog, I store it as a weak reference in the application object. On orientation change or anything else that causes the Activity to pause (phone call, user hits home etc.) and then resume, I dismiss the old dialog and recreate a new dialog in the newly created Activity.
For indefinite progress dialogs this is easy. For progress bar style, you have to put the last known progress in the bundle and whatever information you're using locally in the activity to keep track of the progress. On restoring the progress, you'll use this information to re-spawn the progress bar in the same state as before and then update based on the current state of things.
So to summarize, putting long-running tasks into an IntentService coupled with judicious use of onSaveInstanceState()
allows you to efficiently keep track of dialogs and restore then across the Activity life-cycle events. Relevant bits of Activity code are below. You'll also need logic in your BroadcastReceiver to handle Sticky intents appropriately, but that is beyond the scope of this.
public void doSignIn(View view) {
waiting=true;
AppClass app=(AppClass) getApplication();
String logingon=getString(R.string.signon);
app.Dialog=new WeakReference<ProgressDialog>(ProgressDialog.show(AddAccount.this, "", logingon, true));
...
}
@Override
protected void onSaveInstanceState(Bundle saveState) {
super.onSaveInstanceState(saveState);
saveState.putBoolean("waiting",waiting);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState!=null) {
restoreProgress(savedInstanceState);
}
...
}
private void restoreProgress(Bundle savedInstanceState) {
waiting=savedInstanceState.getBoolean("waiting");
if (waiting) {
AppClass app=(AppClass) getApplication();
ProgressDialog refresher=(ProgressDialog) app.Dialog.get();
refresher.dismiss();
String logingon=getString(R.string.signon);
app.Dialog=new WeakReference<ProgressDialog>(ProgressDialog.show(AddAccount.this, "", logingon, true));
}
}
first type cmd
then the windows command prompt will appear:
PATH C:\XAMPP\MYSQL\BIN;%PATH%;
mysql -u root -p
where:
This is an issue relating JRE.In my case (eclipse Luna with Maven plugin, JDK 7) I solved this by making following change in pom.xml and then Maven Update Project.
from:
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
to:
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
Screenshot showing problem in JRE:
You can call UserPrincipal.FindByIdentity
inside System.DirectoryServices.AccountManagement
:
using System.DirectoryServices.AccountManagement;
using (var pc = new PrincipalContext(ContextType.Domain, "MyDomainName"))
{
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "MyDomainName\\" + userName);
}
I think this is a best practice (You may be have many Tomcat instance in same computer, you want per Tomcat instance use other Java Runtime Environment):
This is manual inside file: catalina.sh
# JRE_HOME Must point at your Java Runtime installation.
# Defaults to JAVA_HOME if empty. If JRE_HOME and JAVA_HOME
# are both set, JRE_HOME is used.
UIImage *image = [UIImage imageNamed:@"decline_clicked.png"];
NSData *imageData = UIImageJPEGRepresentation(image,1);
NSString *queryStringss = [NSString stringWithFormat:@"http://119.9.77.121/lets_chat/index.php/webservices/uploadfile/"];
queryStringss = [queryStringss stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[manager POST:queryStringss parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileData:imageData name:@"fileName" fileName:@"decline_clicked.png" mimeType:@"image/jpeg"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *dict = [responseObject objectForKey:@"Result"];
NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
NSLog(@"Error: %@ ***** %@", operation.responseString, error);
}];
Instead of the modulo operator, which has slightly different semantics, for non-negative integers, you can use the remainder operator %
. For your exact example:
if ((a % 2) == 0)
{
isEven = true;
}
else
{
isEven = false;
}
This can be simplified to a one-liner:
isEven = (a % 2) == 0;
You can use Environment Replacement in your Dockerfile
as follows:
ENV PATH="/opt/gtk/bin:${PATH}"
Just use multiline selection in sublime to combine all of the files into a single line and add a space between each file name and then add rm
at the beginning of the list. This is mostly useful when there isn't a pattern in the filenames you want to delete.
[$]> rm abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28 abc.log.2012-03-29 abc.log.2012-03-30 abc.log.2012-04-02 abc.log.2012-04-04 abc.log.2012-04-05 abc.log.2012-04-09 abc.log.2012-04-10
1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math
.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply
and sapply
:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
You can use .is(':visible')
Selects all elements that are visible.
For example:
if($('#selectDiv').is(':visible')){
Also, you can get the div which is visible by:
$('div:visible').callYourFunction();
Live example:
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
display: none; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
To get the current router instance or current location you have to create a Higher order component with withRouter
from react-router-dom
. otherwise, when you are trying to access this.props.location
it will return undefined
Example
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
class className extends Component {
render(){
return(
....
)
}
}
export default withRouter(className)
..extending Mikaels' answers
SELECT
CASE WHEN ISNUMERIC(QTY + 'e0') = 1 THEN CAST(QTY AS float) ELSE null END AS MyFloat
CASE WHEN ISNUMERIC(QTY + 'e0') = 0 THEN QTY ELSE null END AS MyVarchar
FROM
...
e0
fixes some ISNUMERIC issues (such as +
-
.
and empty string being accepted)$_SERVER['HTTP_REFERER'];
But if you run a file (that contains the above code) by directly hitting the URL in the browser then you get the following error.
Notice: Undefined index: HTTP_REFERER
UPDATED ANSWER:
Old answer, correct method nowadays is to use jQuery's .prop()
. IE, element.prop("selected", true)
OLD ANSWER:
Use this instead:
$("#routetype option[value='quietest']").attr("selected", "selected");
Fiddle'd: http://jsfiddle.net/x3UyB/4/
The solution i'm using is as follows and allows you to set the active class per php page.
Give each of your menu items a unique class, i use .nav-x
(nav-about, here).
<li class="nav-item nav-about">
<a class="nav-link" href="about.php">About</a>
</li>
At the top of each page (about.php here):
<!-- Navbar Active Class -->
<?php $activeClass = '.nav-about > a'; ?>
Elsewhere (header.php / index.php):
<style>
<?php echo $activeClass; ?> {
color: #fff !important;
}
</style>
Simply change the .nav-about > a
per page, .nav-forum > a
, for example.
If you want different styling (colors etc) for each nav item, just attach the inline styling to that page instead of the index / header page.
You can use this:
$("#id").click(function()
{
$(this).data('clicked', true);
});
Now check it via an if statement:
if($("#id").data('clicked'))
{
// code here
}
For more information you can visit the jQuery website on the .data() function.
I found this solution after days.
Firstly, which Python version you want to install?
If you want for Python 2.7 version:
STEP 1:
scipy-0.19.0-cp27-cp27m-win32.whl
scipy-0.19.0-cp27-cp27m-win_amd64.whl
numpy-1.11.3+mkl-cp27-cp27m-win32.whl
numpy-1.11.3+mkl-cp27-cp27m-win_amd64.whl
If you want for Python 3.4 version:
scipy-0.19.0-cp34-cp34m-win32.whl
scipy-0.19.0-cp34-cp34m-win_amd64.whl
numpy-1.11.3+mkl-cp34-cp34m-win32.whl
numpy-1.11.3+mkl-cp34-cp34m-win_amd64.whl
If you want for Python 3.5 version:
scipy-0.19.0-cp35-cp35m-win32.whl
scipy-0.19.0-cp35-cp35m-win_amd64.whl
numpy-1.11.3+mkl-cp35-cp35m-win32.whl
numpy-1.11.3+mkl-cp35-cp35m-win_amd64.whl
If you want for Python 3.6 version:
scipy-0.19.0-cp36-cp36m-win32.whl
scipy-0.19.0-cp36-cp36m-win_amd64.whl
numpy-1.11.3+mkl-cp36-cp36m-win32.whl
numpy-1.11.3+mkl-cp36-cp36m-win_amd64.whl
Link: click
Once finishing installation, go to your directory.
For example, my directory:
cd C:\Users\asus\AppData\Local\Programs\Python\Python35\Scripts>
pip install [where/is/your/downloaded/scipy_whl.]
STEP 2:
NumPy + MKL
From same web site based on the Python version again:
After that use same thing again in the script folder:
cd C:\Users\asus\AppData\Local\Programs\Python\Python35\Scripts>
pip3 install [where/is/your/downloaded/numpy_whl.]
And test it in the Python folder.
Python35>python
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import scipy
null
is a special value that is not an instance of any class. This is illustrated by the following program:
public class X {
void f(Object o)
{
System.out.println(o instanceof String); // Output is "false"
}
public static void main(String[] args) {
new X().f(null);
}
}
Ansible has a version_compare
filter since 1.6.
You can do something like below in when
conditional:
when: ansible_distribution_version | version_compare('12.04', '>=')
This will give you support for major & minor versions comparisons and you can compare versions using operators like:
<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne
You can find more information about this here: Ansible - Version comparison filters
Otherwise if you have really simple case you can use what @ProfHase85 suggested
I am using this which works if you pass it a date obj or js timestamp:
getHumanReadableDate: function(date) {
if (date instanceof Date) {
return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
} else if (isFinite(date)) {//timestamp
var d = new Date();
d.setTime(date);
return this.getHumanReadableDate(d);
}
}
refer to my code, hope helpful for you:
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
String mount = new String();
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
if (line.contains("secure")) continue;
if (line.contains("asec")) continue;
if (line.contains("fat")) {//TF card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
mount = mount.concat("*" + columns[1] + "\n");
}
} else if (line.contains("fuse")) {//internal storage
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
mount = mount.concat(columns[1] + "\n");
}
}
}
txtView.setText(mount);
Use rgba as most of the commonly used browsers supports it..
.social img:hover {
background-color: rgba(0, 0, 0, .5)
}
In simpler case (when html tags is the same):
<h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>
File myFile = new File(uri.toString());
myFile.getAbsolutePath()
should return u the correct path
EDIT
As @Tron suggested the working code is
File myFile = new File(uri.getPath());
myFile.getAbsolutePath()
max_connections
You can change max_connections
while MySQL is running via SET
:
mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 5000 |
+-----------------+-------+
1 row in set (0.00 sec)
timeout
relatedI had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.
I suggest that you increase this value to 100k or disable connection pooling Pooling=false
he has two questions.
Q1 - what happens if I disable pooling
Slow down making DB connection. connection pooling
is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool
Q2 - Can the value of pooling be increased or the maximum is 100?
you can increase but I'm sure what is MAX value, maybe max_connections
in my.cnf
My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.
If you have Stress Test tool like JMeter
you can test youself.
You can give like this also
labelName.font = UIFont(name: "systemFont", size: 30)
I got this issue when I used an ajax call to retrieve data from the database. When the controller returned the array it converted it to a boolean. The problem was that I had "invalid characters" like ú (u with accent).
The problem comes because of an interesting clash of new C++ features and what you're trying to do. First, let's take a look at the push_back
signature:
void push_back(const T&)
It's expecting a reference to an object of type T
. Under the old system of initialization, such a member exists. For example, the following code compiles just fine:
#include <vector>
class Foo {
public:
static const int MEMBER;
};
const int Foo::MEMBER = 1;
int main(){
std::vector<int> v;
v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER'
v.push_back( (int) Foo::MEMBER ); // OK
return 0;
}
This is because there is an actual object somewhere that has that value stored in it. If, however, you switch to the new method of specifying static const members, like you have above, Foo::MEMBER
is no longer an object. It is a constant, somewhat akin to:
#define MEMBER 1
But without the headaches of a preprocessor macro (and with type safety). That means that the vector, which is expecting a reference, can't get one.
Similar to yebmouxing I could not the
xhr.getResponseHeader('Set-Cookie');
method to work. It would only return null even if I had set HTTPOnly to false on my server.
I too wrote a simple js helper function to grab the cookies from the document. This function is very basic and only works if you know the additional info (lifespan, domain, path, etc. etc.) to add yourself:
function getCookie(cookieName){
var cookieArray = document.cookie.split(';');
for(var i=0; i<cookieArray.length; i++){
var cookie = cookieArray[i];
while (cookie.charAt(0)==' '){
cookie = cookie.substring(1);
}
cookieHalves = cookie.split('=');
if(cookieHalves[0]== cookieName){
return cookieHalves[1];
}
}
return "";
}
I totally agree with the guys, it's better to use virtualenv so you can set a custom environment for every project. It ideal for maintenance because it's like a different world for every project and every update of an application you make won't interfere with other projects.
Here you can find a nutshell of virtualenv related to installation and first steps.
I actually check all bash scripts in current dir for syntax errors WITHOUT running them using find
tool:
Example:
find . -name '*.sh' -exec bash -n {} \;
If you want to use it for a single file, just edit the wildcard with the name of the file.
There is HasFlag method in .NET 4 or higher.
if(letter.HasFlag(Letters.AB))
{
}
pandas.merge()
is the underlying function used for all merge/join behavior.
DataFrames provide the pandas.DataFrame.merge()
and pandas.DataFrame.join()
methods as a convenient way to access the capabilities of pandas.merge()
. For example, df1.merge(right=df2, ...)
is equivalent to pandas.merge(left=df1, right=df2, ...)
.
These are the main differences between df.join()
and df.merge()
:
df1.join(df2)
always joins via the index of df2
, but df1.merge(df2)
can join to one or more columns of df2
(default) or to the index of df2
(with right_index=True
). df1.join(df2)
uses the index of df1
and df1.merge(df2)
uses column(s) of df1
. That can be overridden by specifying df1.join(df2, on=key_or_keys)
or df1.merge(df2, left_index=True)
. df1.join(df2)
does a left join by default (keeps all rows of df1
), but df.merge
does an inner join by default (returns only matching rows of df1
and df2
).So, the generic approach is to use pandas.merge(df1, df2)
or df1.merge(df2)
. But for a number of common situations (keeping all rows of df1
and joining to an index in df2
), you can save some typing by using df1.join(df2)
instead.
Some notes on these issues from the documentation at http://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging:
merge
is a function in the pandas namespace, and it is also available as a DataFrame instance method, with the calling DataFrame being implicitly considered the left object in the join.The related
DataFrame.join
method, usesmerge
internally for the index-on-index and index-on-column(s) joins, but joins on indexes by default rather than trying to join on common columns (the default behavior formerge
). If you are joining on index, you may wish to useDataFrame.join
to save yourself some typing.
...
These two function calls are completely equivalent:
left.join(right, on=key_or_keys) pd.merge(left, right, left_on=key_or_keys, right_index=True, how='left', sort=False)
I would be inclined to use a class in your css that alters the border style or border width when the button is depressed, so it gives the appearance of a toggle button.
Create a class and put all your code in there and call an instance of this class from the Main :
static void Main(string[] args)
{
MyClass cls = new MyClass();
Console.Write("Write a number: ");
long a= Convert.ToInt64(Console.ReadLine()); // a is the number given by the user
long av = cls.volteado(a);
bool isTrue = cls.siprimo(a);
......etc
}
I was looking for a solution to add an UIImage
to my UIButton
. The problem was just it displays the image bigger than needed. Just helped me with this:
_imageViewBackground = [[UIImageView alloc] initWithFrame:rectImageView];
_imageViewBackground.image = [UIImage imageNamed:@"gradientBackgroundPlain"];
[self addSubview:_imageViewBackground];
[self insertSubview:_imageViewBackground belowSubview:self.label];
_imageViewBackground.hidden = YES;
Every time I want to display my UIImageView
I just set the var hidden
to YES
or NO
.
There might be other solutions but I got confused so many times with this stuff and this solved it and I didn't need to deal with internal stuff UIButton
is doing in background.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// ...
});
The dispatch_after(_:_:_:)
function takes three parameters:
a delay
a dispatch queue
a block or closure
The dispatch_after(_:_:_:)
function invokes the block or closure on the dispatch queue that is passed to the function after a given delay. Note that the delay is created using the dispatch_time(_:_:)
function. Remember this because we also use this function in Swift.
I recommend to go through the tutorial Raywenderlich Dispatch tutorial
Although this question is old and answered, I've stumbled across a problem with some of the solutions and decided to add my suggestion into the mix.
The problem with some of the solutions is that they build a single command string. This creates issues when some parameters contain spaces, especially java.home.
For example, on windows, the line
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
Might return something like this:C:\Program Files\Java\jre7\bin\java
This string has to be wrapped in quotes or escaped due to the space in Program Files
. Not a huge problem, but somewhat annoying and error prone, especially in cross platform applications.
Therefore my solution builds the command as an array of commands:
public static void restart(String[] args) {
ArrayList<String> commands = new ArrayList<String>(4 + jvmArgs.size() + args.length);
List<String> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments();
// Java
commands.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java");
// Jvm arguments
for (String jvmArg : jvmArgs) {
commands.add(jvmArg);
}
// Classpath
commands.add("-cp");
commands.add(ManagementFactory.getRuntimeMXBean().getClassPath());
// Class to be executed
commands.add(BGAgent.class.getName());
// Command line arguments
for (String arg : args) {
commands.add(arg);
}
File workingDir = null; // Null working dir means that the child uses the same working directory
String[] env = null; // Null env means that the child uses the same environment
String[] commandArray = new String[commands.size()];
commandArray = commands.toArray(commandArray);
try {
Runtime.getRuntime().exec(commandArray, env, workingDir);
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
%RANDOM% gives you a random number between 0 and 32767.
You can control the number's range with:
set /a num=%random% %%100
- will produce number between 0~99.
This one:
set /a num=%random% %%100 +1
- will produce number between 1~100.
IN MS SQL server use the COLLATE clause.
SELECT Column1
FROM Table1
WHERE Column1 COLLATE Latin1_General_CS_AS = 'casesearch'
Adding COLLATE Latin1_General_CS_AS
makes the search case sensitive.
Default Collation of the SQL Server installation SQL_Latin1_General_CP1_CI_AS
is not case sensitive.
To change the collation of the any column for any table permanently run following query.
ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(20)
COLLATE Latin1_General_CS_AS
To know the collation of the column for any table run following Stored Procedure.
EXEC sp_help DatabaseName
Source : SQL SERVER – Collate – Case Sensitive SQL Query Search
In c# or Xamarin.ios, this.NavigationItem.HidesBackButton = true;
To solve the problem do following:
First uninstall numpy
sudo pip uninstall numpy
Install numpy with --no-cache-dir option
sudo pip install --no-cache-dir numpy
And to specify any specific version e.g. 1.14.2
sudo pip install --no-cache-dir numpy==1.14.2
If you have PowerShell 5.0 or higher (pre-installed with Windows 10 and Windows Server 2016):
powershell Expand-Archive your.zip -DestinationPath your_destination
i will provide mine because @muni s solution was a bit overkill for me
note: if you want to add custom definitions for several resolutions together, say something like this:
//mobile generally
@media screen and (max-width: 1199) {
.irns-desktop{
display: none;
}
.irns-mobile{
display: initial;
}
}
Be sure to add those definitions on top of the accurate definitions, so it cascades correctly (e.g. 'smartphone portrait' must win versus 'mobile generally')
//here all definitions to apply globally
//desktop
@media only screen
and (min-width : 1200) {
}
//tablet landscape
@media screen and (min-width: 1024px) and (max-width: 1600px) {
} // end media query
//tablet portrait
@media screen and (min-width: 768px) and (max-width: 1023px) {
}//end media definition
//smartphone landscape
@media screen and (min-width: 480px) and (max-width: 767px) {
}//end media query
//smartphone portrait
@media screen /*and (min-width: 320px)*/
and (max-width: 479px) {
}
//end media query
Here is the code with tests cases ;) :
@Test
public void testNullStringShouldReturnStringWithSpaces() throws Exception {
String fixedString = writeAtFixedLength(null, 5);
assertEquals(fixedString, " ");
}
@Test
public void testEmptyStringReturnStringWithSpaces() throws Exception {
String fixedString = writeAtFixedLength("", 5);
assertEquals(fixedString, " ");
}
@Test
public void testShortString_ReturnSameStringPlusSpaces() throws Exception {
String fixedString = writeAtFixedLength("aa", 5);
assertEquals(fixedString, "aa ");
}
@Test
public void testLongStringShouldBeCut() throws Exception {
String fixedString = writeAtFixedLength("aaaaaaaaaa", 5);
assertEquals(fixedString, "aaaaa");
}
private String writeAtFixedLength(String pString, int lenght) {
if (pString != null && !pString.isEmpty()){
return getStringAtFixedLength(pString, lenght);
}else{
return completeWithWhiteSpaces("", lenght);
}
}
private String getStringAtFixedLength(String pString, int lenght) {
if(lenght < pString.length()){
return pString.substring(0, lenght);
}else{
return completeWithWhiteSpaces(pString, lenght - pString.length());
}
}
private String completeWithWhiteSpaces(String pString, int lenght) {
for (int i=0; i<lenght; i++)
pString += " ";
return pString;
}
I like TDD ;)
downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?
You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.
http://www.microsoft.com/en-us/download/details.aspx?id=1695
Per MSDN it is
By default, the maximum size of an Array is 2 gigabytes (GB).
In a 64-bit environment, you can avoid the size restriction by setting the enabled attribute of the gcAllowVeryLargeObjects configuration element to true in the run-time environment.
However, the array will still be limited to a total of 4 billion elements.
Refer Here http://msdn.microsoft.com/en-us/library/System.Array(v=vs.110).aspx
Note: Here I am focusing on the actual length of array by assuming that we will have enough hardware RAM.
I had this same problem just now, and found the reason was my editor (Visual Studio Code) was running against the wrong instance of python; I had it set to run again python bundled with tensorflow, I changed it to my Anaconda python and it worked.
That code looks like the route you want to take with a few changes.
You'll want to change the append method to look like this. I've changed it to accept the number 0, and to make it return this
so you can chain your appends.
StringBuilder.prototype.append = function (value) {
if (value || value === 0) {
this.strings.push(value);
}
return this;
}
In C, a string is actually stored as an array of characters, so the 'string pointer' is pointing to the first character. For instance,
char myString[] = "This is some text";
You can access any character as a simple char by using myString as an array, thus:
char myChar = myString[6];
printf("%c\n", myChar); // Prints s
Hope this helps! David
Right click your project > Run As > Run Configuration... > Java Application (in left side panel) - double click on it. That will create new configuration. click on search button under Main Class section and select your main class from it.
ary.GetLength(0)
ary.GetLength(1)
for 2 dimensional array
You can use
grep 'string1' filename | grep 'string2'
Or
grep 'string1.*string2\|string2.*string1' filename
I got exactly the same error in Windows 8 while trying to export decision tree digraph using tree.export_graphviz! Then I installed GraphViz from this link. And then I followed the below steps which resolved my issue:
The html that you posted should use some <br>
to actually have divs with different heights. Like this:
<div>
<div class="panel">
Line 1<br>
Line 2
</div>
<div class="panel">
Line 1<br>
Line 2<br>
Line 3<br>
Line 4
</div>
<div class="panel">
Line 1
</div>
<div class="panel">
Line 1<br>
Line 2
</div>
</div>
Apart from that, if you want a reference to the div with the max height you can do this:
var highest = null;
var hi = 0;
$(".panel").each(function(){
var h = $(this).height();
if(h > hi){
hi = h;
highest = $(this);
}
});
//highest now contains the div with the highest so lets highlight it
highest.css("background-color", "red");
a=[100,200,300,400,500]
def search(b):
try:
k=a.index(b)
return a[k]
except ValueError:
return 'not found'
print(search(500))
it'll return the object if found else it'll return "not found"
.card-img-top {
width: 100%;
height: 40vh;
object-fit: cover;
}
As shown above but when you add height i suggest using "vh" (Viewport Height units) for a more mobile-friendly experience.
I've created a gist testing some different ways of resolving promises, with results. It may be helpful to see the options that work.
In the absense of cache control directives that specify otherwise, a 301 redirect defaults to being cached without any expiry date.
That is, it will remain cached for as long as the browser's cache can accommodate it. It will be removed from the cache if you manually clear the cache, or if the cache entries are purged to make room for new ones.
You can verify this at least in Firefox by going to about:cache
and finding it under disk cache. It works this way in other browsers including Chrome and the Chromium based Edge, though they don't have an about:cache
for inspecting the cache.
In all browsers it is still possible to override this default behavior using caching directives, as described below:
If you don't want the redirect to be cached
This indefinite caching is only the default caching by these browsers in the absence of headers that specify otherwise. The logic is that you are specifying a "permanent" redirect and not giving them any other caching instructions, so they'll treat it as if you wanted it indefinitely cached.
The browsers still honor the Cache-Control and Expires headers like with any other response, if they are specified.
You can add headers such as Cache-Control: max-age=3600
or Expires: Thu, 01 Dec 2014 16:00:00 GMT
to your 301 redirects. You could even add Cache-Control: no-cache
so it won't be cached permanently by the browser or Cache-Control: no-store
so it can't even be stored in temporary storage by the browser.
Though, if you don't want your redirect to be permanent, it may be a better option to use a 302 or 307 redirect. Issuing a 301 redirect but marking it as non-cacheable is going against the spirit of what a 301 redirect is for, even though it is technically valid. YMMV, and you may find edge cases where it makes sense for a "permanent" redirect to have a time limit. Note that 302 and 307 redirects aren't cached by default by browsers.
If you previously issued a 301 redirect but want to un-do that
If people still have the cached 301 redirect in their browser they will continue to be taken to the target page regardless of whether the source page still has the redirect in place. Your options for fixing this include:
A simple solution is to issue another redirect back again.
If the browser is directed back to a same URL a second time during a redirect, it should fetch it from the origin again instead of redirecting again from cache, in an attempt to avoid a redirect loop. Comments on this answer indicate this now works in all major browsers - but there may be some minor browsers where it doesn't.
If you don't have control over the site where the previous redirect target went to, then you are out of luck. Try and beg the site owner to redirect back to you.
Prevention is better than cure - avoid a 301 redirect if you are not sure you want to permanently de-commission the old URL.
NO, when you are using only one "=" you are assigning the variable.
You must use "==" : You must use "===" :
if (somevar === '836e3ef9-53d4-414b-a401-6eef16ac01d6'){
$("#code").text(data.DATA[0].ID);
}
You could use fonction like .toLowerCase()
to avoid case problem if you want
Sure you can.
ALTER TABLE myTable ALTER COLUMN myColumn int NULL
Just substitute int for whatever datatype your column is.
Search All Files with Control+Shift+F or Console->[Search tab]
NOTE: Global Search shows up next to the CONSOLE menu
volatile
only guarantees that all threads, even themselves, are incrementing. For example: a counter sees the same face of the variable at the same time. It is not used instead of synchronized or atomic or other stuff, it completely makes the reads synchronized. Please do not compare it with other java keywords. As the example shows below volatile variable operations are also atomic they fail or succeed at once.
package io.netty.example.telnet;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static volatile int a = 0;
public static void main(String args[]) throws InterruptedException{
List<Thread> list = new ArrayList<Thread>();
for(int i = 0 ; i<11 ;i++){
list.add(new Pojo());
}
for (Thread thread : list) {
thread.start();
}
Thread.sleep(20000);
System.out.println(a);
}
}
class Pojo extends Thread{
int a = 10001;
public void run() {
while(a-->0){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
Main.a++;
System.out.println("a = "+Main.a);
}
}
}
Even you put volatile or not results will always differ. But if you use AtomicInteger as below results will be always same. This is same with synchronized also.
package io.netty.example.telnet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static volatile AtomicInteger a = new AtomicInteger(0);
public static void main(String args[]) throws InterruptedException{
List<Thread> list = new ArrayList<Thread>();
for(int i = 0 ; i<11 ;i++){
list.add(new Pojo());
}
for (Thread thread : list) {
thread.start();
}
Thread.sleep(20000);
System.out.println(a.get());
}
}
class Pojo extends Thread{
int a = 10001;
public void run() {
while(a-->0){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
Main.a.incrementAndGet();
System.out.println("a = "+Main.a);
}
}
}
The way I cam across this question was when I tried doing something similar where I was defining a function and it was being called with the array like others pointed out
You could do something like this however for this scenarios its less elegant compared to Sven's method.
sapply(a, function(x) afunc(x))
afunc<-function(a){
if (a>0){
a/sum(a)
}
else 1
}
I had to uninstall some external components like Postsharp and Apex and then it worked. I also tried the chosen solution but it gave me more errors.
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
For Oracle you can use LISTAGG
input { float: right; clear: both; }
Here's my modification of the OP's answer.
In short, many people who tried to optimize this complained that a loop was being used. Yes, while loops can be slow, other approaches can be inaccurate.
Therefore, my approach uses Binary Search to find the best Font Size:
$.fn.textfill = function()
{
var self = $(this);
var parent = self.parent();
var attr = self.attr('max-font-size');
var maxFontSize = parseInt(attr, 10);
var unit = attr.replace(maxFontSize, "");
var minFontSize = parseInt(self.attr('min-font-size').replace(unit, ""));
var fontSize = (maxFontSize + minFontSize) / 2;
var maxHeight = parent.height();
var maxWidth = parent.width();
var textHeight;
var textWidth;
do
{
self.css('font-size', fontSize + unit);
textHeight = self.height();
textWidth = self.width();
if(textHeight > maxHeight || textWidth > maxWidth)
{
maxFontSize = fontSize;
fontSize = Math.floor((fontSize + minFontSize) / 2);
}
else if(textHeight < maxHeight || textWidth < maxWidth)
{
minFontSize = fontSize;
fontSize = Math.floor((fontSize + maxFontSize) / 2);
}
else
break;
}
while(maxFontSize - minFontSize > 1 && maxFontSize > minFontSize);
self.css('font-size', fontSize + unit);
return this;
}
function resizeText()
{
$(".textfill").textfill();
}
$(document).ready(resizeText);
$(window).resize(resizeText);
This also allows the element to specify the minimum and maximum font:
<div class="container">
<div class="textfill" min-font-size="10px" max-font-size="72px">
Text that will fill the container, to the best of its abilities, and it will <i>never</i> have overflow.
</div>
</div>
Furthermore, this algorithm is unitless. You may specify em
, rem
, %
, etc. and it will use that for its final result.
Here's the Fiddle: https://jsfiddle.net/fkhqhnqe/1/
If you want to push your current detached HEAD (check git log
before), try:
git push origin HEAD:master
to send your detached HEAD into master branch at origin. If your push gets rejected, try git pull origin master
first to get the changes from origin. If you don't care about the changes from origin and it's rejected, because you did some intentional rebase and you want to replace origin/master with your currently detached branch - then you may force it (-f
). In case you lost some access to previous commits, you can always run git reflog
to see the history from all branches.
To get back on a master branch, while keeping the changes, try the following commands:
git rebase HEAD master
git checkout master
Logical address:- Logical address generated by the CPU . when we are give the problem to the computer then our computer pass the problem to the processor through logical address , which we are not seen this address called logical address .
Physical address :- when our processor create process and solve our problem then we store data in secondary memory through address called physical address
You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
I don't think the autoload -U colors && colors
is needed anymore and one can simply do:
PS1="%{%F{red}%}%n%{%f%}@%{%F{blue}%}%m %{%F{yellow}%}%~ %{$%f%}%% "
to achieve the same result as FireDude's answer. See the ZSH documentation for more info.
Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)
Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.
Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"
Reload your .bashrc file: source ~/.bashrc
Verify the latest cmake version is installed: cmake --version
You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.
To put what others have said in a pithier manner...
Exceptions are for Exceptional circumstances
If this method is pure data access layer, I would say that given some parameter that gets included in a select statement, it would expect that I may not find any rows from which to build an object, and therefore returning null would be acceptable as this is data access logic.
On the other hand, if I expected my parameter to reflect a primary key and I should only get one row back, if I got more than one back I would throw an exception. 0 is ok to return null, 2 is not.
Now, if I had some login code that checked against an LDAP provider then checked against a DB to get more details and I expected those should be in sync at all times, I might toss the exception then. As others said, it's business rules.
Now I'll say that is a general rule. There are times where you may want to break that. However, my experience and experiments with C# (lots of that) and Java(a bit of that) has taught me that it is much more expensive performance wise to deal with exceptions than to handle predictable issues via conditional logic. I'm talking to the tune of 2 or 3 orders of magnitude more expensive in some cases. So, if it's possible your code could end up in a loop, then I would advise returning null and testing for it.
There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that are defined in the List interface. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.
Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).
That's called polymorphism. You can read up on it.
Have you tried the Interpolation syntax?
background: url(#{$get-path-to-assets}/site/background.jpg) repeat-x fixed 0 0;
This answer has been updated to Swift 3
I always think it is nice to have a very simple, self-contained example so that nothing is assumed when I am learning a new task. This answer is that for deleting UITableView
rows. The project performs like this:
This project is based on the UITableView example for Swift.
Create a new project and replace the ViewController.swift code with the following.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// These strings will be the data for the table view cells
var animals: [String] = ["Horse", "Cow", "Camel", "Pig", "Sheep", "Goat"]
let cellReuseIdentifier = "cell"
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// It is possible to do the following three things in the Interface Builder
// rather than in code if you prefer.
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
tableView.delegate = self
tableView.dataSource = self
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = self.animals[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
// this method handles row deletion
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// remove the item from the data model
animals.remove(at: indexPath.row)
// delete the table view row
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Not used in our example, but if you were adding a new row, this is where you would do it.
}
}
}
The single key method in the code above that enables row deletion is the last one. Here it is again for emphasis:
// this method handles row deletion
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// remove the item from the data model
animals.remove(at: indexPath.row)
// delete the table view row
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Not used in our example, but if you were adding a new row, this is where you would do it.
}
}
Add a UITableView
to the View Controller in the storyboard. Use auto layout to pin the four sides of the table view to the edges of the View Controller. Control drag from the table view in the storyboard to the @IBOutlet var tableView: UITableView!
line in the code.
That's all. You should be able to run your app now and delete rows by swiping left and tapping "Delete".
Change the "Delete" button text
Add the following method:
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return "Erase"
}
Custom button actions
Add the following method.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
// action one
let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in
print("Edit tapped")
})
editAction.backgroundColor = UIColor.blue
// action two
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, indexPath) in
print("Delete tapped")
})
deleteAction.backgroundColor = UIColor.red
return [editAction, deleteAction]
}
Note that this is only available from iOS 8. See this answer for more details.
Updated for iOS 11
Actions can be placed either leading or trailing the cell using methods added to the UITableViewDelegate API in iOS 11.
func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
let editAction = UIContextualAction(style: .normal, title: "Edit", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
success(true)
})
editAction.backgroundColor = .blue
return UISwipeActionsConfiguration(actions: [editAction])
}
func tableView(_ tableView: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
let deleteAction = UIContextualAction(style: .normal, title: "Delete", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
success(true)
})
deleteAction.backgroundColor = .red
return UISwipeActionsConfiguration(actions: [deleteAction])
}
After insuring that the string "strOutput" has a correct XML structure, you can do this:
Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");
Would something like
(pattern.*?(pattern))*
work for you?
Edit:
The problem with this is that it uses the non-greedy operator *?
, which can require an awful lot of backtracking along the string instead of just looking at each letter once. What this means for you is that this could be slow for large gaps.
Try to change where Member class
public function users() {
return $this->hasOne('User');
}
return $this->belongsTo('User');
I think Amith Koujalgi is correct but also, in cases where the webservice responses are in JSON then it might be more useful to see the results in a clean JSON format instead of a very long string. Just add | grep }| python -mjson.tool to the end of curl commands here is two examples:
GET approach with JSON result
curl -i -H "Accept: application/json" http://someHostName/someEndpoint | grep }| python -mjson.tool
POST approach with JSON result
curl -X POST -H "Accept: Application/json" -H "Content-Type: application/json" http://someHostName/someEndpoint -d '{"id":"IDVALUE","name":"Mike"}' | grep }| python -mjson.tool
Python 3 includes an improved super() which allows use like this:
super().__init__(args)
From "The Principles of Object-Oriented Javascript" by Nicholas C. Zakas
But why an object when the type is null? (In fact, this has been acknowledged as an error by TC39, the committee that designs and maintains JavaScript. You could reason that null is an empty object pointer, making "object" a logical return value, but that’s still confusing.)
Zakas, Nicholas C. (2014-02-07). The Principles of Object-Oriented JavaScript (Kindle Locations 226-227). No Starch Press. Kindle Edition.
That said:
var game = null; //typeof(game) is "object"
game.score = 100;//null is not an object, what the heck!?
game instanceof Object; //false, so it's not an instance but it's type is object
//let's make this primitive variable an object;
game = {};
typeof(game);//it is an object
game instanceof Object; //true, yay!!!
game.score = 100;
Undefined case:
var score; //at this point 'score' is undefined
typeof(score); //'undefined'
var score.player = "felix"; //'undefined' is not an object
score instanceof Object; //false, oh I already knew that.
I tend to use Spring's Named JDBC Parameters so I can write a standard string like "select * from blah where colX=':someValue'"; I think that's pretty readable.
An alternative would be to supply the string in a separate .sql file and read the contents in using a utility method.
Oh, also worth having a look at Squill: https://squill.dev.java.net/docs/tutorial.html
try vertical-align: middle
also your code seems like it should be:
<form>_x000D_
<div>_x000D_
<input id="blah" type="checkbox"><label for="blah">Label text</label>_x000D_
</div>_x000D_
</form>
_x000D_
I had the same problem and the root cause was different:
I was logged in as a Test User of a different application. Therefore I wasn't able to authorize an app that's not the one where the Test User was created for.
When I logged out and logged in as a regular user or a Test User for the app I tried to authorize, everything was OK.
In ES5 there is no efficient way to iterate over a sparse array without using the length property. In ES6 you can use for...of
. Take this examples:
'use strict';_x000D_
_x000D_
var arr = ['one', 'two', undefined, 3, 4],_x000D_
output;_x000D_
_x000D_
arr[6] = 'five';_x000D_
_x000D_
output = '';_x000D_
arr.forEach(function (val) {_x000D_
output += val + ' ';_x000D_
});_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
output += arr[i] + ' ';_x000D_
}_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var val of arr) {_x000D_
output += val + ' ';_x000D_
};_x000D_
console.log(output);
_x000D_
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->_x000D_
<script src="//gh-canon.github.io/stack-snippet-console/console.min.js"></script>
_x000D_
All array methods which you can use to iterate safely over dense arrays use the length
property of an object created by calling ToObject
internaly. See for instance the algorithm used in the forEach
method: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18
However in es6, you can use for...of
safely for iterating over sparse arrays.
See also Are Javascript arrays sparse?.
You're very close. Use same type on both sides, and include ()
.
ArrayList<Class> myArray = new ArrayList<Class>();
No valid Kits found The problem occurs because qt-creator don't know the versions of your qt, your compiler or your debugger. First off, let's solve the Qt versions. It may normally solve the others too ;).
You try to create a new project, run select a kit and then there is no kit available in the list.
Follow the steps:
Yes I ...
Hope it's help ;)
pip install --trusted-host=pypi.org --trusted-host=files.pythonhosted.org opencv-python
.As mentioned above, you need the autoreload
extension. If you want it to automatically start every time you launch ipython
, you need to add it to the ipython_config.py
startup file:
It may be necessary to generate one first:
ipython profile create
Then include these lines in ~/.ipython/profile_default/ipython_config.py
:
c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
As well as an optional warning in case you need to take advantage of compiled Python code in .pyc
files:
c.InteractiveShellApp.exec_lines.append('print "Warning: disable autoreload in ipython_config.py to improve performance." ')
edit: the above works with version 0.12.1 and 0.13
There is a hotkey, mapped by default to Ctrl+Shift+NUM_KEYPAD_DIVIDE.
You can change it to something else via Window -> Preferences, search for "Keys", then for "Collapse All".
To open all code blocks the shortcut is Ctrl+Shift+NUM_KEYPAD_MULTIPLY.
In the Eclipse extension PyDev, close all code blocks is Ctrl + 9
To open all blocks, is Ctrl + 0
Xamarin
Label.Font = UIFont.FromName("Copperplate", 10.0f);
Swift
text.font = UIFont.init(name: "Poppins-Regular", size: 14)
To get the list of font family Github/IOS-UIFont-Names
I would like to add recommendations from oracle trouble shooting article.
Exception in thread thread_name: java.lang.OutOfMemoryError: Java heap space
The detail message Java heap space indicates object could not be allocated in the Java heap. This error does not necessarily imply a memory leak
Possible causes:
Simple configuration issue, where the specified heap size is insufficient for the application.
Application is unintentionally holding references to objects, and this prevents the objects from being garbage collected.
Excessive use of finalizers.
One other potential source of this error arises with applications that make excessive use of finalizers. If a class has a finalize method, then objects of that type do not have their space reclaimed at garbage collection time
After garbage collection, the objects are queued for finalization, which occurs at a later time. finalizers are executed by a daemon thread that services the finalization queue. If the finalizer thread cannot keep up with the finalization queue, then the Java heap could fill up and this type of OutOfMemoryError exception would be thrown.
One scenario that can cause this situation is when an application creates high-priority threads that cause the finalization queue to increase at a rate that is faster than the rate at which the finalizer thread is servicing that queue.
If you are building a client with Resttemplate, you can only set the endpoint like this: https://IP/path_to_service and set the requestFactory.
With this solution you don't need to RESTART your TOMCAT or Apache:
public static HttpComponentsClientHttpRequestFactory requestFactory(CloseableHttpClient httpClient) {
TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
};
SSLContext sslContext = null;
try {
sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
final SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext,hostnameVerifier);
final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new PlainConnectionSocketFactory())
.register("https", csf)
.build();
final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(100);
httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.setConnectionManager(cm)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
return requestFactory;
}
If you are looking to block the execution of code with call to sleep
, then no, there is no method for that in JavaScript
.
JavaScript
does have setTimeout
method. setTimeout
will let you defer execution of a function for x milliseconds.
setTimeout(myFunction, 3000);
// if you have defined a function named myFunction
// it will run after 3 seconds (3000 milliseconds)
Remember, this is completely different from how sleep
method, if it existed, would behave.
function test1()
{
// let's say JavaScript did have a sleep function..
// sleep for 3 seconds
sleep(3000);
alert('hi');
}
If you run the above function, you will have to wait for 3 seconds (sleep
method call is blocking) before you see the alert 'hi'. Unfortunately, there is no sleep
function like that in JavaScript
.
function test2()
{
// defer the execution of anonymous function for
// 3 seconds and go to next line of code.
setTimeout(function(){
alert('hello');
}, 3000);
alert('hi');
}
If you run test2, you will see 'hi' right away (setTimeout
is non blocking) and after 3 seconds you will see the alert 'hello'.
$(".ui-widget-overlay").click (function () {
$("#dialog-id").dialog( "close" );
});
Fiddle showing the above code in action.
To replace multiples columns convert to numpy array using .values
:
df.loc[df.A==0, ['B', 'C']] = df.loc[df.A==0, ['B', 'C']].values / 2
Try Like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class UserController extends Controller
{
function index(){
$users = DB::table('users')->get();
foreach ($users as $user)
{
var_dump($user->name);
}
}
}
?>
Is the standard procedure not working?
git stash save
git branch xxx HEAD
git checkout xxx
git stash pop
Shorter:
git stash
git checkout -b xxx
git stash pop
BEGIN;
INSERT INTO test_b (price_sum)
SELECT price
FROM test_a;
INSERT INTO test_c (price_summ)
SELECT price
FROM test_a;
COMMIT;
Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:
public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
{
$result = $this->model->with($with);
$dataSet = $result->where($where)
// Conditionally use $orderBy if not empty
->when(!empty($orderBy), function ($query) use ($orderBy) {
// Break $orderBy into pairs
$pairs = array_chunk($orderBy, 2);
// Iterate over the pairs
foreach ($pairs as $pair) {
// Use the 'splat' to turn the pair into two arguments
$query->orderBy(...$pair);
}
})
->paginate($limit)
->appends(Input::except('page'));
return $dataSet;
}
Now, you can make your call like this:
$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);
If the array is unsorted, you will need to use linear search.
@qbzenker provided the most idiomatic method IMO
Here are a few alternatives:
In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
Col1 Col2 Col3
1 0 NaN 0.0
In [29]: df[np.isnan(df.Col2)]
Out[29]:
Col1 Col2 Col3
1 0 NaN 0.0
//It is working
#include<iostream>
using namespace std;
void main()
{
int a[5];
int temp=0;
cout<<"Enter Values"<<endl;
for(int i=0;i<5;i++)
{
cin>>a[i];
}
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
cout<<"Asending Series"<<endl;
for(int i=0;i<5;i++)
{
cout<<endl;
cout<<a[i]<<endl;
}
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
if(a[i]<a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
cout<<"Desnding Series"<<endl;
for(int i=0;i<5;i++)
{
cout<<endl;
cout<<a[i]<<endl;
}
}
It might be easier for you to understand using Functionoids which are expressively neater and more powerful to use, see this excellent and highly recommended C++ FAQ lite, in particular, look at section 33.12 onwards, but nonetheless, read it from the start of that section to gain a grasp and understanding of it.
To answer your question:
typedef void (*foobar)() fubarfn;
void Fun(fubarfn& baz){
fubarfn = baz;
baz();
}
Edit:
&
means the reference address*
means the value of what's contained at the reference address, called de-referencingSo using the reference, example below, shows that we are passing in a parameter, and directly modify it.
void FunByRef(int& iPtr){
iPtr = 2;
}
int main(void){
// ...
int n;
FunByRef(n);
cout << n << endl; // n will have value of 2
}
This should work, since your state will change after the Ajax call, and the parent component will re-render.
render : function () {
var item;
if (this.state.isRequired) {
item = <MyOwnInput attribute={'whatever'} />
} else {
item = <MyOwnInput />
}
return (
<div>
{item}
</div>
);
}
I recently came to this question because the usual suspects were not working with linked packages. If you're like me and are taking advantage of npm link
during development to effectively work on a project that is made up of many packages, it's important that changes that occur in dependencies trigger a reload as well.
After having tried node-mon and pm2, even following their instructions for additionally watching the node_modules folder, they still did not pick up changes. Although there are some custom solutions in the answers here, for something like this, a separate package is cleaner. I came across node-dev today and it works perfectly without any options or configuration.
From the Readme:
In contrast to tools like supervisor or nodemon it doesn't scan the filesystem for files to be watched. Instead it hooks into Node's require() function to watch only the files that have been actually required.
I recently ran into the same problem, and found a workaround though it'll only be useful if you can change the html code to suit.
I used tables to achieve my padded layout, so to create the equivalent of a div with internal padding I made a table with 3 columns/3 rows and put the content in the centre row/column. The first and last columns/rows are used for the padding.
eg.
<table>
<tr>
<td width="10"> </td>
<td> </td>
<td width="10"> </td>
</tr>
<tr>
<td> </td>
<td>content goes here</td>
<td> </td>
</tr>
<tr>
<td width="10"> </td>
<td> </td>
<td width="10"> </td>
</tr>
</table>
Hope that helps.
Joe
support for document.location
is also good though its a deprecated method.
I've been using this method for a while with no problems.
you can refer here for more details:
https://developer.mozilla.org/en-US/docs/Web/API/document.location
Compile with O3, The compiler performs optimization well.
q = x / y;
if (x % y) ++q;
You can use ajax upload to preview your selected file.. http://zurb.com/playground/ajax-upload
Another way of doing this is using border-image in combination with a linear-gradient.
div {_x000D_
width: 100px;_x000D_
height: 75px;_x000D_
background-color: green;_x000D_
background-clip: content-box; /* so that the background color is not below the border */_x000D_
_x000D_
border-left: 5px solid black;_x000D_
border-image: linear-gradient(to top, #000 50%, rgba(0,0,0,0) 50%); /* to top - at 50% transparent */_x000D_
border-image-slice: 1;_x000D_
}
_x000D_
<div></div>
_x000D_
jsfiddle: https://jsfiddle.net/u7zq0amc/1/
Browser Support: IE: 11+
Chrome: all
Firefox: 15+
For a better support also add vendor prefixes.
in bootstrap v4, i center and fill the carousel img to the screen using
<img class="d-block mx-auto" max-width="100%" max-height="100%">
pretty sure this requires parent elements' height or width to be set
html,body{height:100%;}
.carousel,.carousel-item,.active{height:100%;}
.carousel-inner{height:100%;}
If you're going to say that HTML is a programming language, then you might as well include things such as word documents, as they too are based on ML, or 'Markup Language'.
So, no, HTML is a not a programming language. It is called "markup" for that reason.
Simply put--HTML defines content!
Thanks to cryo for improved version that I based my tested code below:
#Instead of adding silence at start and end of recording (values=0) I add the original audio . This makes audio sound more natural as volume is >0. See trim()
#I also fixed issue with the previous code - accumulated silence counter needs to be cleared once recording is resumed.
from array import array
from struct import pack
from sys import byteorder
import copy
import pyaudio
import wave
THRESHOLD = 500 # audio levels not normalised.
CHUNK_SIZE = 1024
SILENT_CHUNKS = 3 * 44100 / 1024 # about 3sec
FORMAT = pyaudio.paInt16
FRAME_MAX_VALUE = 2 ** 15 - 1
NORMALIZE_MINUS_ONE_dB = 10 ** (-1.0 / 20)
RATE = 44100
CHANNELS = 1
TRIM_APPEND = RATE / 4
def is_silent(data_chunk):
"""Returns 'True' if below the 'silent' threshold"""
return max(data_chunk) < THRESHOLD
def normalize(data_all):
"""Amplify the volume out to max -1dB"""
# MAXIMUM = 16384
normalize_factor = (float(NORMALIZE_MINUS_ONE_dB * FRAME_MAX_VALUE)
/ max(abs(i) for i in data_all))
r = array('h')
for i in data_all:
r.append(int(i * normalize_factor))
return r
def trim(data_all):
_from = 0
_to = len(data_all) - 1
for i, b in enumerate(data_all):
if abs(b) > THRESHOLD:
_from = max(0, i - TRIM_APPEND)
break
for i, b in enumerate(reversed(data_all)):
if abs(b) > THRESHOLD:
_to = min(len(data_all) - 1, len(data_all) - 1 - i + TRIM_APPEND)
break
return copy.deepcopy(data_all[_from:(_to + 1)])
def record():
"""Record a word or words from the microphone and
return the data as an array of signed shorts."""
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK_SIZE)
silent_chunks = 0
audio_started = False
data_all = array('h')
while True:
# little endian, signed short
data_chunk = array('h', stream.read(CHUNK_SIZE))
if byteorder == 'big':
data_chunk.byteswap()
data_all.extend(data_chunk)
silent = is_silent(data_chunk)
if audio_started:
if silent:
silent_chunks += 1
if silent_chunks > SILENT_CHUNKS:
break
else:
silent_chunks = 0
elif not silent:
audio_started = True
sample_width = p.get_sample_size(FORMAT)
stream.stop_stream()
stream.close()
p.terminate()
data_all = trim(data_all) # we trim before normalize as threshhold applies to un-normalized wave (as well as is_silent() function)
data_all = normalize(data_all)
return sample_width, data_all
def record_to_file(path):
"Records from the microphone and outputs the resulting data to 'path'"
sample_width, data = record()
data = pack('<' + ('h' * len(data)), *data)
wave_file = wave.open(path, 'wb')
wave_file.setnchannels(CHANNELS)
wave_file.setsampwidth(sample_width)
wave_file.setframerate(RATE)
wave_file.writeframes(data)
wave_file.close()
if __name__ == '__main__':
print("Wait in silence to begin recording; wait in silence to terminate")
record_to_file('demo.wav')
print("done - result written to demo.wav")
SEARCH
does not return 0
if there is no match, it returns #VALUE!
. So you have to wrap calls to SEARCH
with IFERROR
.
For example...
=IF(IFERROR(SEARCH("cat", A1), 0), "cat", "none")
or
=IF(IFERROR(SEARCH("cat",A1),0),"cat",IF(IFERROR(SEARCH("22",A1),0),"22","none"))
Here, IFERROR
returns the value from SEARCH
when it works; the given value of 0
otherwise.
An instance might be corrupted or not updated properly.
Try these Commands:
C:\>sqllocaldb stop MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" stopped.
C:\>sqllocaldb delete MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" deleted.
C:\>sqllocaldb create MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" created with version 13.0.1601.5.
C:\>sqllocaldb start MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" started.
Here is your code. I'm assuming you're using python 3 based on the your use of print()
and input()
:
import random
def main():
#random.seed() --> don't need random.seed()
#Prompts the user to enter the number of tickets they wish to play.
#python 3 version:
tickets = int(input("How many lottery tickets do you want?\n"))
#Creates the dictionaries "winning_numbers" and "guess." Also creates the variable "winnings" for total amount of money won.
winning_numbers = []
winnings = 0
#Generates the winning lotto numbers.
for i in range(tickets * 5):
#del winning_numbers[:] what is this line for?
randNum = random.randint(1,30)
while randNum in winning_numbers:
randNum = random.randint(1,30)
winning_numbers.append(randNum)
print(winning_numbers)
guess = getguess(tickets)
nummatches = checkmatch(winning_numbers, guess)
print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")
winningRanks = [0, 0, 10, 500, 20000, 1000000]
winnings = sum(winningRanks[:nummatches + 1])
print("You won a total of",winnings,"with",tickets,"tickets.\n")
#Gets the guess from the user.
def getguess(tickets):
guess = []
for i in range(tickets):
bubble = [int(i) for i in input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split()]
guess.extend(bubble)
print(bubble)
return guess
#Checks the user's guesses with the winning numbers.
def checkmatch(winning_numbers, guess):
match = 0
for i in range(5):
if guess[i] == winning_numbers[i]:
match += 1
return match
main()
Can be done in major new broswers using the code below
.img {
-webkit-filter:invert(100%);
filter:progid:DXImageTransform.Microsoft.BasicImage(invert='1');
}
However, if you want it to work across all browsers you need to use Javascript. Something like this gist will do the job.
const crypto = require('crypto')
crypto.createHash('md5').update('hello world').digest('hex')
Code snippet above computes MD5 hex string for string hello world
The advantage of this solution is you don't need to install additional library.
I think built in solution should be the fastest. If not, we should create issue/PR for the Node.js project.
Since everything is an expression, and thus results in a value, you can just use if/else
.
a = if true then 5 else 10
a = if false then 5 else 10
You can see more about expression examples here.
you must have record in table or array record in database.
example:
SELECT * FROM tabel_record
WHERE table_record.fieldName IN (SELECT fieldName FROM table_reference);
You may calculate the moving average of a vector x
with a window width of k
by:
apply(embed(x, k), 1, mean)
In My case (Using Javascript insidde Razor) This worked perfectly inside an Foreach loop
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, this);
});
When you make a call to using namespace <some_namespace>;
all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.
E.g. if you add using namespace std;
you can write just cout
instead of std::cout
when calling the operator cout
defined in the namespace std
.
This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace
you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:
#include <iostream>
using std::cout;
int main() {
cout << "Hello world!";
return 0;
}