From CLR via C#:
When normalizing strings, it is highly recommended that you use ToUpperInvariant instead of ToLowerInvariant because Microsoft has optimized the code for performing uppercase comparisons.
I remember one time my coworker always changed strings to uppercase before comparing. I've always wondered why he does that because I feel it's more "natural" to convert to lowercase first. After reading the book now I know why.
When using command extensions shell options in a script, it is HIGHLY suggested that you do the following trick at the beginning of your scripts.
-- Information pasted from http://www.ss64.com/nt/setlocal.html
SETLOCAL will set an ERRORLEVEL if given an argument. It will be zero if one of the two valid arguments is given and one otherwise.
You can use this in a batch file to determine if command extensions are available, using the following technique:
VERIFY errors 2>nul
SETLOCAL ENABLEEXTENSIONS
IF ERRORLEVEL 1 echo Unable to enable extensions
This works because "VERIFY errors" sets ERRORLEVEL to 1 and then the SETLOCAL will fail to reset the ERRORLEVEL value if extensions are not available (e.g. if the script is running under command.com)
If Command Extensions are permanently disabled then SETLOCAL ENABLEEXTENSIONS will not restore them.
__slots__
is a nice way to save memory, but it's very hard to get a dict of the values of the object. Imagine the following object:
class Point(object):
__slots__ = ('x', 'y')
Now that object obviously has two attributes. Now we can create an instance of it and build a dict of it this way:
>>> p = Point()
>>> p.x = 3
>>> p.y = 5
>>> dict((k, getattr(p, k)) for k in p.__slots__)
{'y': 5, 'x': 3}
This however won't work if point was subclassed and new slots were added. However Python automatically implements __reduce_ex__
to help the copy
module. This can be abused to get a dict of values:
>>> p.__reduce_ex__(2)[2][1]
{'y': 5, 'x': 3}
JavaScript
var myObj = {
id: "c001",
name: "Hello Test"
}
Result(JSON)
{
"id": "c001",
"name": "Hello Test"
}
You can use for loop if you really want to.
char table[][] table = new char[row][col];
for(int i = 0; i < row * col ; ++i){
table[i/row][i % col] = char('a' + (i+1));
}
or do what bhesh said.
You can use $expr ( 3.6 mongo version operator ) to use aggregation functions in regular query.
Compare query operators
vs aggregation comparison operators
.
db.accommodations.find({$expr:{$gt:[{$size:"$name"}, 1]}})
Make sure the name of the directory in which the .sh file is present does not have a space character. e.g: Say if it is in a folder called 'New Folder', you're bound to come across the error that you've cited. Instead just name it as 'New_Folder'. I hope this helps.
A KeyError
generally means the key doesn't exist. So, are you sure the path
key exists?
From the official python docs:
exception KeyError
Raised when a mapping (dictionary) key is not found in the set of existing keys.
For example:
>>> mydict = {'a':'1','b':'2'}
>>> mydict['a']
'1'
>>> mydict['c']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'c'
>>>
So, try to print the content of meta_entry
and check whether path
exists or not.
>>> mydict = {'a':'1','b':'2'}
>>> print mydict
{'a': '1', 'b': '2'}
Or, you can do:
>>> 'a' in mydict
True
>>> 'c' in mydict
False
var format = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
// ^ ^
document.write(format.test("My @string-with(some%text)") + "<br/>");
document.write(format.test("My string with spaces") + "<br/>");
document.write(format.test("My StringContainingNoSpecialChars"));
_x000D_
Try this.Vals.replace(/("|')/g, "")
I had the same problem, this is what I ended up doing:
function parseMillisecondsIntoReadableTime(milliseconds){_x000D_
//Get hours from milliseconds_x000D_
var hours = milliseconds / (1000*60*60);_x000D_
var absoluteHours = Math.floor(hours);_x000D_
var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;_x000D_
_x000D_
//Get remainder from hours and convert to minutes_x000D_
var minutes = (hours - absoluteHours) * 60;_x000D_
var absoluteMinutes = Math.floor(minutes);_x000D_
var m = absoluteMinutes > 9 ? absoluteMinutes : '0' + absoluteMinutes;_x000D_
_x000D_
//Get remainder from minutes and convert to seconds_x000D_
var seconds = (minutes - absoluteMinutes) * 60;_x000D_
var absoluteSeconds = Math.floor(seconds);_x000D_
var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;_x000D_
_x000D_
_x000D_
return h + ':' + m + ':' + s;_x000D_
}_x000D_
_x000D_
_x000D_
var time = parseMillisecondsIntoReadableTime(86400000);_x000D_
_x000D_
alert(time);
_x000D_
With C# String formatting you can avoid the multiplication by 100 as it will make the code shorter and cleaner especially because of less brackets and also the rounding up code can be avoided.
(current / maximum).ToString("0.00%");
// Output - 16.67%
For changing visibility:
predictbtn.setVisibility(View.INVISIBLE);
For removing:
predictbtn.setVisibility(View.GONE);
You need to implement a custom Authenticator
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
class GMailAuthenticator extends Authenticator {
String user;
String pw;
public GMailAuthenticator (String username, String password)
{
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
Now use it in the Session
Session session = Session.getInstance(props, new GMailAuthenticator(username, password));
Also check out the JavaMail FAQ
You should simply apply the following transformation to your input data array.
input_data = input_data.reshape((-1, image_side1, image_side2, channels))
You just need to use the Gradle Application plugin:
apply plugin:'application'
mainClassName = "org.gradle.sample.Main"
And then simply gradle run
.
As Teresa points out, you can also configure mainClassName
as a system property and run with a command line argument.
You can make the id the primary key, and set member_id to NOT NULL UNIQUE
. (Which you've done.) Columns that are NOT NULL UNIQUE
can be the target of foreign key references, just like a primary key can. (I'm pretty sure that's true of all SQL platforms.)
At the conceptual level, there's no difference between PRIMARY KEY
and NOT NULL UNIQUE
. At the physical level, this is a MySQL issue; other SQL platforms will let you use a sequence without making it the primary key.
But if performance is really important, you should think twice about widening your table by four bytes per row for that tiny visual convenience. In addition, if you switch to INNODB in order to enforce foreign key constraints, MySQL will use your primary key in a clustered index. Since you're not using your primary key, I imagine that could hurt performance.
While a few of these answers will get you in the ballpark, you cannot do what you're trying to do with arbitrary dates for SqlServer 2005 and earlier because of daylight savings time. Using the difference between the current local and current UTC will give me the offset as it exists today. I have not found a way to determine what the offset would have been for the date in question.
That said, I know that SqlServer 2008 provides some new date functions that may address that issue, but folks using an earlier version need to be aware of the limitations.
Our approach is to persist UTC and perform the conversion on the client side where we have more control over the conversion's accuracy.
On Debian/Ubuntu:
aptitude install python-numpy
On Windows, download the installer:
http://sourceforge.net/projects/numpy/files/NumPy/
On other systems, download the tar.gz and run the following:
$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install
As far as i know that is impossible and that makes sense since what you are trying to do is against the idea of tabular data presentation. You could however put the data in multiple tables and remove any padding and margins in between them to achieve the same result, at least visibly. Something along the lines of:
<html>_x000D_
_x000D_
<head>_x000D_
<style type="text/css">_x000D_
.mytable {_x000D_
border-collapse: collapse;_x000D_
width: 100%;_x000D_
background-color: white;_x000D_
}_x000D_
.mytable-head {_x000D_
border: 1px solid black;_x000D_
margin-bottom: 0;_x000D_
padding-bottom: 0;_x000D_
}_x000D_
.mytable-head td {_x000D_
border: 1px solid black;_x000D_
}_x000D_
.mytable-body {_x000D_
border: 1px solid black;_x000D_
border-top: 0;_x000D_
margin-top: 0;_x000D_
padding-top: 0;_x000D_
margin-bottom: 0;_x000D_
padding-bottom: 0;_x000D_
}_x000D_
.mytable-body td {_x000D_
border: 1px solid black;_x000D_
border-top: 0;_x000D_
}_x000D_
.mytable-footer {_x000D_
border: 1px solid black;_x000D_
border-top: 0;_x000D_
margin-top: 0;_x000D_
padding-top: 0;_x000D_
}_x000D_
.mytable-footer td {_x000D_
border: 1px solid black;_x000D_
border-top: 0;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<table class="mytable mytable-head">_x000D_
<tr>_x000D_
<td width="25%">25</td>_x000D_
<td width="50%">50</td>_x000D_
<td width="25%">25</td>_x000D_
</tr>_x000D_
</table>_x000D_
<table class="mytable mytable-body">_x000D_
<tr>_x000D_
<td width="50%">50</td>_x000D_
<td width="30%">30</td>_x000D_
<td width="20%">20</td>_x000D_
</tr>_x000D_
</table>_x000D_
<table class="mytable mytable-body">_x000D_
<tr>_x000D_
<td width="16%">16</td>_x000D_
<td width="68%">68</td>_x000D_
<td width="16%">16</td>_x000D_
</tr>_x000D_
</table>_x000D_
<table class="mytable mytable-footer">_x000D_
<tr>_x000D_
<td width="20%">20</td>_x000D_
<td width="30%">30</td>_x000D_
<td width="50%">50</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I don't know your requirements but i'm sure there's a more elegant solution.
If the values are integer then you can use [2-3]
or you can use [5,7,8]
for non continuous values.
#!/bin/bash
while [ $# -gt 0 ];
do
case $1 in
1)
echo "one"
;;
[2-3])
echo "two or three"
;;
[4-6])
echo "four to six"
;;
[7,9])
echo "seven or nine"
;;
*)
echo "others"
;;
esac
shift
done
If the values are string then you can use |
.
#!/bin/bash
while [ $# -gt 0 ];
do
case $1 in
"one")
echo "one"
;;
"two" | "three")
echo "two or three"
;;
*)
echo "others"
;;
esac
shift
done
There are 3 main possibilities to execute a function:
var callback = function(x, y) {
// "this" may be different depending how you call the function
alert(this);
};
The method you choose depends whether:
Docs for Function.call, Function.apply
If you have a SOCK_STREAM
socket, recv
just gets "up to the first 3000 bytes" from the stream. There is no clear guidance on how big to make the buffer: the only time you know how big a stream is, is when it's all done;-).
If you have a SOCK_DGRAM
socket, and the datagram is larger than the buffer, recv
fills the buffer with the first part of the datagram, returns -1, and sets errno to EMSGSIZE. Unfortunately, if the protocol is UDP, this means the rest of the datagram is lost -- part of why UDP is called an unreliable protocol (I know that there are reliable datagram protocols but they aren't very popular -- I couldn't name one in the TCP/IP family, despite knowing the latter pretty well;-).
To grow a buffer dynamically, allocate it initially with malloc
and use realloc
as needed. But that won't help you with recv
from a UDP source, alas.
try document.getElementById('<%=Label1.ClientID%>').text or innerHTML OTHERWISE LOAD JQUERY SCRIPT AND put your code as it is....
If you were open to using JQuery, you could modify the background color for any link that has the property aria-expanded
set to true by doing the following...
$("a[aria-expanded='true']").css("background-color", "#42DCA3");
Depending on how specific you want to be regarding which links this applies to, you may have to slightly modify your selector.
From MySQL 5.7 onwards, this is possible, but requires first enabling the mdl
instrument in the performance_schema.setup_instruments
table. You can do this temporarily (until the server is next restarted) by running:
UPDATE performance_schema.setup_instruments
SET enabled = 'YES'
WHERE name = 'wait/lock/metadata/sql/mdl';
Or permanently, by adding the following incantation to the [mysqld]
section of your my.cnf
file (or whatever config files MySQL reads from on your installation):
[mysqld]
performance_schema_instrument = 'wait/lock/metadata/sql/mdl=ON'
(Naturally, MySQL will need to be restarted to make the config change take effect if you take the latter approach.)
Locks you take out after the mdl
instrument has been enabled can be seen by running a SELECT
against the performance_schema.metadata_locks
table. As noted in the docs, GET_LOCK
locks have an OBJECT_TYPE
of 'USER LEVEL LOCK'
, so we can filter our query down to them with a WHERE
clause:
mysql> SELECT GET_LOCK('foobarbaz', -1);
+---------------------------+
| GET_LOCK('foobarbaz', -1) |
+---------------------------+
| 1 |
+---------------------------+
1 row in set (0.00 sec)
mysql> SELECT * FROM performance_schema.metadata_locks
-> WHERE OBJECT_TYPE='USER LEVEL LOCK'
-> \G
*************************** 1. row ***************************
OBJECT_TYPE: USER LEVEL LOCK
OBJECT_SCHEMA: NULL
OBJECT_NAME: foobarbaz
OBJECT_INSTANCE_BEGIN: 139872119610944
LOCK_TYPE: EXCLUSIVE
LOCK_DURATION: EXPLICIT
LOCK_STATUS: GRANTED
SOURCE: item_func.cc:5482
OWNER_THREAD_ID: 35
OWNER_EVENT_ID: 3
1 row in set (0.00 sec)
mysql>
The meanings of the columns in this result are mostly adequately documented at https://dev.mysql.com/doc/refman/en/metadata-locks-table.html, but one point of confusion is worth noting: the OWNER_THREAD_ID
column does not contain the connection ID (like would be shown in the PROCESSLIST
or returned by CONNECTION_ID()
) of the thread that holds the lock. Confusingly, the term "thread ID" is sometimes used as a synonym of "connection ID" in the MySQL documentation, but this is not one of those times. If you want to determine the connection ID of the connection that holds a lock (for instance, in order to kill that connection with KILL
), you'll need to look up the PROCESSLIST_ID
that corresponds to the THREAD_ID
in the performance_schema.threads
table. For instance, to kill the connection that was holding my lock above...
mysql> SELECT OWNER_THREAD_ID FROM performance_schema.metadata_locks
-> WHERE OBJECT_TYPE='USER LEVEL LOCK'
-> AND OBJECT_NAME='foobarbaz';
+-----------------+
| OWNER_THREAD_ID |
+-----------------+
| 35 |
+-----------------+
1 row in set (0.00 sec)
mysql> SELECT PROCESSLIST_ID FROM performance_schema.threads
-> WHERE THREAD_ID=35;
+----------------+
| PROCESSLIST_ID |
+----------------+
| 10 |
+----------------+
1 row in set (0.00 sec)
mysql> KILL 10;
Query OK, 0 rows affected (0.00 sec)
After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).
A quick rerun of your data:
In [25]: df.hist(column='Trip_distance')
Prints out absolutely fine.
The df.hist
function comes with an optional keyword argument bins=10
which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:
In [34]: df.hist(column='Trip_distance', bins=50)
Create a second enum, for your DB containing the following:
enum DBGroupTypes
{
OEM = 0,
CMB = 1
}
Now, you can use Enum.Parse to retrieve the correct DBGroupTypes value from the strings "OEM" and "CMB". You can then convert those to int and retrieve the correct values from the right enumeration you want to use further in your model.
If you must have a UITextField with 2 lines of text, one option is to add a UILabel as a subview of the UITextField for the second line of text. I have a UITextField in my app that users often do not realize is editable by tapping, and I wanted to add some small subtitle text that says "Tap to Edit" to the UITextField.
CGFloat tapLlblHeight = 10;
UILabel *tapEditLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, textField.frame.size.height - tapLlblHeight - 2, 70, tapLlblHeight)];
tapEditLbl.backgroundColor = [UIColor clearColor];
tapEditLbl.textColor = [UIColor whiteColor];
tapEditLbl.text = @"Tap to Edit";
[textField addSubview:tapEditLbl];
DECLARE @theDate DATETIME
SET @theDate = '2010-01-01'
Then change your query to use this logic:
AND
(
tblWO.OrderDate > DATEADD(MILLISECOND, -1, @theDate)
AND tblWO.OrderDate < DATEADD(DAY, 1, @theDate)
)
Below mentioned link gives the clear explanation with example.
http://www.aspsnippets.com/Articles/Open-Show-jQuery-UI-Dialog-Modal-Popup-on-Button-Click.aspx
Code from the same link
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("#dialog").dialog({
modal: true,
autoOpen: false,
title: "jQuery Dialog",
width: 300,
height: 150
});
$("#btnShow").click(function () {
$('#dialog').dialog('open');
});
});
</script>
<input type="button" id="btnShow" value="Show Popup" />
<div id="dialog" style="display: none" align = "center">
This is a jQuery Dialog.
</div>
I have encountered that problem myself and I made my launchers in a .bat so you could choose the version you want to launch.
The only problem is your .py must be in the python folder, but anyway here is the code:
For Python2
@echo off
title Python2 Launcher by KinDa
cls
echo Type the exact version of Python you use (eg. 23, 24, 25, 26)
set/p version=
cls
echo Type the file you want to launch without .py (eg. hello world, calculator)
set/p launch=
path = %PATH%;C:\Python%version%
cd C:\Python%version%
python %launch%.py
pause
For Python3
@echo off
title Python3 Launcher by KinDa
cls
echo Type the exact version of Python you use (eg. 31, 32, 33, 34)
set/p version=
cls
echo Type the file you want to launch without .py (eg. hello world, calculator)
set/p launch=
cls
set path = %PATH%:C:\Python%version%
cd C:\Python%version%
python %launch%.py
pause
Save them as .bat and follow the instructions inside.
You can use this in app.js
file .
var apiurl = express.Router();
apiurl.use(function(req, res, next) {
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
next();
});
app.use('/', apiurl);
In your question, it seems that you want to avoid rounding the numbers as well? I think .format() will round the numbers using half-up, afaik?
so if you want to round, 200.3456 should be 200.35 for a precision of 2. but in your case, if you just want the first 2 and then discard the rest?
You could multiply it by 100 and then cast to an int (or taking the floor of the number), before dividing by 100 again.
200.3456 * 100 = 20034.56;
(int) 20034.56 = 20034;
20034/100.0 = 200.34;
You might have issues with really really big numbers close to the boundary though. In which case converting to a string and substring'ing it would work just as easily.
By the way, in the question above:
For:
Hello, my name is bob
Find part:
my name is (\w)+
With replace part:
my name used to be \1
Would return:
Hello, my name used to be b
Change find part to:
my name is (\w+)
And replace will be what you expect:
Hello, my name used to be bob
While (\w)+ will match "bob", it is not the grouping you want for replacement.
I had this very same issue.
However I was using bootbox.js, so it could have been something to do with that.
Either way, I realised that the issue was being caused by having an element with the same class as it's parent. When one of these elements is used to bind a click function to display the modal, then the problem occurs.
i.e. this is what causes the problem:
<div class="myElement">
<div class="myElement">
Click here to show modal
</div>
</div>
change it so that the element being clicked on doesn't have the same class as it's parent, any of it's children, or any other ancestors. It's probably good practice to do this in general when binding click functions.
See this JSFiddle
input[type="text"]_x000D_
{_x000D_
border: 0;_x000D_
border-bottom: 1px solid red;_x000D_
outline: 0;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
</form>
_x000D_
This is an old question, but I stumbled onto this when looking for the answer so I wanted to give the update to the answer for reference.
The methods save
and update
are deprecated.
save(to_save, manipulate=True, check_keys=True, **kwargs)¶ Save a document in this collection.
DEPRECATED - Use insert_one() or replace_one() instead.
Changed in version 3.0: Removed the safe parameter. Pass w=0 for unacknowledged write operations.
update(spec, document, upsert=False, manipulate=False, multi=False, check_keys=True, **kwargs) Update a document(s) in this collection.
DEPRECATED - Use replace_one(), update_one(), or update_many() instead.
Changed in version 3.0: Removed the safe parameter. Pass w=0 for unacknowledged write operations.
in the OPs particular case, it's better to use replace_one
.
The POSIX standard mandates that multiple /
are treated as a single /
in a file name. Thus
//dir///subdir////file
is the same as /dir/subdir/file
.
As such concatenating a two strings to build a complete path is a simple as:
full_path="$part1/$part2"
That may because you run APK file from external SD card storage. Just copy APK file into internal storagem problem will be solved
For example, to execute following with command prompt or BATCH file we can use this:
C:\Python27\python.exe "C:\Program files(x86)\dev_appserver.py" --host 0.0.0.0 --post 8080 "C:\blabla\"
Same thing to do with Python, we can do this:
subprocess.Popen(['C:/Python27/python.exe', 'C:\\Program files(x86)\\dev_appserver.py', '--host', '0.0.0.0', '--port', '8080', 'C:\\blabla'], shell=True)
or
subprocess.Popen(['C:/Python27/python.exe', 'C:/Program files(x86)/dev_appserver.py', '--host', '0.0.0.0', '--port', '8080', 'C:/blabla'], shell=True)
CTRL+R, CTRL+W : Toggle showing whitespace
or under the Edit Menu:
[BTW, it also appears you are using Tabs. It's common practice to have the IDE turn Tabs into spaces (often 4), via Options.]
I have recently used google mobile vision in both ios and android. I highly recommend to use Google Barcode Scan. It is pretty responsive with any orientation and processing time is pretty fast. It is called Google Mobile Vision.
The Barcode Scanner API detects barcodes in real time in any orientation. You can also detect and parse several barcodes in different formats at the same time.
https://developers.google.com/vision/
https://codelabs.developers.google.com/codelabs/bar-codes/#0
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
/* PUT THIS LINE IN YOUR CLASS PROGRAM MAIN() */
AppDomain.CurrentDomain.AssemblyResolve += (sender, arg) => { if (arg.Name.StartsWith("YOURDLL")) return Assembly.Load(Properties.Resources.YOURDLL); return null; };
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
First add the DLL´s to your project-Resources. Add a folder "Resources"
If you are using Any CPU
you may need to put it in single quotes.
Certainly when running in a Dockerfile, I had to use single quotes:
# Fails. Gives: MSBUILD : error MSB1008: Only one project can be specified.
RUN msbuild ConsoleAppFw451.sln /p:Configuration=Debug /p:Platform="Any CPU"
# Passes. Gives: Successfully built 40163c3e0121
RUN msbuild ConsoleAppFw451.sln /p:Configuration=Debug /p:Platform='Any CPU'
You get your browser's language for your button. There's no way to change it programmatically.
We found it practical and useful to put the version in the URL. It makes it easy to tell what you're using at a glance. We do alias /foo to /foo/(latest versions) for ease of use, shorter / cleaner URLs, etc, as the accepted answer suggests.
Keeping backwards compatibility forever is often cost-prohibitive and/or very difficult. We prefer to give advanced notice of deprecation, redirects like suggested here, docs, and other mechanisms.
No curly braces required you can directly write
@if($user->status =='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>
@else
<td>{{ $user->status }}</td>
@endif
From your description, it looks like that you want to "reserve" the allocated storage space of vector t_Names.
Take note that resize
initialize the newly allocated vector where reserve
just allocates but does not construct. Hence, 'reserve' is much faster than 'resize'
You can refer to the documentation regarding the difference of resize and reserve
I've been having this same problem for Solaris Express 11. It took me a while but I managed to find where the certificates needed to be placed. According to /etc/openssl/openssl.cnf, the path for certificates is /etc/openssl/certs. I placed the certificates generated using the above advice from Alexey.
You can verify that things are working using openssl on the commandline:
openssl s_client -connect github.com:443
You should use keyPressed
if you want an immediate effect, and keyReleased
if you want the effect after you release the key. You cannot use keyTyped
because F5 is not a character. keyTyped
is activated only when an character is pressed.
Command to get the database backup from linux machine terminal.
sqlcmd -S localhost -U SA -Q "BACKUP DATABASE [demodb] TO DISK = N'/var/opt/mssql/data/demodb.bak' WITH NOFORMAT, NOINIT, NAME = 'demodb-full', SKIP, NOREWIND, NOUNLOAD, STATS = 10"
Andrey's above post is still valid for the latest version of Intellij as of 3rd Quarter of 2017. So use it. 'Cause, build project, and external command line gradle build, does NOT add it to the external dependencies in Intellij...crazy as that sounds it is true. Only difference now is that the UI looks different to the above, but still the same icon for updating is used. I am only putting an answer here, cause I cannot paste a snapshot of the new UI...I dont want any up votes per se. Andrey still gave the correct answer above:
I tried for a long time to improve vokimon's drawn marker and make it more similar to Google Maps one (and pretty much succeeded). This is the code I got:
let circle=true;
path = 'M 0,0 C -0.7,-9 -3,-14 -5.5,-18.5 '+
'A 16,16 0 0,1 -11,-29 '+
'A 11,11 0 1,1 11,-29 '+
'A 16,16 0 0,1 5.5,-18.5 '+
'C 3,-14 0.7,-9 0,0 z '+
['', 'M -2,-28 '+
'a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0'][new Number(circle)];
I also scaled it by 0.8.
These snippets all perform exactly the same thing:
element.on('click', function () { ... });
element.bind('click', function () { ... });
element.click(function () { ... });
However, they are very different from these, which all perform the same thing:
element.on('click', 'selector', function () { ... });
element.delegate('click', 'selector', function () { ... });
$('selector').live('click', function () { ... });
The second set of event handlers use event delegation and will work for dynamically added elements. Event handlers that use delegation are also much more performant. The first set will not work for dynamically added elements, and are much worse for performance.
jQuery's on()
function does not introduce any new functionality that did not already exist, it is just an attempt to standardize event handling in jQuery (you no longer have to decide between live, bind, or delegate).
I have made this simple test with outerHTML being tokimon solution (without clone), and outerHTML2 being jessica solution (clone)
console.time("outerHTML");
for(i=0;i<1000;i++)
{
var html = $("<span style='padding:50px; margin:50px; display:block'><input type='text' title='test' /></span>").outerHTML();
}
console.timeEnd("outerHTML");
console.time("outerHTML2");
for(i=0;i<1000;i++)
{
var html = $("<span style='padding:50px; margin:50px; display:block'><input type='text' title='test' /></span>").outerHTML2();
}
console.timeEnd("outerHTML2");
and the result in my chromium (Version 20.0.1132.57 (0)) browser was
outerHTML: 81ms
outerHTML2: 439ms
but if we use tokimon solution without the native outerHTML function (which is now supported in probably almost every browser)
we get
outerHTML: 594ms
outerHTML2: 332ms
and there are gonna be more loops and elements in real world examples, so the perfect combination would be
$.fn.outerHTML = function()
{
$t = $(this);
if( "outerHTML" in $t[0] ) return $t[0].outerHTML;
else return $t.clone().wrap('<p>').parent().html();
}
so clone method is actually faster than wrap/unwrap method
(jquery 1.7.2)
there are some syntax errors to your program heres a working code;
#include<stdio.h>
int main()
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0){
printf("this is multiple number");
}
else if (b%a==0){
printf("this is multiple number");
}
else{
printf("this is not multiple number");
return 0;
}
}
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.
For CSS Only solution 1. Either height of wrapper should be fixed or 2. height of second div should be fixed
There could be a global variable, likely set with argparse
from sys.argv
, that stands for whether the program should be verbose or not.
Then a decorator could be written such that if verbosity was on, then the standard input would be diverted into the null device as long as the function were to run:
import os
from contextlib import redirect_stdout
verbose = False
def louder(f):
def loud_f(*args, **kwargs):
if not verbose:
with open(os.devnull, 'w') as void:
with redirect_stdout(void):
return f(*args, **kwargs)
return f(*args, **kwargs)
return loud_f
@louder
def foo(s):
print(s*3)
foo("bar")
This answer is inspired by this code; actually, I was going to just use it as a module in my program, but I got errors I couldn't understand, so I adapted a portion of it.
The downside of this solution is that verbosity is binary, unlike with logging
, which allows for finer-tuning of how verbose the program can be.
Also, all print
calls are diverted, which might be unwanted for.
I see you are using jQuery for the form initialization.
When I try @KyungHun Jeon's answer, it doesn't work for me that use jQuery too.
So, I tried appending the form to the body by using the jQuery way:
$(document.body).append(form);
And it worked!
To get all the values from a map:
for (Tab tab : hash.values()) {
// do something with tab
}
To get all the entries from a map:
for ( Map.Entry<String, Tab> entry : hash.entrySet()) {
String key = entry.getKey();
Tab tab = entry.getValue();
// do something with key and/or tab
}
To process all values:
hash.values().forEach(tab -> /* do something with tab */);
To process all entries:
hash.forEach((key, tab) -> /* do something with key and tab */);
I got it
Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"
Basically, I need to set the cell format, instead of setting the date.
as far as we want to send all the form input fields which have name attribute, you can do this for all forms, regardless of the field names:
First Solution
function submitForm(form){
var url = form.attr("action");
var formData = {};
$(form).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$.post(url, formData).done(function (data) {
alert(data);
});
}
Second Solution: in this solution you can create an array of input values:
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
You should be using the unwind library.
unw_cursor_t cursor; unw_context_t uc;
unw_word_t ip, sp;
unw_getcontext(&uc);
unw_init_local(&cursor, &uc);
unsigned long a[100];
int ctr = 0;
while (unw_step(&cursor) > 0) {
unw_get_reg(&cursor, UNW_REG_IP, &ip);
unw_get_reg(&cursor, UNW_REG_SP, &sp);
if (ctr >= 10) break;
a[ctr++] = ip;
}
Your approach also would work fine unless you make a call from a shared library.
You can use the addr2line
command on Linux to get the source function / line number of the corresponding PC.
This error is very non-descriptive but the key here is that 'ID' is in uppercase. This indicates that the route has not been correctly set up. To let the application handle URLs with an id, you need to make sure that there's at least one route configured for it. You do this in the RouteConfig.cs located in the App_Start folder. The most common is to add the id as an optional parameter to the default route.
public static void RegisterRoutes(RouteCollection routes)
{
//adding the {id} and setting is as optional so that you do not need to use it for every action
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Now you should be able to redirect to your controller the way you have set it up.
[HttpPost]
public ActionResult RedirectToImages(int id)
{
return RedirectToAction("Index","ProductImageManager", new { id });
//if the action is in the same controller, you can omit the controller:
//RedirectToAction("Index", new { id });
}
In one or two occassions way back I ran into some issues by normal redirect and had to resort to doing it by passing a RouteValueDictionary. More information on RedirectToAction with parameter
return RedirectToAction("Index", new RouteValueDictionary(
new { controller = "ProductImageManager", action = "Index", id = id } )
);
If you get a very similar error but in lowercase 'id', this is usually because the route expects an id parameter that has not been provided (calling a route without the id /ProductImageManager/Index
). See this so question for more information.
I think what you want is this:
last_list=[]
if p.last_name != None and p.last_name != "":
last_list.append(p.last_name)
print last_list
Your current if statement:
if p.last_name == None or p.last_name == "":
pass
Effectively never does anything. If p.last_name is none or the empty string, it does nothing inside the loop. If p.last_name is something else, the body of the if statement is skipped.
Also, it looks like your statement pan_list.append(p.last)
is a typo, because I see neither pan_list nor p.last getting used anywhere else in the code you have posted.
Why not just return the worksheet name with address = cell.Worksheet.Name then you can concatenate the address back on like this address = cell.Worksheet.Name & "!" & cell.Address
Julien Danjou wrote a good article explaining why you should never deal with timezones. An excerpt:
Indeed, Python datetime API always returns unaware datetime objects, which is very unfortunate. Indeed, as soon as you get one of this object, there is no way to know what the timezone is, therefore these objects are pretty "useless" on their own.
Alas, even though you may use utcnow()
, you still won't see the timezone info, as you discovered.
Recommendations:
Always use aware
datetime
objects, i.e. with timezone information. That makes sure you can compare them directly (aware and unawaredatetime
objects are not comparable) and will return them correctly to users. Leverage pytz to have timezone objects.Use ISO 8601 as the input and output string format. Use
datetime.datetime.isoformat()
to return timestamps as string formatted using that format, which includes the timezone information.If you need to parse strings containing ISO 8601 formatted timestamps, you can rely on
iso8601
, which returns timestamps with correct timezone information. This makes timestamps directly comparable.
A little bit of validation with:
/<(?=.*? .*?\/ ?>|br|hr|input|!--|wbr)[a-z]+.*?>|<([a-z]+).*?<\/\1>/i.test(htmlStringHere)
This searches for empty tags (some predefined) and /
terminated XHTML empty tags and validates as HTML because of the empty tag OR will capture the tag name and attempt to find it's closing tag somewhere in the string to validate as HTML.
Explained demo: http://regex101.com/r/cX0eP2
Update:
Complete validation with:
/<(br|basefont|hr|input|source|frame|param|area|meta|!--|col|link|option|base|img|wbr|!DOCTYPE).*?>|<(a|abbr|acronym|address|applet|article|aside|audio|b|bdi|bdo|big|blockquote|body|button|canvas|caption|center|cite|code|colgroup|command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frameset|head|header|hgroup|h1|h2|h3|h4|h5|h6|html|i|iframe|ins|kbd|keygen|label|legend|li|map|mark|menu|meter|nav|noframes|noscript|object|ol|optgroup|output|p|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video).*?<\/\2>/i.test(htmlStringHere)
This does proper validation as it contains ALL HTML tags, empty ones first followed by the rest which need a closing tag.
Explained demo here: http://regex101.com/r/pE1mT5
You could try exe4j. This is effectively what we use through its cousin install4j.
This is what I normally use, albeit a bit manual:
/* Add a 'temporary' UDDT with the new definition */
exec sp_addtype t_myudt_tmp, 'numeric(18,5)', NULL
/* Build a command to alter all the existing columns - cut and
** paste the output, then run it */
select 'alter table dbo.' + TABLE_NAME +
' alter column ' + COLUMN_NAME + ' t_myudt_tmp'
from INFORMATION_SCHEMA.COLUMNS
where DOMAIN_NAME = 't_myudt'
/* Remove the old UDDT */
exec sp_droptype t_mydut
/* Rename the 'temporary' UDDT to the correct name */
exec sp_rename 't_myudt_tmp', 't_myudt', 'USERDATATYPE'
If you want to rotate a vector you should construct what is known as a rotation matrix.
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
I fix it by brew install libpng
Sure you can:
SELECT * FROM table
WHERE DateStamp > DATE_ADD(NOW(), INTERVAL -1 DAY)
stdout is the standard output file stream. Obviously, it's first and default pointer to output is the screen, however you can point it to a file as desired!
Please read:
http://www.cplusplus.com/reference/cstdio/stdout/
C++ is very similar to C however, object oriented.
Here is the good function for pre PHP 5: I added GMT difference at the end, it's not hardcoded.
function iso8601($time=false) {
if ($time === false) $time = time();
$date = date('Y-m-d\TH:i:sO', $time);
return (substr($date, 0, strlen($date)-2).':'.substr($date, -2));
}
That data looks like it is in JSON format.
You can use this JSON implementation for Ruby to extract it.
This is how I come up with the IP
func ReadUserIP(r *http.Request) string {
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
return IPAddress
}
X-Real-Ip - fetches first true IP (if the requests sits behind multiple NAT sources/load balancer)
X-Forwarded-For - if for some reason X-Real-Ip is blank and does not return response, get from X-Forwarded-For
data = [150,300]; // data from ajax or any other way
chart.series[0].setData(data, true);
The setData
will call redraw method.
Reference: http://api.highcharts.com/highcharts/Series.setData
ECMAScript 6 introduced the let
statement. You can use it in a for
statement.
var ids:string = [];
for(let result of this.results){
ids.push(result.Id);
}
File -> Export -> Web -> WAR file
OR in Kepler follow as shown below :
The reason you separate the login and non-login shell is because the .bashrc
file is reloaded every time you start a new copy of Bash. The .profile
file is loaded only when you either log in or use the appropriate flag to tell Bash to act as a login shell.
Personally,
PATH
setup into a .profile
file (because I sometimes use other shells);.bashrc
file;I put this
#!/bin/bash
#
# CRM .bash_profile Time-stamp: "2008-12-07 19:42"
#
# echo "Loading ${HOME}/.bash_profile"
source ~/.profile # get my PATH setup
source ~/.bashrc # get my Bash aliases
in my .bash_profile
file.
Oh, and the reason you need to type bash
again to get the new alias is that Bash loads your .bashrc
file when it starts but it doesn't reload it unless you tell it to. You can reload the .bashrc
file (and not need a second shell) by typing
source ~/.bashrc
which loads the .bashrc
file as if you had typed the commands directly to Bash.
From android 6.0 you need to check for user permission, if you want to use GoogleMap.setMyLocationEnabled(true)
you will get Call requires permission which may be rejected by user
error
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}
if you want to read more, check google map docs
I thought this would be for "onunload", not page load, since aren't we talking about firing an event when hitting "Back"? $document.ready() is for events desired on page load, no matter how you get to that page (i.e. redirect, opening the browser to the URL directly, etc.), not when clicking "Back", unless you're talking about what to fire on the previous page when it loads again. And I'm not sure the page isn't getting cached as I've found that Javascripts still are, even when $document.ready() is included in them. We've had to hit Ctrl+F5 when editing our scripts that have this event whenever we revise them and we want test the results in our pages.
$(window).unload(function(){ alert('do unload stuff here'); });
is what you'd want for an onunload event when hitting "Back" and unloading the current page, and would also fire when a user closes the browser window. This sounded more like what was desired, even if I'm outnumbered with the $document.ready() responses. Basically the difference is between an event firing on the current page while it's closing or on the one that loads when clicking "Back" as it's loading. Tested in IE 7 fine, can't speak for the other browsers as they aren't allowed where we are. But this might be another option.
Additional information for modern (systemd) linux systems.
There are many resources about this of values that may need tweaking (such as How to increase maximum number of JVM threads (Linux 64bit)); however a new limit is imposed by way of the systemd "TasksMax" limit which sets pids.max on the cgroup.
For login sessions the UserTasksMax default is 33% of the kernel limit pids_max (usually 12,288) and can be override in /etc/systemd/logind.conf.
For services the DefaultTasksMax default is 15% of the kernel limit pids_max (usually 4,915). You can override it for the service by setting TasksMax in "systemctl edit" or update DefaultTasksMax in /etc/systemd/system.conf
$.getJSON('//freegeoip.net/json/?callback=?', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Just want to add another way of doing this. I've seen multiple people on various related threads ask if you can use VerifyRenderingInServerForm without adding it to the parent page.
You actually can do this but it's a bit of a bodge.
First off create a new Page class which looks something like the following:
public partial class NoRenderPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
public override void VerifyRenderingInServerForm(Control control)
{
//Allows for printing
}
public override bool EnableEventValidation
{
get { return false; }
set { /*Do nothing*/ }
}
}
Does not need to have an .ASPX associated with it.
Then in the control you wish to render you can do something like the following.
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
var page = new NoRenderPage();
page.DesignerInitialize();
var form = new HtmlForm();
page.Controls.Add(form);
form.Controls.Add(pnl);
controlToRender.RenderControl(hw);
Now you've got your original control rendered as HTML. If you need to, add the control back into it's original position. You now have the HTML rendered, the page as normal and no changes to the page itself.
I would avoid using component state since this could be difficult to manage and prone to issues that can be difficult to troubleshoot.
You should use either cookies
or localStorage
for persisting a user's session data. You can also use a closure as a wrapper around your cookie
or localStorage
data.
Here is a simple example of a UserProfile
closure that will hold the user's name.
var UserProfile = (function() {
var full_name = "";
var getName = function() {
return full_name; // Or pull this from cookie/localStorage
};
var setName = function(name) {
full_name = name;
// Also set this in cookie/localStorage
};
return {
getName: getName,
setName: setName
}
})();
export default UserProfile;
When a user logs in, you can populate this object with user name, email address etc.
import UserProfile from './UserProfile';
UserProfile.setName("Some Guy");
Then you can get this data from any component in your app when needed.
import UserProfile from './UserProfile';
UserProfile.getName();
Using a closure will keep data outside of the global namespace, and make it is easily accessible from anywhere in your app.
FWIW,
Poor mans security folder (to protect a public shared folder from little prying eyes ;) )
mkdir -p {0..9}/{0..9}/{0..9}/{0..9}
Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.
// Define appendVal by extending JQuery_x000D_
$.fn.appendVal = function( TextToAppend ) {_x000D_
return $(this).val(_x000D_
$(this).val() + TextToAppend_x000D_
);_x000D_
};_x000D_
//______________________________________________x000D_
_x000D_
// And that's how to use it:_x000D_
$('#SomeID')_x000D_
.appendVal( 'This text was just added' )
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
<textarea _x000D_
id = "SomeID"_x000D_
value = "ValueText"_x000D_
type = "text"_x000D_
>Current NodeText_x000D_
</textarea>_x000D_
</form>
_x000D_
Well when creating this example I somehow got a little confused. "ValueText" vs >Current NodeText< Isn't .val()
supposed to run on the data of the value attribute? Anyway I and you me may clear up this sooner or later.
However the point for now is:
When working with form data use .val().
When dealing with the mostly read only data in between the tag use .text() or .append() to append text.
First: back up your entire directory, including the .git directory.
Second: You can use git fsck --lost-found
to obtain the ID of the lost commits.
Third: rebase or merge onto the lost commit.
Fourth: Always think twice before using -D or --force with git :)
You could also read this good discussion of how to recover from this kind of error.
EDIT: By the way, don't run git gc
(or allow it to run by itself - i.e. don't run git fetch
or anything similar) or you may lose your commits for ever.
You can use unix timestamp to direct:
SELECT UNIX_TIMESTAMP(date) AS epoch_time FROM table;
Then get the epoch_time into JavaScript, and it's a simple matter of:
var myDate = new Date(epoch_time * 1000);
The multiplying by 1000 is because JavaScript takes milliseconds, and UNIX_TIMESTAMP gives seconds.
Best thing is to try it for yourself.
mkdir test
cd test
git init
touch aaa.txt
git add .
git commit -a -m "New file"
mv aaa.txt bbb.txt
git add .
git status
git commit --dry-run -a
Now git status and git commit --dry-run -a shows two different results where git status shows bbb.txt as a new file/ aaa.txt is deleted, and the --dry-run commands shows the actual rename.
~/test$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# new file: bbb.txt
#
# Changes not staged for commit:
# (use "git add/rm <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# deleted: aaa.txt
#
/test$ git commit --dry-run -a
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# renamed: aaa.txt -> bbb.txt
#
Now go ahead and do the check-in.
git commit -a -m "Rename"
Now you can see that the file is in fact renamed, and what's shown in git status is wrong.
Moral of the story: If you're not sure whether your file got renamed, issue a "git commit --dry-run -a". If its showing that the file is renamed, you're good to go.
Instead of:
var host = req.get('host');
var origin = req.get('origin');
you can also use:
var host = req.headers.host;
var origin = req.headers.origin;
If you want to append to the file, open it with 'a'
. If you want to seek through the file to find the place where you should insert the line, use 'r+'
. (docs)
Like @takeshin said .d stands for declaration file for typescript (.ts).
Few points to be clarified before proceeding to answer this post -
If you are thinking if typescript is just syntactic superset, what benefits does it offer - https://basarat.gitbooks.io/typescript/docs/why-typescript.html#the-typescript-type-system
To Answer this post -
As we discussed, typescript is superset of javascript and needs to be transpiled into javascript. So if a library or third party code is written in typescript, it eventually gets converted to javascript which can be used by javascript project but vice versa does not hold true.
For ex -
If you install javascript library -
npm install --save mylib
and try importing it in typescript code -
import * from "mylib";
you will get error.
"Cannot find module 'mylib'."
As mentioned by @Chris, many libraries like underscore, Jquery are already written in javascript. Rather than re-writing those libraries for typescript projects, an alternate solution was needed.
In order to do this, you can provide type declaration file in javascript library named as *.d.ts, like in above case mylib.d.ts. Declaration file only provides type declarations of functions and variables defined in respective javascript file.
Now when you try -
import * from "mylib";
mylib.d.ts gets imported which acts as an interface between javascript library code and typescript project.
This is the problem:
while(str.charAt(i)==ch)
That will keep going until it falls off the end... when i
is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:
while (i < str.length() && str.charAt(i) == ch)
You also need to set count
to 0 at the start of each iteration of the bigger loop - the count resets, after all - and change
count = count + i;
to either:
count++;
... or get rid of count
or i
. They're always going to have the same value, after all. Personally I'd just use one variable, declared and initialized inside the loop. That's a general style point, in fact - it's cleaner to declare local variables when they're needed, rather than declaring them all at the top of the method.
However, then your program will loop forever, as this doesn't do anything useful:
str.substring(count);
Strings are immutable in Java - substring
returns a new string. I think you want:
str = str.substring(count);
Note that this will still output "a2b2a2" for "aabbaa". Is that okay?
The pretty way is printf '\33c\e[3J'
If your solution requires returning 0 instead of true/false, I've found this to be useful:
PS C:\> [array]$foo = $null
PS C:\> ($foo | Measure-Object).Count
0
This operation is different from the count property of the array, because Measure-Object
is counting objects. Since there are none, it will return 0.
ping waits for about 5 seconds before timing out, not 1 second as was stated above. That is, unless you tell it to only wait for 1 second before timing out.
ping 1.0.0.1 -n 1 -w 1000
will ping once, wait only 1 second (1000 ms) for a response, then time out.
So an approximately 20-second delay would be:
ping 1.0.0.1 -n 20 -w 1000
If you can use Guava library, since version 21, you can use
Streams.stream(iterable)
I am able to send the live camera video from mobile to my server.using this link see the link
Refer the above link.there is a sample application in that link. Just you need to set your service url in RecordActivity.class.
Example as: ffmpeg_link="rtmp://yourserveripaddress:1935/live/venkat";
we can able to send H263 and H264 type videos using that link.
This command will help to pull from the repository as the different user:
git pull https://[email protected]/projectfolder/projectname.git master
It is a workaround, when you are using same machine that someone else used before you, and had saved credentials
final
means that the value cannot be changed after initialization, that's what makes it a constant. static
means that instead of having space allocated for the field in each object, only one instance is created for the class.
So, static final
means only one instance of the variable no matter how many objects are created and the value of that variable can never change.
I think your co-worker is right as long as he does not enter in the process to write executable code in the header. The right balance, I think, is to follow the path indicated by GNAT Ada where the .ads file gives a perfectly adequate interface definition of the package for its users and for its childs.
By the way Ted, have you had a look on this forum to the recent question on the Ada binding to the CLIPS library you wrote several years ago and which is no more available (relevant Web pages are now closed). Even if made to an old Clips version, this binding could be a good start example for somebody willing to use the CLIPS inference engine within an Ada 2012 program.
Use the FormBorderStyle
property. Make it FixedSingle
:
this.FormBorderStyle = FormBorderStyle.FixedSingle;
Why not
DELETE FROM table ORDER BY id DESC LIMIT 1, 123456789
Just delete all but the first row (order is DESC!), using a very very large nummber as second LIMIT-argument. See here
I found this can also occur if the most of the data plotted is outside of the axis limits. In that case, adjust the axis scales accordingly.
Including the implementation file (test.c
) causes it to be prepended to your main.c and complied there and then again separately. So, the function test
has two definitions -- one in the object code of main.c
and once in that of test.c
, which gives you a ODR violation. You need to create a header file containing the declaration of test
and include it in main.c
:
/* test.h */
#ifndef TEST_H
#define TEST_H
void test(); /* declaration */
#endif /* TEST_H */
With EF or LINQ to SQL:
var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();
With LINQ to Objects I suggest to use morelinq extension MaxBy
(get morelinq from nuget):
var item = items.MaxBy(i => i.Value);
I used a JS solution. It works in Firefox and Chrome. Any problems, let me know.
html
<body>
<header id="header">
<h1>Extra-Long Page Heading That Wraps</h1>
<nav id="nav">
<ul>
<li><a href="" title="">Home</a></li>
<li><a href="" title="">Page 2</a></li>
<li><a href="" title="">Page 3</a></li>
</ul>
</nav>
</header>
<main>
<p><!-- ridiculously long content --></p>
</main>
<footer>
<p>FOOTER CONTENT</p>
</footer>
<script src="navbar.js" type="text/javascript"></script>
</body>
css
nav a {
background: #aaa;
font-size: 1.2rem;
text-decoration: none;
padding: 10px;
}
nav a:hover {
background: #bbb;
}
nav li {
background: #aaa;
padding: 10px 0;
}
nav ul {
background: #aaa;
list-style-type: none;
margin: 0;
padding: 0;
}
@media (min-width: 768px) {
nav ul {
display: flex;
}
}
js
function applyNavbarSticky() {
let header = document.querySelector('body > header:first-child')
let navbar = document.querySelector('nav')
header.style.position = 'sticky'
function setTop() {
let headerHeight = header.clientHeight
let navbarHeight = navbar.clientHeight
let styleTop = navbarHeight - headerHeight
header.style.top = `${styleTop}px`
}
setTop()
window.onresize = function () {
setTop()
}
}
In case someone also want to dump response like me. i avoided to dump response body. following code just dump the StatusCode and Headers.
static private String dumpResponse(HttpServletResponse resp){
StringBuilder sb = new StringBuilder();
sb.append("Response Status = [" + resp.getStatus() + "], ");
String headers = resp.getHeaderNames().stream()
.map(headerName -> headerName + " : " + resp.getHeaders(headerName) )
.collect(Collectors.joining(", "));
if (headers.isEmpty()) {
sb.append("Response headers: NONE,");
} else {
sb.append("Response headers: "+headers+",");
}
return sb.toString();
}
With Springboot 2 you can set the root logging Level with an Environment Variable like this:
logging.level.root=DEBUG
Or you can set specific logging for packages like this:
logging.level.my.package.name=TRACE
I know it's quite late, but removing the Unique Key
Constraint solved the problem. I didn't use the TEXT
or LONGTEXT
column as PK , but I was trying to make it unique. I got the 1170 error
, but when I removed UK
, the error was removed too.
I don't fully understand why.
Try to use the method isChecked();
Like,
selectedRadioButton.isChecked() -> returns boolean.
Refere here for more details on Radio Button
For the replacement portion, Python uses \1
the way sed and vi do, not $1
the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1
interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.
Python 3.2 (r32:88445, Jul 27 2011, 13:41:33)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>>
The top answers by Paul H and J. Li do not work for all types of seaborn figures. For the FacetGrid
type (for instance sns.lmplot()
), use the size
and aspect
parameter.
Size
changes both the height and width, maintaining the aspect ratio.
Aspect
only changes the width, keeping the height constant.
You can always get your desired size by playing with these two parameters.
Note: I had problem on Windows 7 but it might help you as well..
I had problem with android studio detecting my phone(Acer Liquid Zest 4G), tried restarting android studio, switching back and forth between PTP and MTP, OS was able to detect device normally.
So what I did was, in Developer Options i enabled USB debugging, USB connection is in PTP mode, then from phone manufacturer's site (you can find site for your phone here: https://developer.android.com/studio/run/oem-usb.html), I downloaded USB driver for my phone model, installed driver and android studio was able to detect my phone(there was no need for restart).
I will repeat again, you must have USB Debugging enabled in Developer Options, otherwise it won't work. Hope it helps.
Just in case, someone out there having same issue but changing file permission doesn't solve the issue, add this line to your config.inc.php
file
<?php
// other config goes here . . .
$cfg['CheckConfigurationPermissions'] = false;
And you're good to go.
In my case, I'm using windows 10 WSL with phpmyadmin installed on D:
drive. There's no way to (for now) change file permission on local disk through WSL unless your installation directory is inside WSL filesystem it-self. There's updates according to this issue, but still on insider build.
Cheers.
You could use...
Math.trunc()
(truncate fractional part, also see below)Math.floor()
(round down)Math.ceil()
(round up) Math.round()
(round to nearest integer)...dependent on how you wanted to remove the decimal.
Math.trunc()
isn't supported on all platforms yet (namely IE), but you could easily use a polyfill in the meantime.
Another method of truncating the fractional portion with excellent platform support is by using a bitwise operator (.e.g |0
). The side-effect of using a bitwise operator on a number is it will treat its operand as a signed 32bit integer, therefore removing the fractional component. Keep in mind this will also mangle numbers larger than 32 bits.
You may also be talking about the inaccuracy of decimal rounding with floating point arithmetic.
Required Reading - What Every Computer Scientist Should Know About Floating-Point Arithmetic.
you can use UPDATE command.
UPDATE table_name SET name=@name, email=@email, phone=@phone WHERE client_id=@client_id
Like others have said, it should most likely go in an external file. I prefer to include such files at the end of the <head />. This method is more human friendly than machine friendly, but that way I always know where the JS is. It is just not as readable to include script files anywhere else (imho).
I you really need to squeeze out every last ms then you probably should do what Yahoo says.
You need to link the with the -lm
linker option
You need to compile as
gcc test.c -o test -lm
gcc (Not g++) historically would not by default include the mathematical functions while linking. It has also been separated from libc onto a separate library libm. To link with these functions you have to advise the linker to include the library -l
linker option followed by the library name m
thus -lm
.
Try this
Scanner scanner = new Scanner(System.in);
int amountOfPlayers;
do {
System.out.print("Select the amount of players (1/2): ");
while (!scanner.hasNextInt()) {
System.out.println("That's not a number!");
scanner.next(); // this is important!
}
amountOfPlayers = scanner.nextInt();
} while ((amountOfPlayers <= 0) || (amountOfPlayers > 2));
if(scanner != null) {
scanner.close();
}
System.out.println("You've selected " + amountOfPlayers+" player(s).");
To set the build configuration to Debug or Release, choose 'Edit Scheme' from the 'Product' menu.
Then you see a clear choice.
The Apple Transition Guide mentions a button at the top left of the Xcode screen, but I cannot see it in Xcode 4.3.
Here is the raw way to do it
$startTimeStamp = strtotime("2011/07/01");
$endTimeStamp = strtotime("2011/07/17");
$timeDiff = abs($endTimeStamp - $startTimeStamp);
$numberDays = $timeDiff/86400; // 86400 seconds in one day
// and you might want to convert to integer
$numberDays = intval($numberDays);
use default convertation class: Convert.ToDecimal(Double)
the window
contains everything, so you can call window.screen
and window.document
to get those elements. Check out this fiddle, pretty-printing the contents of each object: http://jsfiddle.net/JKirchartz/82rZu/
You can also see the contents of the object in firebug/dev tools like this:
console.dir(window);
console.dir(document);
console.dir(screen);
window
is the root of everything, screen
just has screen dimensions, and document
is top DOM object. so you can think of it as window
being like a super-document
...
sudo dscl . -append /Groups/wheel wheel $(whoami)
chmod -R 775 ${this_is_your_python_package_path}
pip3 install requests
and got:File "/usr/local/python3/lib/python3.6/os.py", line 220, in makedirs
mkdir(name, mode)
PermissionError: [Errno 13] Permission denied:
'/usr/local/python3/lib/python3.6/site-packages/requests'
cd /usr/local/python3/lib/python3.6/site-packages
,
then ls -al
and got:drwxr-xr-x 6 root wheel 192B 2 27 18:06 requests/
when i saw this, i understood, makedirs is an action of write,
but the requests mode drwxrwxr-x
displaied only user root
can write the requests file.
If add yutou(whoami
) to the group wheel, and modify the package
to the group wheel can write, then i can write, and the problem solved.
How to add yutou to group wheel?
+ detect group wheel, sudo dscl . -list /groups GroupMembership
, you will find:
wheel root
the group wheel only one member root.
+ add yutou to group wheel, sudo dscl . -append /Groups/wheel wheel yutou
.
+ check, sudo dscl . -list /groups GroupMembership
:
wheel root yutou
modify the python package mode
chmod -R 775 /usr/local/python3/lib/python3.6
Actually, the internal behavior is translating the anonymous object to a dictionary. So what I do in these scenarios is go for a dictionary:
@{
var htmlAttributes = new Dictionary<string, object>
{
{ "class" , "form-control"},
{ "placeholder", "Why?" }
};
if (Model.IsDisabled)
{
htmlAttributes.Add("disabled", "disabled");
}
}
@Html.EditorFor(m => m.Description, new { htmlAttributes = htmlAttributes })
Or, as Stephen commented here:
@Html.EditorFor(m => m.Description,
Model.IsDisabled ? (object)new { disabled = "disabled" } : (object)new { })
There's a rather crude way of doing this, but be careful because first, this relies on python interpreter process identifying themselves as python, and second, it has the concomitant effect of also killing any other processes identified by that name.
In short, you can kill all python interpreters by typing this into your shell (make sure you read the caveats above!):
ps aux | grep python | grep -v "grep python" | awk '{print $2}' | xargs kill -9
To break this down, this is how it works. The first bit, ps aux | grep python | grep -v "grep python"
, gets the list of all processes calling themselves python, with the grep -v making sure that the grep command you just ran isn't also included in the output. Next, we use awk to get the second column of the output, which has the process ID's. Finally, these processes are all (rather unceremoniously) killed by supplying each of them with kill -9
.
I hope this complete example will help you.
This is the TaxiInfo class which holds information about a taxi ride:
namespace Taxi.Models
{
public class TaxiInfo
{
public String Driver { get; set; }
public Double Fare { get; set; }
public Double Distance { get; set; }
public String StartLocation { get; set; }
public String EndLocation { get; set; }
}
}
We also have a convenience model which holds a List of TaxiInfo(s):
namespace Taxi.Models
{
public class TaxiInfoSet
{
public List<TaxiInfo> TaxiInfoList { get; set; }
public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
{
TaxiInfoList = new List<TaxiInfo>();
foreach(var TaxiInfo in TaxiInfos)
{
TaxiInfoList.Add(TaxiInfo);
}
}
}
}
Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:
public ActionResult Index()
{
var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };
return View(new TaxiInfoSet(taxi1,taxi2));
}
The code for the view is as follows:
@model Taxi.Models.TaxiInfoSet
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach(var TaxiInfo in Model.TaxiInfoList){
<form>
<h1>Cost: [email protected]</h1>
<h2>Distance: @(TaxiInfo.Distance) km</h2>
<p>
Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
</p>
@Html.ActionLink("Home","Booking",TaxiInfo)
</form>
}
The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:
public ActionResult Booking(TaxiInfo Taxi)
{
return View(Taxi);
}
This returns a the following view:
@model Taxi.Models.TaxiInfo
@{
ViewBag.Title = "Booking";
}
<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>
A visual tour:
In general, to set a video's FPS to 24, almost always you can do:
With Audio and without re-encoding:
# Extract video stream
ffmpeg -y -i input_video.mp4 -c copy -f h264 output_raw_bitstream.h264
# Extract audio stream
ffmpeg -y -i input_video.mp4 -vn -acodec copy output_audio.aac
# Remux with new FPS
ffmpeg -y -r 24 -i output_raw_bitstream.h264 -i output-audio.aac -c copy output.mp4
If you want to find the video format (H264 in this case), you can use FFprobe, like this
ffprobe -loglevel error -select_streams v -show_entries stream=codec_name -of default=nw=1:nk=1 input_video.mp4
which will output:
h264
Read more in How can I analyze file and detect if the file is in H.264 video format?
With re-encoding:
ffmpeg -y -i input_video.mp4 -vf -r 24 output.mp4
The main difference from other solutions here is that this one reuses logic in RequiredAttribute
on the server side, and uses required
's validation method depends
property on the client side:
public class RequiredIf : RequiredAttribute, IClientValidatable
{
public string OtherProperty { get; private set; }
public object OtherPropertyValue { get; private set; }
public RequiredIf(string otherProperty, object otherPropertyValue)
{
OtherProperty = otherProperty;
OtherPropertyValue = otherPropertyValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);
if (otherPropertyInfo == null)
{
return new ValidationResult($"Unknown property {OtherProperty}");
}
object otherValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (Equals(OtherPropertyValue, otherValue)) // if other property has the configured value
return base.IsValid(value, validationContext);
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "requiredif"; // data-val-requiredif
rule.ValidationParameters.Add("other", OtherProperty); // data-val-requiredif-other
rule.ValidationParameters.Add("otherval", OtherPropertyValue); // data-val-requiredif-otherval
yield return rule;
}
}
$.validator.unobtrusive.adapters.add("requiredif", ["other", "otherval"], function (options) {
var value = {
depends: function () {
var element = $(options.form).find(":input[name='" + options.params.other + "']")[0];
return element && $(element).val() == options.params.otherval;
}
}
options.rules["required"] = value;
options.messages["required"] = options.message;
});
Use the CellMouseDown
event on the DataGridView
. From the event handler arguments you can determine which cell was clicked. Using the PointToClient()
method on the DataGridView you can determine the relative position of the pointer to the DataGridView, so you can pop up the menu in the correct location.
(The DataGridViewCellMouseEvent
parameter just gives you the X
and Y
relative to the cell you clicked, which isn't as easy to use to pop up the context menu.)
This is the code I used to get the mouse position, then adjust for the position of the DataGridView:
var relativeMousePosition = DataGridView1.PointToClient(Cursor.Position);
this.ContextMenuStrip1.Show(DataGridView1, relativeMousePosition);
The entire event handler looks like this:
private void DataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
// Ignore if a column or row header is clicked
if (e.RowIndex != -1 && e.ColumnIndex != -1)
{
if (e.Button == MouseButtons.Right)
{
DataGridViewCell clickedCell = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];
// Here you can do whatever you want with the cell
this.DataGridView1.CurrentCell = clickedCell; // Select the clicked cell, for instance
// Get mouse position relative to the vehicles grid
var relativeMousePosition = DataGridView1.PointToClient(Cursor.Position);
// Show the context menu
this.ContextMenuStrip1.Show(DataGridView1, relativeMousePosition);
}
}
}
Building on dnolans example, this is the version I could actually get to work (there were some errors with the boundary, encoding wasn't set) :-)
To send the data:
HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create("http://you.url.here");
oRequest.ContentType = "multipart/form-data; boundary=" + PostData.boundary;
oRequest.Method = "POST";
PostData pData = new PostData();
Encoding encoding = Encoding.UTF8;
Stream oStream = null;
/* ... set the parameters, read files, etc. IE:
pData.Params.Add(new PostDataParam("email", "[email protected]", PostDataParamType.Field));
pData.Params.Add(new PostDataParam("fileupload", "filename.txt", "filecontents" PostDataParamType.File));
*/
byte[] buffer = encoding.GetBytes(pData.GetPostData());
oRequest.ContentLength = buffer.Length;
oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);
oStream.Close();
HttpWebResponse oResponse = (HttpWebResponse)oRequest.GetResponse();
The PostData class should look like:
public class PostData
{
// Change this if you need to, not necessary
public static string boundary = "AaB03x";
private List<PostDataParam> m_Params;
public List<PostDataParam> Params
{
get { return m_Params; }
set { m_Params = value; }
}
public PostData()
{
m_Params = new List<PostDataParam>();
}
/// <summary>
/// Returns the parameters array formatted for multi-part/form data
/// </summary>
/// <returns></returns>
public string GetPostData()
{
StringBuilder sb = new StringBuilder();
foreach (PostDataParam p in m_Params)
{
sb.AppendLine("--" + boundary);
if (p.Type == PostDataParamType.File)
{
sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
sb.AppendLine("Content-Type: application/octet-stream");
sb.AppendLine();
sb.AppendLine(p.Value);
}
else
{
sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
sb.AppendLine();
sb.AppendLine(p.Value);
}
}
sb.AppendLine("--" + boundary + "--");
return sb.ToString();
}
}
public enum PostDataParamType
{
Field,
File
}
public class PostDataParam
{
public PostDataParam(string name, string value, PostDataParamType type)
{
Name = name;
Value = value;
Type = type;
}
public PostDataParam(string name, string filename, string value, PostDataParamType type)
{
Name = name;
Value = value;
FileName = filename;
Type = type;
}
public string Name;
public string FileName;
public string Value;
public PostDataParamType Type;
}
This code works for me:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
namespace Json
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(DeserializeNames());
Console.ReadLine();
}
public static string DeserializeNames()
{
var jsonData = "{\"name\":[{\"last\":\"Smith\"},{\"last\":\"Doe\"}]}";
JavaScriptSerializer ser = new JavaScriptSerializer();
nameList myNames = ser.Deserialize<nameList>(jsonData);
return ser.Serialize(myNames);
}
//Class descriptions
public class name
{
public string last { get; set; }
}
public class nameList
{
public List<name> name { get; set; }
}
}
}
If you need a free and simple API for converting one currency to another, try free.currencyconverterapi.com.
Disclaimer, I'm the author of the website and I use it for one of my other websites.
The service is free to use even for commercial applications but offers no warranty. For performance reasons, the values are only updated every hour.
A sample conversion URL is: http://free.currencyconverterapi.com/api/v6/convert?q=EUR_PHP&compact=ultra&apiKey=sample-api-key which will return a json-formatted value, e.g. {"EUR_PHP":60.849184}
Rather than getting lost amongst the random selection of formulae mentioned here, I suggest you go for the formula recommended by W3C standards.
Here's a straightforward but exact PHP implementation of the WCAG 2.0 SC 1.4.3 relative luminance and contrast ratio formulae. It produces values that are appropriate for evaluating the ratios required for WCAG compliance, as on this page, and as such is suitable and appropriate for any web app. This is trivial to port to other languages.
/**
* Calculate relative luminance in sRGB colour space for use in WCAG 2.0 compliance
* @link http://www.w3.org/TR/WCAG20/#relativeluminancedef
* @param string $col A 3 or 6-digit hex colour string
* @return float
* @author Marcus Bointon <[email protected]>
*/
function relativeluminance($col) {
//Remove any leading #
$col = trim($col, '#');
//Convert 3-digit to 6-digit
if (strlen($col) == 3) {
$col = $col[0] . $col[0] . $col[1] . $col[1] . $col[2] . $col[2];
}
//Convert hex to 0-1 scale
$components = array(
'r' => hexdec(substr($col, 0, 2)) / 255,
'g' => hexdec(substr($col, 2, 2)) / 255,
'b' => hexdec(substr($col, 4, 2)) / 255
);
//Correct for sRGB
foreach($components as $c => $v) {
if ($v <= 0.04045) {
$components[$c] = $v / 12.92;
} else {
$components[$c] = pow((($v + 0.055) / 1.055), 2.4);
}
}
//Calculate relative luminance using ITU-R BT. 709 coefficients
return ($components['r'] * 0.2126) + ($components['g'] * 0.7152) + ($components['b'] * 0.0722);
}
/**
* Calculate contrast ratio acording to WCAG 2.0 formula
* Will return a value between 1 (no contrast) and 21 (max contrast)
* @link http://www.w3.org/TR/WCAG20/#contrast-ratiodef
* @param string $c1 A 3 or 6-digit hex colour string
* @param string $c2 A 3 or 6-digit hex colour string
* @return float
* @author Marcus Bointon <[email protected]>
*/
function contrastratio($c1, $c2) {
$y1 = relativeluminance($c1);
$y2 = relativeluminance($c2);
//Arrange so $y1 is lightest
if ($y1 < $y2) {
$y3 = $y1;
$y1 = $y2;
$y2 = $y3;
}
return ($y1 + 0.05) / ($y2 + 0.05);
}
this would work too..
string your_id = "[email protected]";
string your_password = "password";
try
{
SmtpClient client = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential(your_id, your_password),
Timeout = 10000,
};
MailMessage mm = new MailMessage(your_iD, "[email protected]", "subject", "body");
client.Send(mm);
Console.WriteLine("Email Sent");
}
catch (Exception e)
{
Console.WriteLine("Could not end email\n\n"+e.ToString());
}
A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
I see similar answers on here... but not mine...
This is how I am unfortunatley going to deal with it... I like the len(join(arr)) > 0 approach, but it wouldn't work if the array was an array of emptystrings...
Public Function arrayLength(arr As Variant) As Long
On Error GoTo handler
Dim lngLower As Long
Dim lngUpper As Long
lngLower = LBound(arr)
lngUpper = UBound(arr)
arrayLength = (lngUpper - lngLower) + 1
Exit Function
handler:
arrayLength = 0 'error occured. must be zero length
End Function
When starting the Python interpreter in the terminal/command line you may also see a line like:
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Where [MSC v.1500 64 bit (AMD64)]
means 64-bit Python.
Works for my particular setup.
If you don't want to jQuery, here's the vanilla JavaScript:
///Mute
var video = document.getElementById("your-video-id");
video.muted= true;
//Unmute
var video = document.getElementById("your-video-id");
video.muted= false;
It will work for audio too, just put the element's id and it will work (and change the var name if you want, to 'media' or something suited for both audio/video as you like).
The answer given by FelixFett worked for me. To reiterate:
<meta http-equiv="X-UA-Compatible" content="IE=11; IE=10; IE=9; IE=8; IE=7; IE=EDGE" />
I have it as the first 'meta' tag in my code. I added 10 and 11 as those are versions that are published now for Internet Explorer.
I would've just commented on his answer but I do not have a high enough reputation...
// Ready to run
import java.io.File;
public class Filewalker {
public void walk( String path ) {
File root = new File( path );
File[] list = root.listFiles();
if (list == null) return;
for ( File f : list ) {
if ( f.isDirectory() ) {
walk( f.getAbsolutePath() );
System.out.println( "Dir:" + f.getAbsoluteFile() );
}
else {
System.out.println( "File:" + f.getAbsoluteFile() );
}
}
}
public static void main(String[] args) {
Filewalker fw = new Filewalker();
fw.walk("c:\\" );
}
}
you can use :
git clone <url> --branch <branch>
to clone/download only the contents of the branch.
This was helpful to me especially, since the contents of my branch were entirely different from the master branch (though this is not usually the case). Hence, the suggestions listed by others above didn't help me and I would end up getting a copy of the master even after I checked out the branch and did a git pull.
This command would directly give you the contents of the branch. It worked for me.
In that scenario use map, you don't need a new Observable for it.
you should use Exceptions.propagate, which is a wrapper so you can send those checked exceptions to the rx mechanism
Observable<String> obs = Observable.from(jsonFile).map(new Func1<File, String>() {
@Override public String call(File file) {
try {
return new Gson().toJson(new FileReader(file), Object.class);
} catch (FileNotFoundException e) {
throw Exceptions.propagate(t); /will propagate it as error
}
}
});
You then should handle this error in the subscriber
obs.subscribe(new Subscriber<String>() {
@Override
public void onNext(String s) { //valid result }
@Override
public void onCompleted() { }
@Override
public void onError(Throwable e) { //e might be the FileNotFoundException you got }
};);
There is an excellent post for it: http://blog.danlew.net/2015/12/08/error-handling-in-rxjava/
There are long-term maintenance risks as well. First, I'd recommend reading about how Lombok actually works, e.g. some answers from its developers here.
The official site also contains a list of downsides, including this quote from Reinier Zwitserloot:
It's a total hack. Using non-public API. Presumptuous casting (knowing that an annotation processor running in javac will get an instance of JavacAnnotationProcessor, which is the internal implementation of AnnotationProcessor (an interface), which so happens to have a couple of extra methods that are used to get at the live AST).
On eclipse, it's arguably worse (and yet more robust) - a java agent is used to inject code into the eclipse grammar and parser class, which is of course entirely non-public API and totally off limits.
If you could do what lombok does with standard API, I would have done it that way, but you can't. Still, for what its worth, I developed the eclipse plugin for eclipse v3.5 running on java 1.6, and without making any changes it worked on eclipse v3.4 running on java 1.5 as well, so it's not completely fragile.
As a summary, while Lombok may save you some development time, if there is a non-backwards compatible javac update (e.g. a vulnerability mitigation) Lombok might get you stuck with an old version of Java while the developers scramble to update their usage of those internal APIs. Whether this is a serious risk obviously depends on the project.
This setup solved following issues for me:
.../
to .../123
State configuration
state('training', {
abstract: true,
url: '/training',
templateUrl: 'partials/training.html',
controller: 'TrainingController'
}).
state('training.edit', {
url: '/:trainingId'
}).
state('training.new', {
url: '/{trainingId}',
// Optional Parameter
params: {
trainingId: null
}
})
Invoking the states (from any other controller)
$scope.editTraining = function (training) {
$state.go('training.edit', { trainingId: training.id });
};
$scope.newTraining = function () {
$state.go('training.new', { });
};
Training Controller
var newTraining;
if (!!!$state.params.trainingId) {
// new
newTraining = // create new training ...
// Update the URL without reloading the controller
$state.go('training.edit',
{
trainingId : newTraining.id
},
{
location: 'replace', // update url and replace
inherit: false,
notify: false
});
} else {
// edit
// load existing training ...
}
Sometime you must to give all the link like this
System.Web.HttpContext.Current.Request.UrlReferrer.ToString();
(in option when "Current" not founded)
After reading Java 7 Update 21 Security Improvements in Detail mention..
With the introduced changes it is most likely that no end-user is able to run your application when they are either self-signed or unsigned.
..I was wondering how this would go for loose class files - the 'simplest' applets of all.
Your security settings have blocked a local application from running
That is the dialog seen for an applet consisting of loose class files being loaded off the local file system when the JRE is set to the default 'High' security setting.
Note that a slight quirk of the JRE only produced that on point 3 of.
If you load the simple applet (loose class file) seen at this resizable applet demo off the internet - which boasts an applet
element of:
<applet
code="PlafChanger.class"
codebase="."
alt="Pluggable Look'n'Feel Changer appears here if Java is enabled"
width='100%'
height='250'>
<p>Pluggable Look'n'Feel Changer appears here in a Java capable browser.</p>
</applet>
It also seems to load successfully. Implying that:-
Applets loaded from the local file system are now subject to a stricter security sandbox than those loaded from the internet or a local server.
As of Java 7 update 51.
Try following int git bash
1.git add -u :/
2.git commit -m "your commit message"
git push -u origin master
Note:if you have not initialized your repo.
First of all
git init
and follow above mentioned steps in order. This worked for me
I found that, when you use EXTERNAL TABLE and LOCATION together, Hive creates table and initially no data will present (assuming your data location is different from the Hive 'LOCATION').
When you use 'LOAD DATA INPATH' command, the data get MOVED (instead of copy) from data location to location that you specified while creating Hive table.
If location is not given when you create Hive table, it uses internal Hive warehouse location and data will get moved from your source data location to internal Hive data warehouse location (i.e. /user/hive/warehouse/).
psql --pset=format=FORMAT
Great for executing queries from command line, e.g.
psql --pset=format=unaligned -c "select bandanavalue from bandana where bandanakey = 'atlassian.confluence.settings';"
Your function is just fine but isn't working because you put the ()
after the last }
. If you move the ()
to the top just next to new List<string>()
the error stops.
Sample below:
List<string> optionList = new List<string>()
{
"AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
};
Its simple try below code --
a{
outline: medium none !important;
}
If happy cheers! Good day
yum -y remove php*
to remove all php packages then you can install the 5.6 ones.
There is a subtle difference in terms of conflict management. In case of conflicts, a pull request in Github will result in a merge commit on the destination branch. In Gitlab, when a conflict is found, the modifications made will be on a merge commit on the source branch.
See https://docs.gitlab.com/ee/user/project/merge_requests/resolve_conflicts.html
"GitLab resolves conflicts by creating a merge commit in the source branch that is not automatically merged into the target branch. This allows the merge commit to be reviewed and tested before the changes are merged, preventing unintended changes entering the target branch without review or breaking the build."
Cache() and persist() both the methods are used to improve performance of spark computation. These methods help to save intermediate results so they can be reused in subsequent stages.
The only difference between cache() and persist() is ,using Cache technique we can save intermediate results in memory only when needed while in Persist() we can save the intermediate results in 5 storage levels(MEMORY_ONLY, MEMORY_AND_DISK, MEMORY_ONLY_SER, MEMORY_AND_DISK_SER, DISK_ONLY).
Matthew's supremely efficient script updated to use the dm_exec_sessions DMV, replacing the deprecated sysprocesses system table:
USE [master];
GO
DECLARE @Kill VARCHAR(8000) = '';
SELECT
@Kill = @Kill + 'kill ' + CONVERT(VARCHAR(5), session_id) + ';'
FROM
sys.dm_exec_sessions
WHERE
database_id = DB_ID('<YourDB>');
EXEC sys.sp_executesql @Kill;
Alternative using WHILE loop (if you want to process any other operations per execution):
USE [master];
GO
DECLARE @DatabaseID SMALLINT = DB_ID(N'<YourDB>');
DECLARE @SQL NVARCHAR(10);
WHILE EXISTS ( SELECT
1
FROM
sys.dm_exec_sessions
WHERE
database_id = @DatabaseID )
BEGIN;
SET @SQL = (
SELECT TOP 1
N'kill ' + CAST(session_id AS NVARCHAR(5)) + ';'
FROM
sys.dm_exec_sessions
WHERE
database_id = @DatabaseID
);
EXEC sys.sp_executesql @SQL;
END;
DATE_FORMAT(FROM_UNIXTIME(`orderdate`), '%Y-%m-%d %H:%i:%s') as "Date" FROM `orders`
This is the ultimate solution if the given date is in encoded format like 1300464000
Hello this is a snippet from an old project of mine that uses curl to get ip information from some free ip databases services which reply in json format. I think it might help you.
$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");
getUserLocation($ip_srv);
Function:
function getUserLocation($services) {
$ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout
for ($i = 0; $i < count($services); $i++) {
// Configuring curl options
$options = array (
CURLOPT_RETURNTRANSFER => true, // return web page
//CURLOPT_HEADER => false, // don't return headers
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
CURLOPT_TIMEOUT => 5, // timeout on response
CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
);
// Initializing curl
$ch = curl_init($services[$i]);
curl_setopt_array ( $ch, $options );
$content = curl_exec ( $ch );
$err = curl_errno ( $ch );
$errmsg = curl_error ( $ch );
$header = curl_getinfo ( $ch );
$httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
curl_close ( $ch );
//echo 'service: ' . $services[$i] . '</br>';
//echo 'err: '.$err.'</br>';
//echo 'errmsg: '.$errmsg.'</br>';
//echo 'httpCode: '.$httpCode.'</br>';
//print_r($header);
//print_r(json_decode($content, true));
if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {
return json_decode($content, true);
}
}
}
$(document).on('click', '#submitBtn', function(e){
e.preventDefault();
e.stopImmediatePropagation();
var form = $("#myForm").closest("form");
var formData = new FormData(form[0]);
$.ajax({
type: "POST",
data: formData,
dataType: "json",
url: form.attr('action'),
processData: false,
contentType: false,
success: function(data) {
alert('Sucess! Form data posted with file type of input also!');
}
)};});
By making use of new FormData()
and setting processData: false, contentType:false
in ajax call submission of form with file input worked for me
Using above code I am able to submit form data with file field also through Ajax
First you need to set a reference (Menu: Tools->References) to the Microsoft Excel Object Library then you can access all Excel Objects.
After you added the Reference you have full access to all Excel Objects. You need to add Excel in front of everything for example:
Dim xlApp as Excel.Application
Let's say you added an Excel Workbook Object in your Form and named it xLObject.
Here is how you Access a Sheet of this Object and change a Range
Dim sheet As Excel.Worksheet
Set sheet = xlObject.Object.Sheets(1)
sheet.Range("A1") = "Hello World"
(I copied the above from my answer to this question)
Another way to use Excel in Access is to start Excel through a Access Module (the way shahkalpesh described it in his answer)
if you are on Windows
sqlplus / as sysdba
Now you are logged with SYS user and you can do anything you want (query DBA_USERS to find out your username, or change any user password). You can not see the old password, you can only change it.
I'm suprised that no one mentioned this.
Use the Sieve Of Eratosthenes
Details:
The sieve of Eratosthenes finds a prime number and stores it. When a new number is checked for primeness all of the previous primes are checked against the know prime list.
Reasons:
Two native solutions
performance.now
--> Call to ... took 6.414999981643632
milliseconds.console.time
--> Call to ... took 5.815
millisecondsThe difference between both is precision.
For usage and explanation read on.
Performance.now
(For microsecond precision use)
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
function doSomething(){
for(i=0;i<1000000;i++){var x = i*i;}
}
_x000D_
Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.
Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().
console.time
Example: (timeEnd
wrapped in setTimeout
for simulation)
console.time('Search page');
doSomething();
console.timeEnd('Search page');
function doSomething(){
for(i=0;i<1000000;i++){var x = i*i;}
}
_x000D_
You can change the Timer-Name for different operations.
Make sure you're passing a selector to jQuery, not some form of data:
$( '.my-selector' )
not:
$( [ 'my-data' ] )
boolarr.sum(axis=1 or axis=0)
axis = 1 will output number of trues in a row and axis = 0 will count number of trues in columns so
boolarr[[true,true,true],[false,false,true]]
print(boolarr.sum(axis=1))
will be (3,1)
You want this:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
The YAML equivalent of a JSON object is a mapping, which looks like these:
# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2
Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:
# OK
foo: 1
bar: 2
# Parse error
foo: 1
bar: 2
The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):
# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz
In a block sequence the -
s must be in the same column.
Let's turn your JSON into YAML. Here's your JSON:
{"AAPL": [
{
"shares": -75.088,
"date": "11/27/2015"
},
{
"shares": 75.088,
"date": "11/26/2015"
},
]}
As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.
Starting from the inside out, we have objects that look like this:
{
"shares": -75.088,
"date": "11/27/2015"
}
The equivalent YAML mapping is:
shares: -75.088
date: 11/27/2015
We have two of these in an array (sequence):
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Note how the -
s line up and the first characters of the mapping keys line up.
Finally, this sequence is itself a value in a mapping with the key AAPL
:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Parsing this and converting it back to JSON yields the expected result:
{
"AAPL": [
{
"date": "11/27/2015",
"shares": -75.088
},
{
"date": "11/26/2015",
"shares": 75.088
}
]
}
You can see it (and edit it interactively) here.
If you want an index, you can use std::find
in combination with std::distance
.
auto it = std::find(Names.begin(), Names.end(), old_name_);
if (it == Names.end())
{
// name not in vector
} else
{
auto index = std::distance(Names.begin(), it);
}
Use this code:
HttpContext.Current.Server.MapPath("~")
Detailed Reference:
Server.MapPath
specifies the relative or virtual path to map to a physical directory.
Server.MapPath(".")
returns the current physical directory of the
file (e.g. aspx) being executedServer.MapPath("..")
returns the parent directoryServer.MapPath("~")
returns the physical path to the root of the
applicationServer.MapPath("/")
returns the physical path to the root of the
domain name (is not necessarily the same as the root of the
application)An example:
Let's say you pointed a web site application (http://www.example.com/) to
C:\Inetpub\wwwroot
and installed your shop application (sub web as virtual directory in IIS, marked as application) in
D:\WebApps\shop
For example, if you call Server.MapPath
in following request:
http://www.example.com/shop/products/GetProduct.aspx?id=2342
then:
Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop
If Path starts with either a forward (/) or backward slash (), the MapPath
method returns a path as if Path were a full, virtual path.
If Path doesn't start with a slash, the MapPath
method returns a path relative to the directory of the request being processed.
Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.
Footnotes
Server.MapPath(null)
and Server.MapPath("")
will produce this effect too.
You can pass a string with your list and use a prepared statements to run a query, e.g. -
DELIMITER $$
CREATE PROCEDURE GetFruits(IN fruitArray VARCHAR(255))
BEGIN
SET @sql = CONCAT('SELECT * FROM Fruits WHERE Name IN (', fruitArray, ')');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
$$
DELIMITER ;
How to use:
SET @fruitArray = '\'apple\',\'banana\'';
CALL GetFruits(@fruitArray);
There is a really nice tutorial that goes over this and other related stuff - Submitting AJAX Forms: The AngularJS Way.
Basically, you need to set the header of the POST request to indicate that you are sending form data as a URL encoded string, and set the data to be sent the same format
$http({
method : 'POST',
url : 'url',
data : $.param(xsrf), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
});
Note that jQuery's param() helper function is used here for serialising the data into a string, but you can do this manually as well if not using jQuery.
Replace:
myBinding.Source = ViewModel.SomeString;
with:
myBinding.Source = ViewModel;
Example:
Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);
Your source should be just ViewModel
, the .SomeString
part is evaluated from the Path
(the Path
can be set by the constructor or by the Path
property).
One or more of your .cpp files is not being linked in, or some non-inline functions in some class are not defined. In particular, takeaway::textualGame()
's implementation can't be found. Note that you've defined a textualGame()
at toplevel, but this is distinct from a takeaway::textualGame()
implementation - probably you just forgot the takeaway::
there.
What the error means is that the linker can't find the "vtable" for a class - every class with virtual functions has a "vtable" data structure associated with it. In GCC, this vtable is generated in the same .cpp file as the first listed non-inline member of the class; if there's no non-inline members, it will be generated wherever you instantiate the class, I believe. So you're probably failing to link the .cpp file with that first-listed non-inline member, or never defining that member in the first place.
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
Thanks to dimo414's answer to a similar question, this shows how his great solution works, and shows that you can have quotes and variables in the text easily as well:
$ ./test.sh
The text from the example function is:
Welcome dev: Would you "like" to know how many 'files' there are in /tmp?
There are " 38" files in /tmp, according to the "wc" command
#!/bin/bash
function text1()
{
COUNT=$(\ls /tmp | wc -l)
cat <<EOF
$1 Would you "like" to know how many 'files' there are in /tmp?
There are "$COUNT" files in /tmp, according to the "wc" command
EOF
}
function main()
{
OUT=$(text1 "Welcome dev:")
echo "The text from the example function is: $OUT"
}
main
One example of usage for null
values is when using a HashMap
as a cache for results of an expensive operation (such as a call to an external web service) which may return null
.
Putting a null
value in the map then allows you to distinguish between the case where the operation has not been performed for a given key (cache.containsKey(someKey)
returns false
), and where the operation has been performed but returned a null
value (cache.containsKey(someKey)
returns true
, cache.get(someKey)
returns null
).
Without null
values, you would have to either put some special value in the cache to indicate a null
response, or simply not cache that response at all and perform the operation every time.
On Windows 7, I had to delete %HOMEPATH%/pip
.
Swift 4
let combination = NSMutableAttributedString()
var part1 = NSMutableAttributedString()
var part2 = NSMutableAttributedString()
var part3 = NSMutableAttributedString()
let attrRegular = [NSAttributedStringKey.font : UIFont(name: "Palatino-Roman", size: 15)]
let attrBold:Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15)]
let attrBoldWithColor: Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15),
NSAttributedStringKey.foregroundColor: UIColor.red]
if let regular = attrRegular as? [NSAttributedStringKey : NSObject]{
part1 = NSMutableAttributedString(string: "first", attributes: regular)
}
if let bold = attrRegular as? [NSAttributedStringKey : NSObject]{
part2 = NSMutableAttributedString(string: "second", attributes: bold)
}
if let boldWithColor = attrBoldWithColor as? [NSAttributedStringKey : NSObject]{
part3 = NSMutableAttributedString(string: "third", attributes: boldWithColor)
}
combination.append(part1)
combination.append(part2)
combination.append(part3)
Attributes list please see here NSAttributedStringKey on Apple Docs
If anyone like me is searching to read only a specific line, example only line 18 here is the code:
filename = "C:\log.log"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
For i = 1 to 17
f.ReadLine
Next
strLine = f.ReadLine
Wscript.Echo strLine
f.Close
This isn't going to be exactly perfect though I was happy to discover that you can control the horizontal and vertical border-spacing separately:
table
{
border-collapse: separate;
border-spacing: 0 8px;
}
One way that I see more powerful and avoid having a isDefault
in all the models is by using the ng-attributes ng-model
, ng-value
and ng-checked
.
ng-model: binds the value to your model.
ng-value: the value to pass to the ng-model
binding.
ng-checked: value or expression that is evaluated. Useful for radio-button and check-boxes.
Example of use: In the following example, I have my model and a list of languages that my site supports. To display the different languages supported and updating the model with the selecting language we can do it in this way.
<!-- Radio -->
<div ng-repeat="language in languages">
<div>
<label>
<input ng-model="site.lang"
ng-value="language"
ng-checked="(site.lang == language)"
name="localizationOptions"
type="radio">
<span> {{language}} </span>
</label>
</div>
</div>
<!-- end of Radio -->
Our model site.lang
will get a language
value whenever the expression under evaluation (site.lang == language)
is true. This will allow you to sync it with server easily since your model already has the change.
Here's a performant and simple function I created (which uses basic string validation before using json_decode
for larger strings):
function isJson($string) {
$response = false;
if (
is_string($string) &&
($string = trim($string)) &&
($stringLength = strlen($string)) &&
(
(
stripos($string, '{') === 0 &&
(stripos($string, '}', -1) + 1) === $stringLength
) ||
(
stripos($string, '[{') === 0 &&
(stripos($string, '}]', -1) + 2) === $stringLength
)
) &&
($decodedString = json_decode($string, true)) &&
is_array($decodedString)
) {
$response = true;
}
return $response;
}
There are many ways to update your path. Jun1st answer works great. Another method is to augment your .bash_profile
to have:
export PATH="/usr/local/bin:/usr/local/sbin:~/bin:$PATH"
The line above places /usr/local/bin
and /usr/local/sbin
in front of your $PATH
. Once you source your .bash_profile
or start a new terminal you can verify your path by echo'ing it out.
$ echo $PATH
/usr/local/bin:/usr/local/sbin:/Users/<your account>/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
Once satisfied with the result running $ brew doctor
again should no longer produce your error.
This blog post helped me out in resolving issues I ran into. http://moncefbelyamani.com/how-to-install-xcode-homebrew-git-rvm-ruby-on-mac/
I've modified Greg's answer to suit my case, and it works. Here it is:
$("#note-items").children('.active').hide('slow', function(){ $("#note-items").children('.active').remove(); });
I needed to indent two rows to allow for a larger first word in a para. A cumbersome one-off solution is to place text in an SVG element and position this the same as an <img>. Using float and the SVG's height tag defines how many rows will be indented e.g.
<p style="color: blue; font-size: large; padding-top: 4px;">
<svg height="44" width="260" style="float:left;margin-top:-8px;"><text x="0" y="36" fill="blue" font-family="Verdana" font-size="36">Lorum Ipsum</text></svg>
dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
Yes it is cumbersome but it is also independent of the width of the containing div.
The above answer was to my own query to allow the first word(s) of a para to be larger and positioned over two rows. To simply indent the first two lines of a para you could replace all the SVG tags with the following single pixel img:
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" style="float:left;width:260px;height:44px;" />
Add this to your .prettierrc file and open the VSCODE
"endOfLine": "auto"
Most easy and clean solution to avoid this is adding onclick="return false;"
to a
tag.
<ul class="nav nav-tabs">
<li class="active">
<a href="#home" onclick="return false;">Home</a>
</li>
<li>
<a href="#ApprovalDetails" onclick="return false;">Approval Details</a>
</li>
</ul>
"cursor:no-drop;"
just makes cursor look disabled, but is clickable, Url gets appending with href target for ex page.apsx#Home
"disabled"
class to <li>
AND removing href
I simply use this jQuery trick:
$("a:focus").attr('data-id');
It gets the focused a
element and gets the data-id
attribute from it.
If you don't want Vim to mangle formatting in incoming pasted text, you might also want to consider using: :set paste
. This will prevent Vim from re-tabbing your code. When done pasting, :set nopaste
will return to the normal behavior.
It's also possible to toggle the mode with a single key, by adding something like set pastetoggle=<F2>
to your .vimrc. More details on toggling auto-indent are here.
You can use $(":disabled")
to select all disabled items in the current context.
To determine whether a single item is disabled you can use $("#textbox1").is(":disabled")
.
That looks like it should stop the service when you uncheck the checkbox. Are there any exceptions in the log? stopService returns a boolean indicating whether or not it was able to stop the service.
If you are starting your service by Intents, then you may want to extend IntentService instead of Service. That class will stop the service on its own when it has no more work to do.
AutoService
class AutoService extends IntentService {
private static final String TAG = "AutoService";
private Timer timer;
private TimerTask task;
public onCreate() {
timer = new Timer();
timer = new TimerTask() {
public void run()
{
System.out.println("done");
}
}
}
protected void onHandleIntent(Intent i) {
Log.d(TAG, "onHandleIntent");
int delay = 5000; // delay for 5 sec.
int period = 5000; // repeat every sec.
timer.scheduleAtFixedRate(timerTask, delay, period);
}
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
timer.cancel();
task.cancel();
return super.stopService(name);
}
}
I would recommend Tim's answer. However, this comment by @blazs states "Suppose searchStr=aaa
and that str=aaaaaa
. Then instead of finding 4 occurences your code will find only 2 because you're making skips by searchStr.length in the loop.", which is true by looking at Tim's code, specifically this line here: startIndex = index + searchStrLen;
Tim's code would not be able to find an instance of the string that's being searched that is within the length of itself. So, I've modified Tim's answer:
function getIndicesOf(searchStr, str, caseSensitive) {
var startIndex = 0, index, indices = [];
if (!caseSensitive) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
}
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + 1;
}
return indices;
}
var searchStr = prompt("Enter a string.");
var str = prompt("What do you want to search for in the string?");
var indices = getIndicesOf(str, searchStr);
document.getElementById("output").innerHTML = indices + "";
_x000D_
<div id="output"></div>
_x000D_
Changing it to + 1
instead of + searchStrLen
will allow the index 1 to be in the indices array if I have an str of aaaaaa
and a searchStr of aaa
.
P.S. If anyone would like comments in the code to explain how the code works, please say so, and I'll be happy to respond to the request.
You should not use "width" and "height" attributes directly, use the style attribute like style="some css here"
if you want to use inline styling:
<div class="button" style="width:60px;height:30px;">This is a button</div>
Note, however, that inline styling should generally be avoided since it makes maintenance and style updates a nightmare. Personally, if I had a button styling like yours but also wanted to apply different sizes, I would work with multiple css classes for sizing, like this:
.button {_x000D_
background-color: #000000;_x000D_
color: #FFFFFF;_x000D_
padding: 10px;_x000D_
border-radius: 10px;_x000D_
-moz-border-radius: 10px;_x000D_
-webkit-border-radius: 10px;_x000D_
margin:10px_x000D_
}_x000D_
_x000D_
.small-btn {_x000D_
width: 50px;_x000D_
height: 25px;_x000D_
}_x000D_
_x000D_
.medium-btn {_x000D_
width: 70px;_x000D_
height: 30px;_x000D_
}_x000D_
_x000D_
.big-btn {_x000D_
width: 90px;_x000D_
height: 40px;_x000D_
}
_x000D_
<div class="button big-btn">This is a big button</div>_x000D_
<div class="button medium-btn">This is a medium button</div>_x000D_
<div class="button small-btn">This is a small button</div>_x000D_
_x000D_
Using this way of defining styles removes all style information from your HTML markup, which in will make it easier down the road if you want to change the size of all small buttons - you'll only have to change them once in the CSS.
I just encountered this. You may be accessing a method/type from within the same package using the package name itself.
Here is an example to illustrate what I mean:
In foo.go:
// foo.go
package foo
func Foo() {...}
In foo_test.go:
// foo_test.go
package foo
// try to access Foo()
foo.Foo() // WRONG <== This was the issue. You are already in package foo, there is no need to use foo.Foo() to access Foo()
Foo() // CORRECT