Based on another solutions. I have use this:
IntPtr xAsIntPtr = new IntPtr(excelObj.Application.Hwnd);
excelObj.ActiveWorkbook.Close();
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (System.Diagnostics.Process p in process)
{
if (p.MainWindowHandle == xAsIntPtr)
{
try
{
p.Kill();
}
catch { }
}
}
Using the "MainWindowHandle" to identify the process and close him.
excelObj: This is my Application Interop excel objecto
Here is the solution:
show full processlist;
to get the process id with status and query itself which causes the database hanging;KILL <pid>;
to kill that process.Sometimes it is not enough to kill each process manually. So, for that we've to go with some trick:
Select concat('KILL ',id,';') from information_schema.processlist where user='user';
to print all processes with KILL
command;|
sign, copy and paste all again into the query console. HIT ENTER. BooM it's done.Paste this into command line
FOR /F "tokens=5 delims= " %P IN ('netstat -ano ^| find "LISTENING" ^| find ":8080 "') DO (TASKKILL /PID %P)
If you want to use it in a batch pu %%P
instead of %P
Quick Answer:
foreach (var process in Process.GetProcessesByName("whatever"))
{
process.Kill();
}
(leave off .exe from process name)
1) Go to (Open) Command Prompt (Press Window + R then type cmd Run this).
2) Run following commands
For all listening ports
Apply port filter
Finally with the PID we can run the following command to kill the process
3) Copy PID from result set
Ex: taskkill /F /PID 189
Done !!! you can start your service now.
If you just want to kill any/all java processes, then all you need is;
killall java
If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;
PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID
Should do it, there is probably an easier way though...
Get the PID of the task and kill it.
lsof -ti:8080 | xargs kill
Send the signal to all the processes in group
self.proc = Popen(commands,
stdout=PIPE,
stderr=STDOUT,
universal_newlines=True,
preexec_fn=os.setsid)
os.killpg(os.getpgid(self.proc.pid), signal.SIGHUP)
os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)
"Unlink" essentially means "delete file" in this case.
This error is not caused by git itself. You should have similar errors deleting those files manually, in a command line or file explorer.
I lost a lot of time on this stupid issue, and i think the message is quite right "there is not the host in the file i'm accessing" but you can have more than a know_host file around on your system (as example i'm using mobaXterm and it keep it's own inside the installation directory mounting the home from that root).
If you are experiencing : it's working from command line but not form the application try to access to your remote server with ssh and check with verbose -v option which file is currently used an example following:
ssh -v [email protected]
OpenSSH_6.2p2, OpenSSL 1.0.1g 7 Apr 2014
debug1: Reading configuration data /etc/ssh_config
debug1: Connecting to gitlab.com [104.210.2.228] port 22.
debug1: Connection established.
debug1: identity file /home/mobaxterm/.ssh/id_rsa type 1
debug1: identity file /home/mobaxterm/.ssh/id_rsa-cert type -1
debug1: identity file /home/mobaxterm/.ssh/id_dsa type -1
debug1: identity file /home/mobaxterm/.ssh/id_dsa-cert type -1
debug1: identity file /home/mobaxterm/.ssh/id_ecdsa type -1
debug1: identity file /home/mobaxterm/.ssh/id_ecdsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.1
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.1 pat OpenSSH*
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr [email protected] [email protected]
debug1: kex: client->server aes128-ctr [email protected] [email protected]
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: RSA b6:03:0e:39:97:9e:d0:e7:24:ce:a3:77:3e:01:42:09
debug1: Host 'gitlab.com' is known and matches the RSA host key.
debug1: Found key in /home/mobaxterm/.ssh/known_hosts:19
debug1: ssh_rsa_verify: signature correct
as you can see the key was found in :
debug1: Found key in /home/mobaxterm/.ssh/known_hosts:19
and not in my windows home under C:\Users\my_local_user\.ssh , i simply merged them and aligned for solve the issue.
Hope this help someone in future
If you want a simple visual comparison on Windows such as you can get in Visual SourceSafe or Team Foundation Server (TFS), try this:
Note: After upgrading to Windows 10 I have lost the Git context menu options. However, you can achieve the same thing using 'gitk' or 'gitk filename' in a command window.
Once you call 'Git History', the Git GUI tool will start, with a history of the file in the top left pane. Select one of the versions you would like to compare. Then right-click on the second version and choose either
Diff this -> selected
or
Diff selected -> this
Colour-coded differences will appear in the lower left-hand pane.
In all of the cases above, the variable is correctly set, but not correctly read! The right way is to use double quotes when referencing:
echo "$var"
This gives the expected value in all the examples given. Always quote variable references!
Why?
When a variable is unquoted, it will:
Undergo field splitting where the value is split into multiple words on whitespace (by default):
Before: /* Foobar is free software */
After: /*
, Foobar
, is
, free
, software
, */
Each of these words will undergo pathname expansion, where patterns are expanded into matching files:
Before: /*
After: /bin
, /boot
, /dev
, /etc
, /home
, ...
Finally, all the arguments are passed to echo, which writes them out separated by single spaces, giving
/bin /boot /dev /etc /home Foobar is free software Desktop/ Downloads/
instead of the variable's value.
When the variable is quoted it will:
This is why you should always quote all variable references, unless you specifically require word splitting and pathname expansion. Tools like shellcheck are there to help, and will warn about missing quotes in all the cases above.
IIS version 8.5 +
To enable Event Tracing for Windows for your website/application
Custom Views > ServerRoles > Web Server
Windows Logs > System
Try to understand through this below function using python3
def floating_decimals(f_val, dec):
prc = "{:."+str(dec)+"f}" #first cast decimal as str
print(prc) #str format output is {:.3f}
return prc.format(f_val)
print(floating_decimals(50.54187236456456564, 3))
Output is : 50.542
Hope this helps you!
A great blog describing 14 address finders: https://www.conversion-uplift.co.uk/free-address-lookup-tools/
Many address autocomplete services, including Google's Places API, appears to offer international address support but it has limited accuracy.
For example, New Zealand address and geolocation data are free to download from Land Information New Zealand (LINZ). When a user search for an address such as 76 Francis St Hauraki from Google or Address Doctor, a positive match is returned. The land parcel was matched but not the postal/delivery address, which is either 76A or 76B. The problem is amplified with apartments and units on a single land parcel.
For 100% accuracy, use a country-specific address finder instead such as https://www.addy.co.nz for NZ address autocomplete.
Some of ways below for different circumstances.
In most normal cases, the simplest way to access the first element is by
yourArray[0]
but this requires you to check if [0] actually exists.
There are real world cases where you don't care about the original array, and don't want to check if index exists, you want just to get the first element or undefined inline.
In this case, you can use shift() method to get the first element, but be cautious that this method modifies the original array (removes the first item and returns it). Therefore the length of an array is reduced by one. This method can be used in inline cases where you just need to get the first element, but you dont care about the original array.
yourArray.shift()
The important thing to know is that the two above are only an option if your array starts with a [0] index.
There are cases where the first element has been deleted, example with, delete yourArray[0] leaving your array with "holes". Now the element at [0] is simply undefined, but you want to get the first "existing" element. I have seen many real world cases of this.
So, assuming we have no knowledge of the array and the first key (or we know there are holes), we can still get the first element.
You can use find() to get the first element.
The advantage of find() is its efficiency as it exits the loop when the first value satisfying the condition is reached (more about this below). (You can customize the condition to exclude null or other empty values too)
var firstItem = yourArray.find(x=>x!==undefined);
I'd also like to include filter() here as an option to first "fix" the array in the copy and then get the first element while keeping the the original array intact (unmodified).
Another reason to include filter() here is that it existed before find() and many programmers have already been using it (it is ES5 against find() being ES6).
var firstItem = yourArray.filter(x => typeof x!==undefined).shift();
Warning that filter() is not really an efficient way (filter() runs through all elements) and creates another array. It is fine to use on small arrays as performance impact would be marginal, closer to using forEach, for example.
(I see some people suggest using for...in loop to get the first element, but I would recommend against this method for...in should not be used to iterate over an Array where the index order is important because it doesn't guarantee the order although you can argue browsers mostly respect the order.By the way, forEach doesn't solve the issue as many suggest because you cant break it and it will run through all elements. You would be better off using a simple for loop and by checking key/value
Both find() and filter() guarantee the order of elements, so are safe to use as above.
No. That is not possible. You should use an array instead:
name[i] = i;
In this case, your name+i
is name[i]
.
You are missing a space between else
and if
It should be else if
instead of elseif
if(condition)
{
}
else if(condition)
{
}
else
{
}
The two have different semantics when it comes to the key already existing in the map. So they aren't really directly comparable.
But the operator[] version requires default constructing the value, and then assigning, so if this is more expensive then copy construction, then it will be more expensive. Sometimes default construction doesn't make sense, and then it would be impossible to use the operator[] version.
Mutex work on blocking critical region, But Semaphore work on count.
Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule
It happened to me when the auto formatter in a visual studio project sorted my includes after which the pre compiled header was not the first include anymore.
In other words. If you have any of these:
#include "pch.h"
or
#include <stdio.h>
or
#include <iostream>
#include "stdafx.h"
Put it at the start of your file.
If your clang formatter is sorting the files automatically, try putting an enter after the pre compiled header. If it is on IBS_Preserve it will sort each #include block separately.
#include "pch.h" // must be first
#include "bar.h" // next block
#include "baz.h"
#include "foo.h"
More info at Compiler Error C2065
You can use require with the path to the global module directory as an argument.
require('/path/to/global/node_modules/the_module');
On my mac, I use this:
require('/usr/local/lib/node_modules/the_module');
How to find where your global modules are? --> Where does npm install packages?
Or File::Find
use File::Find;
finddepth(\&wanted, '/some/path/to/dir');
sub wanted { print };
It'll go through subdirectories if they exist.
Use something like this -
SELECT DISTINCT COL_NAME FROM myTable WHERE UPPER(COL_NAME) LIKE UPPER('%PriceOrder%')
or
SELECT DISTINCT COL_NAME FROM myTable WHERE LOWER(COL_NAME) LIKE LOWER('%PriceOrder%')
Why not use them in the Users directory in the .bash_profile
file, so you don't have to push any files with your variables to production?
DataTable.Clone()
should do the trick.
DataTable newTable = originalTable.Clone();
Thread-safe code is code that will work even if many Threads are executing it simultaneously.
The app is stored in %LocalAppData%
in your %UserProfile%
. So the full path could be:
C:\Users\username\AppData\Local\GitHub
First you have to check login existence using syslogins view:
IF NOT EXISTS
(SELECT name
FROM master.sys.server_principals
WHERE name = 'YourLoginName')
BEGIN
CREATE LOGIN [YourLoginName] WITH PASSWORD = N'password'
END
Then you have to check your database existence:
USE your_dbname
IF NOT EXISTS
(SELECT name
FROM sys.database_principals
WHERE name = 'your_dbname')
BEGIN
CREATE USER [your_dbname] FOR LOGIN [YourLoginName]
END
Basic Solution for Laravel 8 is
use Illuminate\Support\Facades\Http;
$response = Http::get('http://example.com');
I had conflict between "GuzzleHTTP sending requests" and "Illuminate\Http\Request;" don't ask me why... [it's here to be searchable]
So looking for 1sec i found in Laravel 8 Doc...
https://laravel.com/docs/8.x/http-client#making-requests
as you can see
https://laravel.com/docs/8.x/http-client#introduction
Laravel provides an expressive, minimal API around the Guzzle HTTP client, allowing you to quickly make outgoing HTTP requests to communicate with other web applications. Laravel's wrapper around Guzzle is focused on its most common use cases and a wonderful developer experience.
It worked for me very well, have fun and if helpful point up!
reload the app and the cause of this error is the changes of files location made in react-native dependency which other libraries like native-base point to.
To solve it you need to view the mentioned file and change the file location to the correct location.
If you're using Git-Gui, it tells you when you should worry:
This repository currently has approximately 1500 loose objects.
The following command will bring a similar number:
$ git count-objects
Except, from its source, git-gui will do the math by itself, actually counting something at .git/objects
folder and probably brings an approximation (I don't know tcl
to properly read that!).
In any case, it seems to give the warning based on an arbitrary number around 300 loose objects.
You gave a condition ID (>79 and < 296) then the answer is:
delete from tab
where id > 79 and id < 296
this is the same as:
delete from tab
where id between 80 and 295
if id
is an integer.
All answered:
delete from tab
where id between 79 and 296
this is the same as:
delete from tab
where id => 79 and id <= 296
Mind the difference.
You can comma-separate shadows:
box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;
Thanx @krd, I am using your error catch process, but had to update the print and except statements. I am using Python 2.7.6 on Linux Mint 17.2.
Also, it was unclear where the output string was coming from. My update:
import subprocess
# Output returned in error handler
try:
print("Ping stdout output on success:\n" +
subprocess.check_output(["ping", "-c", "2", "-w", "2", "1.1.1.1"]))
except subprocess.CalledProcessError as e:
print("Ping stdout output on error:\n" + e.output)
# Output returned normally
try:
print("Ping stdout output on success:\n" +
subprocess.check_output(["ping", "-c", "2", "-w", "2", "8.8.8.8"]))
except subprocess.CalledProcessError as e:
print("Ping stdout output on error:\n" + e.output)
I see an output like this:
Ping stdout output on error:
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
--- 1.1.1.1 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1007ms
Ping stdout output on success:
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=59 time=37.8 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=59 time=38.8 ms
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 37.840/38.321/38.802/0.481 ms
I came to this question looking to solve the "too many open files" error
, but I am using requests.session()
in my code. A few searches later and I came up with an answer on the Python Requests Documentation which suggests to use the with
block so that the session is closed even if there are unhandled exceptions:
with requests.Session() as s:
s.get('http://google.com')
If you're not using Session you can actually do the same thing: https://2.python-requests.org/en/master/user/advanced/#session-objects
with requests.get('http://httpbin.org/get', stream=True) as r:
# Do something
I tested this and it works fine for me:
from PIL import Image
im = Image.open('image.jpg')
im.show()
If you want to make it center then use android:layout_centerVertical="true"
in the TextView.
You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/
IE Driver is also available in the following site:
You can simply define a style for links, which would override a:hover
, a:visited
etc.:
a {
color: blue;
text-decoration: none; /* no underline */
}
You can also use the inherit
value if you want to use attributes from parent styles instead:
body {
color: blue;
}
a {
color: inherit; /* blue colors for links too */
text-decoration: inherit; /* no underline */
}
You might also see this error if you attempt to parse the same file twice from the same source.
I was parsing the file once to validate and again (from the same InputStream) to process - this produced the above error.
To get round this I parsed the source file into 2 different InputStreams, one to validate and one to process.
tl;dr; Excel does all of this natively - use filters and or tables
(http://office.microsoft.com/en-gb/excel-help/filter-data-in-an-excel-table-HA102840028.aspx)
You can open excel programatically through an oledb connection and execute SQL on the tables within the worksheet.
But you can do everything you are asking to do with no formulas just filters.
have a play around.. some things to note:
DO it with filters unless you are going to do it a lot or you want to automate importing data somewhere or something.. but for completeness:
A c# option:
OleDbConnection ExcelFile = new OleDbConnection( String.Format( "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES\"", filename));
ExcelFile.Open();
a handy place to start is to take a look at the schema as there may be more there than you think:
List<String> excelSheets = new List<string>();
// Add the sheet name to the string array.
foreach (DataRow row in dt.Rows) {
string temp = row["TABLE_NAME"].ToString();
if (temp[temp.Length - 1] == '$') {
excelSheets.Add(row["TABLE_NAME"].ToString());
}
}
then when you want to query a sheet:
OleDbDataAdapter da = new OleDbDataAdapter("select * from [" + sheet + "]", ExcelFile);
dt = new DataTable();
da.Fill(dt);
NOTE - Use Tables in excel!:
Excel has "tables" functionality that make data behave more like a table.. this gives you some great benefits but is not going to let you do every type of query.
http://office.microsoft.com/en-gb/excel-help/overview-of-excel-tables-HA010048546.aspx
For tabular data in excel this is my default.. first thing i do is click into the data then select "format as table" from the home section on the ribbon. this gives you filtering, and sorting by default and allows you to access the table and fields by name (e.g. table[fieldname] ) this also allows aggregate functions on columns e.g. max and average
WHERE
date_created >= DATEADD(MONTH, DATEDIFF(MONTH, 31, CURRENT_TIMESTAMP), 0)
AND date_created < DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0)
Refer this question: The mouseEvent.offsetX I am getting is much larger than actual canvas size .I have given a function there which will exactly suit in your situation
Java:
String s= "abcdef";
if(s.matches("[a-zA-Z]+")){
System.out.println("string only contains letters");
}
Only want to clone the structure of table:
CREATE TABLE foo SELECT * FROM bar WHERE 1 = 2;
Also wants to copy the data:
CREATE TABLE foo as SELECT * FROM bar;
I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:
f, ax = plt.subplots(figsize=(16, 12))
at the meantime until you get a matched size colobar. This worked for me.
There's a term subroutine or subprogram which stands for a parameterized piece of code that can be called from different places.
Functions and procedures are implementations of those. Usually functions return values and procedures don't return anything.
UUID uses java.security.SecureRandom
, which is supposed to be "cryptographically strong". While the actual implementation is not specified and can vary between JVMs (meaning that any concrete statements made are valid only for one specific JVM), it does mandate that the output must pass a statistical random number generator test.
It's always possible for an implementation to contain subtle bugs that ruin all this (see OpenSSH key generation bug) but I don't think there's any concrete reason to worry about Java UUIDs's randomness.
Assuming you are a new starter on Android Studio, Simply you can get it done in design view XML by using
android:textStyle="bold" //to make text bold
android:textStyle="italic" //to make text italic
android:textStyle="bold|italic" //to make text bold & italic
I'd make both the input
and label
elements display: block
, and then split the name label & input, and the email label & input into div's
and float them next to each other.
input, label {_x000D_
display:block;_x000D_
}
_x000D_
<form name="message" method="post">_x000D_
<section>_x000D_
_x000D_
<div style="float:left;margin-right:20px;">_x000D_
<label for="name">Name</label>_x000D_
<input id="name" type="text" value="" name="name">_x000D_
</div>_x000D_
_x000D_
<div style="float:left;">_x000D_
<label for="email">Email</label>_x000D_
<input id="email" type="text" value="" name="email">_x000D_
</div>_x000D_
_x000D_
<br style="clear:both;" />_x000D_
_x000D_
</section>_x000D_
_x000D_
<section>_x000D_
_x000D_
<label for="subject">Subject</label>_x000D_
<input id="subject" type="text" value="" name="subject">_x000D_
<label for="message">Message</label>_x000D_
<input id="message" type="text" value="" name="message">_x000D_
_x000D_
</section>_x000D_
</form>
_x000D_
pylint error: "Unable to import 'django.X'"
After activating the desired Python interpreter in your conda environment, VS Code will sometimes continue to use pylint from the default conda environment. For example:
/home/<username>/anaconda3/bin/pylint
$ conda activate <target environment>
$ conda install pylint
/home/<username>/anaconda3/envs/<target environment>/bin/pylint
Replace <username>
and <target environment>
according to your system configuration.
Now pylint will find the installed libraries, including Django, presuming that Django has been installed in <target environment>.
$ conda install pylint-django
Update the VS Code Settings to use the plugin:
--load-plugins=pylint_django
--django-settings-module=<PROJECT FOLDER>.settings
<PROJECT FOLDER>
with the folder containing the "settings.py" Django configuration file.Is your server single-threaded? If so, what polling / multiplexing function are you using?
Using select() does not work beyond the hard-coded maximum file descriptor limit set at compile-time, which is hopeless (normally 256, or a few more).
poll() is better but you will end up with the scalability problem with a large number of FDs repopulating the set each time around the loop.
epoll() should work well up to some other limit which you hit.
10k connections should be easy enough to achieve. Use a recent(ish) 2.6 kernel.
How many client machines did you use? Are you sure you didn't hit a client-side limit?
I was having the same problem with android tabs when trying to place them on the bottom of the screen. My scenario was to not use a layout file and create the tabs in code, I was also looking to fire activities from each tab which seemed a bit too complex using other approaches so, here is the sample code to overcome the problem:
var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;
I had trouble getting the answer back from the dialog box but eventually came up with a solution by combining the answer from this other question display-yes-and-no-buttons-instead-of-ok-and-cancel-in-confirm-box with part of the code from the modal-confirmation dialog
This is what was suggested for the other question:
Create your own confirm box:
<div id="confirmBox">
<div class="message"></div>
<span class="yes">Yes</span>
<span class="no">No</span>
</div>
Create your own confirm()
method:
function doConfirm(msg, yesFn, noFn)
{
var confirmBox = $("#confirmBox");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function()
{
confirmBox.hide();
});
confirmBox.find(".yes").click(yesFn);
confirmBox.find(".no").click(noFn);
confirmBox.show();
}
Call it by your code:
doConfirm("Are you sure?", function yes()
{
form.submit();
}, function no()
{
// do nothing
});
MY CHANGES
I have tweaked the above so that instead of calling confirmBox.show()
I used confirmBox.dialog({...})
like this
confirmBox.dialog
({
autoOpen: true,
modal: true,
buttons:
{
'Yes': function () {
$(this).dialog('close');
$(this).find(".yes").click();
},
'No': function () {
$(this).dialog('close');
$(this).find(".no").click();
}
}
});
The other change I made was to create the confirmBox div within the doConfirm function, like ThulasiRam did in his answer.
This problem can be easily solved by using view models. View models are classes that are specifically tailored to the needs of a given view. So for example in your case you could have the following view models:
public UpdateViewView
{
[Required]
public string Id { get; set; }
... some other properties
}
public class InsertViewModel
{
public string Id { get; set; }
... some other properties
}
which will be used in their corresponding controller actions:
[HttpPost]
public ActionResult Update(UpdateViewView model)
{
...
}
[HttpPost]
public ActionResult Insert(InsertViewModel model)
{
...
}
Currently PIP does not have a 32bit version of tensorflow, it worked when I uninstalled python 32bit and installed x64
Try this...
function Test()
{
var s1 = new StopWatch();
s1.Start();
// Do something.
s1.Stop();
alert( s1.ElapsedMilliseconds );
}
// Create a stopwatch "class."
StopWatch = function()
{
this.StartMilliseconds = 0;
this.ElapsedMilliseconds = 0;
}
StopWatch.prototype.Start = function()
{
this.StartMilliseconds = new Date().getTime();
}
StopWatch.prototype.Stop = function()
{
this.ElapsedMilliseconds = new Date().getTime() - this.StartMilliseconds;
}
Remember, you are NOT allowed to do this.
class foo():
def print_hello(self):
print("Hello") # This next line will produce an ERROR!
self.print_hello() # <---- it calls a class function, inside a class,
# but outside a class function. Not allowed.
You must call a class function from either outside the class, or from within a function in that class.
There are several ways to do this. Having a container around the radio buttons is highly recommended regardless, but you can also put a class directly on the buttons. With this HTML:
<ul id="shapeList" class="radioList">
<li><label>Shape:</label></li>
<li><input id="shapeList_0" class="shapeButton" type="radio" value="Circular" name="shapeList" /><label for="shapeList_0">Circular</label></li>
<li><input id="shapeList_1" class="shapeButton" type="radio" value="Rectangular" name="shapeList" /><label for="shapeList_1">Rectangular</label></li>
</ul>
you can select by class:
$(".shapeButton").click(SetShape);
or select by container ID:
$("#shapeList").click(SetShape);
In either case, the event will trigger on clicking either the radio button or the label for it, though oddly in the latter case (Selecting by "#shapeList"), clicking on the label will trigger the click function twice for some reason, at least in FireFox; selecting by class won't do that.
SetShape is a function, and looks like this:
function SetShape() {
var Shape = $('.shapeButton:checked').val();
//dostuff
}
This way, you can have labels on your buttons, and can have multiple radio button lists on the same page that do different things. You can even have each individual button in the same list do different things by setting up different behavior in SetShape() based on the button's value.
As far as find BlueBearr response the best (while I,m running my batch script with eg. SYSTEM rights) I have to add something to it. Because in my Windows language version (Polish) line that is to be catched by "%%a %%b"=="User Name:" gets REALLY COMPLICATED (it contains some diacritic characters in my language) I skip first 7 lines and operate on the 8th.
@for /f "SKIP= 7 TOKENS=3,4 DELIMS=\ " %%G in ('tasklist /FI "IMAGENAME eq explorer.exe" /FO LIST /V') do @IF %%G==%COMPUTERNAME% set _currdomain_user=%%H
Very simple , using Alt fragment
Lets take an example of sequence diagram for an ATM machine.Let's say here you want
IF card inserted is valid then prompt "Enter Pin"....ELSE prompt "Invalid Pin"
Then here is the sequence diagram for the same
Hope this helps!
If you want to add double quotes in HTML
echo "<p>Congratulations, “ ". $variable ." ”!</p>";
output -> Congratulations, "Mr Jonh "!
In Ubuntu if you execute the script with sh scriptname.sh
you get this problem.
Try executing the script with ./scriptname.sh
instead.
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
So you can use:
myvar = getURLParameter('myvar');
There are two Things you can do
use
int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();
or
int noOfColumns = sh.getRow(0).getLastCellNum();
There is a fine difference between them
I think you can just do
std::string s( MyVector.begin(), MyVector.end() );
where MyVector is your std::vector.
That's simple, in Java
your_component.setRotation(15);
or
your_component.setRotation(295.18f);
in XML
<Button android:rotation="15" />
ObjectID
s are objects so if you just compare them with ==
you're comparing their references. If you want to compare their values you need to use the ObjectID.equals
method:
if (results.userId.equals(AnotherMongoDocument._id)) {
...
}
Make sure enable this settings from iOS 9:
App Transport Security Settings in Info.plist to ensure loading image from URL so that it will allow download image and set it.
And write this code:
NSURL *url = [[NSURL alloc]initWithString:@"http://feelgrafix.com/data/images/images-1.jpg"];
NSData *data =[NSData dataWithContentsOfURL:url];
quickViewImage.image = [UIImage imageWithData:data];
With permission:
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9875432100"));
if (ActivityCompat.checkSelfPermission(yourActivity.this,android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(yourActivity.this,
android.Manifest.permission.CALL_PHONE)) {
} else {
ActivityCompat.requestPermissions(yourActivity.this,
new String[]{android.Manifest.permission.CALL_PHONE},
MY_PERMISSIONS_REQUEST_CALL_PHONE);
}
}
startActivity(callIntent);
One cheeky solution :
function printDiv(divID) {
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divElements + "</body>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}
HTML :
<form id="form1" runat="server">
<div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
Print me I am in 1st Div
</div>
<div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
I am not going to print
</div>
<input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>
Maybe (from git commit
man page):
git commit --no-verify
-n
--no-verify
This option bypasses the pre-commit and commit-msg hooks. See also githooks(5).
As commented by Blaise, -n
can have a different role for certain commands.
For instance, git push -n
is actually a dry-run push.
Only git push --no-verify
would skip the hook.
Note: Git 2.14.x/2.15 improves the --no-verify behavior:
See commit 680ee55 (14 Aug 2017) by Kevin Willford (``).
(Merged by Junio C Hamano -- gitster
-- in commit c3e034f, 23 Aug 2017)
commit
: skip discarding the index if there is nopre-commit
hook"
git commit
" used to discard the index and re-read from the filesystem just in case thepre-commit
hook has updated it in the middle; this has been optimized out when we know we do not run thepre-commit
hook.
Davi Lima points out in the comments the git cherry-pick
does not support --no-verify.
So if a cherry-pick triggers a pre-commit hook, you might, as in this blog post, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.
The same process would be necessary in case of a git rebase --continue
, after a merge conflict resolution.
In my case the problem was solved by appending the string cordova.system.library.2=com.android.support:support-v4:+
to platforms/android/project.properties
file
numpy.linspace()
gives you a one-dimensional NumPy array. For example:
>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
Therefore:
for index,point in my_array
cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:
>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])
Now you can do this:
>>> for x, y in two_d:
print(x, y)
1 2
4 5
you can also add inline css for adding image as a background as per below example
<div class="item active" style="background-image: url(../../foo.png);">
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}});
As @Ofer said, when you are using another libraries or modules, you should import all of them inside the if __name__ == '__main__':
So, in my case, ended like this:
if __name__ == '__main__':
import librosa
import os
import pandas as pd
run_my_program()
No! It's not a joke.
Take a look here: http://msdn.microsoft.com/en-us/library/ms186939.aspx
Character data types that are either fixed-length, nchar, or variable-length, nvarchar, Unicode data and use the UNICODE UCS-2 character set.
And also here: http://en.wikipedia.org/wiki/UTF-16
The older UCS-2 (2-byte Universal Character Set) is a similar character encoding that was superseded by UTF-16 in version 2.0 of the Unicode standard in July 1996.
To Validate Text Box Accept Ascii Only use this Pattern
[\x00-\x7F]+
For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):
To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is
${basedir}/src/test/resources
. At this point you would have a project directory structure that would look like the following:my-app |-- pom.xml `-- src |-- main | |-- java | | `-- com | | `-- mycompany | | `-- app | | `-- App.java | `-- resources | `-- META-INF | |-- application.properties `-- test |-- java | `-- com | `-- mycompany | `-- app | `-- AppTest.java `-- resources `-- test.properties
In a unit test you could use a simple snippet of code like the following to access the resource required for testing:
... // Retrieve resource InputStream is = getClass().getResourceAsStream("/test.properties" ); // Do something with the resource ...
You should start by defining what a tree is (for the domain), this is best done by defining the interface first. Not all trees structures are modifyable, being able to add and remove nodes should be an optional feature, so we make an extra interface for that.
There's no need to create node objects which hold the values, in fact I see this as a major design flaw and overhead in most tree implementations. If you look at Swing, the TreeModel
is free of node classes (only DefaultTreeModel
makes use of TreeNode
), as they are not really needed.
public interface Tree <N extends Serializable> extends Serializable {
List<N> getRoots ();
N getParent (N node);
List<N> getChildren (N node);
}
Mutable tree structure (allows to add and remove nodes):
public interface MutableTree <N extends Serializable> extends Tree<N> {
boolean add (N parent, N node);
boolean remove (N node, boolean cascade);
}
Given these interfaces, code that uses trees doesn't have to care much about how the tree is implemented. This allows you to use generic implementations as well as specialized ones, where you realize the tree by delegating functions to another API.
Example: file tree structure
public class FileTree implements Tree<File> {
@Override
public List<File> getRoots() {
return Arrays.stream(File.listRoots()).collect(Collectors.toList());
}
@Override
public File getParent(File node) {
return node.getParentFile();
}
@Override
public List<File> getChildren(File node) {
if (node.isDirectory()) {
File[] children = node.listFiles();
if (children != null) {
return Arrays.stream(children).collect(Collectors.toList());
}
}
return Collections.emptyList();
}
}
Example: generic tree structure (based on parent/child relations):
public class MappedTreeStructure<N extends Serializable> implements MutableTree<N> {
public static void main(String[] args) {
MutableTree<String> tree = new MappedTreeStructure<>();
tree.add("A", "B");
tree.add("A", "C");
tree.add("C", "D");
tree.add("E", "A");
System.out.println(tree);
}
private final Map<N, N> nodeParent = new HashMap<>();
private final LinkedHashSet<N> nodeList = new LinkedHashSet<>();
private void checkNotNull(N node, String parameterName) {
if (node == null)
throw new IllegalArgumentException(parameterName + " must not be null");
}
@Override
public boolean add(N parent, N node) {
checkNotNull(parent, "parent");
checkNotNull(node, "node");
// check for cycles
N current = parent;
do {
if (node.equals(current)) {
throw new IllegalArgumentException(" node must not be the same or an ancestor of the parent");
}
} while ((current = getParent(current)) != null);
boolean added = nodeList.add(node);
nodeList.add(parent);
nodeParent.put(node, parent);
return added;
}
@Override
public boolean remove(N node, boolean cascade) {
checkNotNull(node, "node");
if (!nodeList.contains(node)) {
return false;
}
if (cascade) {
for (N child : getChildren(node)) {
remove(child, true);
}
} else {
for (N child : getChildren(node)) {
nodeParent.remove(child);
}
}
nodeList.remove(node);
return true;
}
@Override
public List<N> getRoots() {
return getChildren(null);
}
@Override
public N getParent(N node) {
checkNotNull(node, "node");
return nodeParent.get(node);
}
@Override
public List<N> getChildren(N node) {
List<N> children = new LinkedList<>();
for (N n : nodeList) {
N parent = nodeParent.get(n);
if (node == null && parent == null) {
children.add(n);
} else if (node != null && parent != null && parent.equals(node)) {
children.add(n);
}
}
return children;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
dumpNodeStructure(builder, null, "- ");
return builder.toString();
}
private void dumpNodeStructure(StringBuilder builder, N node, String prefix) {
if (node != null) {
builder.append(prefix);
builder.append(node.toString());
builder.append('\n');
prefix = " " + prefix;
}
for (N child : getChildren(node)) {
dumpNodeStructure(builder, child, prefix);
}
}
}
The best way I see is to use live() or delegate() to capture the event in a parent and not in each child element.
If your button is inside a #parent element, you can replace:
$('#myButton').bind('click', onButtonClicked);
by
$('#parent').delegate('#myButton', 'click', onButtonClicked);
even if #myButton doesn't exist yet when this code is executed.
To count unique non-integers - similar to Eelco Hoogendoorn's answer but considerably faster (factor of 5 on my machine), I used weave.inline
to combine numpy.unique
with a bit of c-code;
import numpy as np
from scipy import weave
def count_unique(datain):
"""
Similar to numpy.unique function for returning unique members of
data, but also returns their counts
"""
data = np.sort(datain)
uniq = np.unique(data)
nums = np.zeros(uniq.shape, dtype='int')
code="""
int i,count,j;
j=0;
count=0;
for(i=1; i<Ndata[0]; i++){
count++;
if(data(i) > data(i-1)){
nums(j) = count;
count = 0;
j++;
}
}
// Handle last value
nums(j) = count+1;
"""
weave.inline(code,
['data', 'nums'],
extra_compile_args=['-O2'],
type_converters=weave.converters.blitz)
return uniq, nums
Profile info
> %timeit count_unique(data)
> 10000 loops, best of 3: 55.1 µs per loop
Eelco's pure numpy
version:
> %timeit unique_count(data)
> 1000 loops, best of 3: 284 µs per loop
Note
There's redundancy here (unique
performs a sort also), meaning that the code could probably be further optimized by putting the unique
functionality inside the c-code loop.
import 'package:intl/intl.dart';
main() {
var formattedDate = new DateTime.Format('yyyy-MM-dd').DateTime.now();
print(formattedDate); // something like 2020-04-16
}
For more details can refer DateFormat Documentation
As I happened to be poorly satisfied by dos2unix, I rolled out my own simple utility. Apart of a few advantages in speed and predictability, the syntax is also a bit simpler :
endlines unix *
And if you want it to go down into subdirectories (skipping hidden dirs and non-text files) :
endlines unix -r .
endlines
is available here https://github.com/mdolidon/endlines
There is _tkinter and Tkinter - both work on Py 3.x But to be safe- Download Loopy and change your python root directory(if you're using an IDE like PyCharms) to Loopy's installation directory. You'll get this library and many more.
Opera also has some support.
Generally however, it is too early to test out. You'll probably have to wait a year or 2 before any browser will have enough realistic support to test against.
EDIT Wikipedia has a good article on how much of HTML 5 various layout engines have implemented. It includes specific aspects of HTML 5.
you can do try lodash
Example code for json object:
var user = {'user':'barney','age':36};
user["newKey"] = true;
console.log(user);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>
_x000D_
for json array elements
Example code:
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
users.map(i=>{i["newKey"] = true});
console.log(users);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>
_x000D_
try this. m = row, n = col
vector<vector<int>> matrix(m, vector<int>(n));
for(i = 0;i < m; i++)
{
for(j = 0; j < n; j++)
{
cin >> matrix[i][j];
}
cout << endl;
}
cout << "::matrix::" << endl;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
If you want a simple one-line solution that doesn't involve exception handling, conditional statements or a requirement of Django 1.6+, do this instead:
x = next(iter(SomeModel.objects.filter(foo='bar')), None)
unchecked the "Automatically detect settings" in the Local Area Network Settings (found in "Internet Options" > Connections > LAN Settings.
To select data in numerical range you can use BETWEEN
which is inclusive.
SELECT JOB FROM MYTABLE WHERE ID BETWEEN 10 AND 15;
Recursion is the process where a method call iself to be able to perform a certain task. It reduces redundency of code. Most recurssive functions or methods must have a condifiton to break the recussive call i.e. stop it from calling itself if a condition is met - this prevents the creating of an infinite loop. Not all functions are suited to be used recursively.
I got this error without any use of base64. So i got a solution that error is in localhost it works fine on 127.0.0.1
Yes, for react,
for
becomes htmlFor
class
becomes className
etc.
see full list of how HTML attributes are changed here:
First of all, you are in a bad position now - having the task of writing tests for the code you did not originally create and without any changes - nightmare! Talk to your boss and explain, it is not possible to test the code without making it "testable". To make code testable you usually do some important changes;
Regarding private variables. You actually never should do that. Aiming to test private variables is the first sign that something wrong with the current design. Private variables are part of the implementation, tests should focus on behavior rather of implementation details.
Sometimes, private field are exposed to public access with some getter. I do that, but try to avoid as much as possible (mark in comments, like 'used for testing').
Since you have no possibility to change the code, I don't see possibility (I mean real possibility, not like Reflection hacks etc.) to check private variable.
In addition to @chanafdo answer, you can use route name
<a href="{{route('login')}}">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="{{route('profile', ['id' => 1])}}">login here</a>
<a href="<?php echo route('login')?>">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="<?php echo route('profile', ['id' => 1])?>">login here</a>
As of laravel 5.2 you can use @php @endphp
to create as <?php ?>
in laravel blade.
Using blade your personal opinion but I suggest to use it. Learn it.
It has many wonderful features as template inheritance, Components & Slots,subviews etc...
While the approach with having a AppSettings class with a string constant as ApiEndpoint works, it is not ideal since we wouldn't be able to swap this real ApiEndpoint for some other values at the time of unit testing.
We need to be able to inject this api endpoints into our services (think of injecting a service into another service). We also do not need to create a whole class for this, all we want to do is to inject a string into our services being our ApiEndpoint. To complete the excellent answer by pixelbits, here is the complete code as to how it can be done in Angular 2:
First we need to tell Angular how to provide an instance of our ApiEndpoint when we ask for it in our app (think of it as registering a dependency):
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide('ApiEndpoint', {useValue: 'http://127.0.0.1:6666/api/'})
]);
And then in the service we inject this ApiEndpoint into the service constructor and Angular will provide it for us based on our registration above:
import {Http} from 'angular2/http';
import {Message} from '../models/message';
import {Injectable, Inject} from 'angular2/core'; // * We import Inject here
import {Observable} from 'rxjs/Observable';
import {AppSettings} from '../appSettings';
import 'rxjs/add/operator/map';
@Injectable()
export class MessageService {
constructor(private http: Http,
@Inject('ApiEndpoint') private apiEndpoint: string) { }
getMessages(): Observable<Message[]> {
return this.http.get(`${this.apiEndpoint}/messages`)
.map(response => response.json())
.map((messages: Object[]) => {
return messages.map(message => this.parseData(message));
});
}
// the rest of the code...
}
I have a similar problem in MVC4 using forms authentication. The problem was this line in the web.config,
<modules runAllManagedModulesForAllRequests="true">
This means that every request, including those for static content, being authenticated.
Change this line to:
<modules runAllManagedModulesForAllRequests="false">
Use the package plyr with lapply to get frequencies for every value (level) and every variable (factor) in your data frame.
library(plyr)
lapply(df, count)
You can execute a function defined in a DLL file by using the rundll command. You can explore the functions available by using Dependency Walker.
By default, all paths you define will be relative. The question is: relative to what? There are several options:
Please note that following a macro such as $(SolutionDir) there is no need to add a backward slash "\". Just use $(SolutionDir)mylibdir\mylib.lib. In case you just can't get it to work, open the project file externally from Notepad and check it.
Use the $_SERVER['HTTP_REFERER']
header, but bear in mind anybody can spoof it at anytime regardless of whether they clicked on a link.
This is how we can join two Dataframes on same column names in PySpark.
df = df1.join(df2, ['col1','col2','col3'])
If you do printSchema()
after this then you can see that duplicate columns have been removed.
So before I found this post, I successfully found this to work.
Model._meta.fields
It works equally as
Model._meta.get_fields()
I'm not sure what the difference is in the results, if there is one. I ran this loop and got the same output.
for field in Model._meta.fields:
print(field.name)
I was getting this error even when all the relevant dependencies were in place because I hadn't created the schema in MySQL.
I thought it would be created automatically but it wasn't. Although the table itself will be created, you have to create the schema.
My version was a combination of accepted and most upvoted answers. But it's a little bit different, because everyone uses SHA1 but nobody tells you how to get it
$ git init
$ git remote add <remote_url>
$ git fetch --all
now you can see all branches & commits
$ git branch -a
$ git log remotes/origin/master <-- or any other branch
Finally you know SHA1 of desired commit
git reset --hard <sha1>
That is interesting subject.
You can play around with two lifecycle hooks to figure out how it works: ngOnChanges
and ngOnInit
.
Basically when you set default value to Input
that's mean it will be used only in case there will be no value coming on that component.
And the interesting part it will be changed before component will be initialized.
Let's say we have such components with two lifecycle hooks and one property coming from input
.
@Component({
selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
@Input() property: string = 'default';
ngOnChanges(changes) {
console.log('Changed', changes.property.currentValue, changes.property.previousValue);
}
ngOnInit() {
console.log('Init', this.property);
}
}
Situation 1
Component included in html without defined property
value
As result we will see in console:
Init default
That's mean onChange
was not triggered. Init was triggered and property
value is default
as expected.
Situation 2
Component included in html with setted property <cmp [property]="'new value'"></cmp>
As result we will see in console:
Changed
new value
Object {}
Init
new value
And this one is interesting. Firstly was triggered onChange
hook, which setted property
to new value
, and previous value was empty object! And only after that onInit
hook was triggered with new value of property
.
All I needed was this :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
try {
String d = sdf.format(new Date());
System.out.println(d);
System.out.println(sdfLocal.parse(d));
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Output : slightly dubious, but I want only the date to be consistent
2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013
One liner:
string.Join(",", from SqlParameter p in cmd.Parameters select p.ToString())
This can also be caused if the application was built from different PCs. You can make it easier for your whole team if you copy a debug.keystore
from someone's machine into a /cert
folder at the top of your project and then add a signingConfigs
section to your app/build.gradle
:
signingConfigs {
debug {
storeFile file("cert/debug.keystore")
}
}
Then tell your debug build how to sign the application:
buildTypes {
debug {
// Other values
signingConfig signingConfigs.debug
}
}
Check this file into source control. This will allow for the seamless install/upgrade process across your entire development team and will make your project resilient against future machine upgrades too.
I think the annotation you are looking for is:
public class CompanyName implements Serializable {
//...
@JoinColumn(name = "COMPANY_ID", referencedColumnName = "COMPANY_ID", insertable = false, updatable = false)
private Company company;
And you should be able to use similar mappings in a hbm.xml as shown here (in 23.4.2):
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-mappings.html
Ignoring checking is a bad idea as it makes you susceptible to Man-in-the-middle attacks.
I took the freedom to improve nikobelia's answer by only adding each machine's key once and actually setting ok/changed status in Ansible:
- name: Accept EC2 SSH host keys
connection: local
become: false
shell: |
ssh-keygen -F {{ inventory_hostname }} ||
ssh-keyscan -H {{ inventory_hostname }} >> ~/.ssh/known_hosts
register: known_hosts_script
changed_when: "'found' not in known_hosts_script.stdout"
However, Ansible starts gathering facts before the script runs, which requires an SSH connection, so we have to either disable this task or manually move it to later:
- name: Example play
hosts: all
gather_facts: no # gather facts AFTER the host key has been accepted instead
tasks:
# https://stackoverflow.com/questions/32297456/
- name: Accept EC2 SSH host keys
connection: local
become: false
shell: |
ssh-keygen -F {{ inventory_hostname }} ||
ssh-keyscan -H {{ inventory_hostname }} >> ~/.ssh/known_hosts
register: known_hosts_script
changed_when: "'found' not in known_hosts_script.stdout"
- name: Gathering Facts
setup:
One kink I haven't been able to work out is that it marks all as changed even if it only adds a single key. If anyone could contribute a fix that would be great!
There is no button type cancel https://www.w3schools.com/jsref/prop_pushbutton_type.asp
To achieve cancel functionality I used DOM history
<button type="button" class="btn btn-primary" onclick="window.history.back();">Cancel</button>
_x000D_
For more details : https://www.w3schools.com/jsref/met_his_back.asp
An idempotent operation is an operation, action, or request that can be applied multiple times without changing the result, i.e. the state of the system, beyond the initial application.
EXAMPLES (WEB APP CONTEXT):
IDEMPOTENT: Making multiple identical requests has the same effect as making a single request. A message in an email messaging system is opened and marked as "opened" in the database. One can open the message many times but this repeated action will only ever result in that message being in the "opened" state. This is an idempotent operation. The first time one PUTs an update to a resource using information that does not match the resource (the state of the system), the state of the system will change as the resource is updated. If one PUTs the same update to a resource repeatedly then the information in the update will match the information already in the system upon every PUT, and no change to the state of the system will occur. Repeated PUTs with the same information are idempotent: the first PUT may change the state of the system, subsequent PUTs should not.
NON-IDEMPOTENT: If an operation always causes a change in state, like POSTing the same message to a user over and over, resulting in a new message sent and stored in the database every time, we say that the operation is NON-IDEMPOTENT.
NULLIPOTENT: If an operation has no side effects, like purely displaying information on a web page without any change in a database (in other words you are only reading the database), we say the operation is NULLIPOTENT. All GETs should be nullipotent.
When talking about the state of the system we are obviously ignoring hopefully harmless and inevitable effects like logging and diagnostics.
str.replace(/[[\]]/g,'')
I have a wrapper script called provision forces you to choose the target, so I don't have to handle it elsewhere.
For those that are curious, I use ENV vars for options that my vagrantfile uses (adding the corresponding ansible arg for cloud systems) and let the rest of the ansible args pass through. Where I am creating and provisioning more than 10 servers at a time I include an auto retry on failed servers (as long as progress is being made - I found when creating 100 or so servers at a time often a few would fail the first time around).
echo 'Usage: [VAR=value] bin/provision [options] dev|all|TARGET|vagrant'
echo ' bootstrap - Bootstrap servers ssh port and initial security provisioning'
echo ' dev - Provision localhost for development and control'
echo ' TARGET - specify specific host or group of hosts'
echo ' all - provision all servers'
echo ' vagrant - Provision local vagrant machine (environment vars only)'
echo
echo 'Environment VARS'
echo ' BOOTSTRAP - use cloud providers default user settings if set'
echo ' TAGS - if TAGS env variable is set, then only tasks with these tags are run'
echo ' SKIP_TAGS - only run plays and tasks whose tags do not match these values'
echo ' START_AT_TASK - start the playbook at the task matching this name'
echo
ansible-playbook --help | sed -e '1d
s#=/etc/ansible/hosts# set by bin/provision argument#
/-k/s/$/ (use for fresh systems)/
/--tags/s/$/ (use TAGS var instead)/
/--skip-tags/s/$/ (use SKIP_TAGS var instead)/
/--start-at-task/s/$/ (use START_AT_TASK var instead)/
'
You can strip non-digits and do a comparison. Here's a demo script:
for num in "44" "-44" "44-" "4-4" "a4" "4a" ".4" "4.4" "-4.4" "09"
do
match=${num//[^[:digit:]]} # strip non-digits
match=${match#0*} # strip leading zeros
echo -en "$num\t$match\t"
case $num in
$match|-$match) echo "Integer";;
*) echo "Not integer";;
esac
done
This is what the test output looks like:
44 44 Integer -44 44 Integer 44- 44 Not integer 4-4 44 Not integer a4 4 Not integer 4a 4 Not integer .4 4 Not integer 4.4 44 Not integer -4.4 44 Not integer 09 9 Not integer
Try StickyList
from Cactoos:
List<String> list = new StickyList<>(iterable);
Disclaimer: I'm one of the developers.
Code :
var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie =
'username=' + value +
'; expires=' + now.toUTCString() +
'; path=/';
Middleware is a general term for software that serves to "glue together" so app.use is a method to configure the middleware, for example: to parse and handle the body of request: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); there are many middlewares you can use in your express application just read the doc : http://expressjs.com/en/guide/using-middleware.html
You can't have a <button>
inside an <a>
element. As W3's content model description for the <a>
element states:
"there must be no interactive content descendant."
(a <button>
is considered interactive content)
To get the effect you're looking for, you can ditch the <a>
tags and add a simple event handler to each button which navigates the browser to the desired location, e.g.
<input type="button" value="stackoverflow.com" onClick="javascript:location.href = 'http://stackoverflow.com';" />
Please consider not doing this, however; there's a reason regular links work as they do:
You also add a completely unnecessary requirement to have JavaScript enabled just to perform a basic navigation; this is such a fundamental aspect of the web that I would consider such a dependency as unacceptable.
You can style your links, if desired, using a background image or background color, border and other techniques, so that they look like buttons, but under the covers, they should be ordinary links.
Use <meta charset="utf-8" />
for web browsers when using HTML5.
Use <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
when using HTML4 or XHTML, or for outdated dom parsers, like DOMDocument
in php 5.3
The default display style for a div is "block." This means that each new div will be under the prior one.
You can:
Override the flow style by using float as @Sarfraz suggests.
or
Change your html to use something other than divs for elements you want on the same line. I suggest that you just leave out the divs for the "last_name" field
<form action="/users" method="post"><div style="margin:0;padding:0">
<div>
<label for="username">First Name</label>
<input id="user_first_name" name="user[first_name]" size="30" type="text" />
<label for="name">Last Name</label>
<input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>
... rest is same
sys.exit()
raises a SystemExit
exception which you are probably assuming as some error. If you want your program not to raise SystemExit but return gracefully, you can wrap your functionality in a function and return from places you are planning to use sys.exit
Maybe :active
over :focus
with :hover
will help!
Try
button {
background:lime;
}
button:hover {
background:green;
}
button:focus {
background:gray;
}
button:active {
background:red;
}
Then:
<button onkeydown="alerted_of_key_pressed()" id="button" title="Test button" href="#button">Demo</button>
Then:
<!--JAVASCRIPT-->
<script>
function alerted_of_key_pressed() { alert("You pressed a key when hovering over this button.") }
</script>
Sorry about that last one. :) I was just showing you a cool function! Wait... did I just emphasize a code block? This is cool!!!
There is a quirk with this that might be relevant for some people... From the PHP docs comments.
If you want cURL to timeout in less than one second, you can use
CURLOPT_TIMEOUT_MS
, although there is a bug/"feature" on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached". The explanation for this behavior is:"If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolution for timeouts with a minimum timeout allowed of one second."
What this means to PHP developers is "You can't use this function without testing it first, because you can't tell if libcurl is using the standard system name resolver (but you can be pretty sure it is)"
The problem is that on (Li|U)nix, when libcurl uses the standard name resolver, a SIGALRM is raised during name resolution which libcurl thinks is the timeout alarm.
The solution is to disable signals using CURLOPT_NOSIGNAL. Here's an example script that requests itself causing a 10-second delay so you can test timeouts:
if (!isset($_GET['foo'])) {
// Client
$ch = curl_init('http://localhost/test/test_timeout.php?foo=bar');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
$data = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_errno > 0) {
echo "cURL Error ($curl_errno): $curl_error\n";
} else {
echo "Data received: $data\n";
}
} else {
// Server
sleep(10);
echo "Done.";
}
From http://www.php.net/manual/en/function.curl-setopt.php#104597
Very short answer :
Different databases have different uses. I'm not a database expert. Rule of thumb:
Short answer:
Let's consider two example scenarios:
Scenario 1:
You are building an online store/website, and you want to be able to:
You want to be able to find data for a particular user, change its name... basically perform INSERT, UPDATE, DELETE operations on user data. Same with products, etc.
You want to be able to make transactions, possibly involving a user buying a product (that's a relation). Then OLTP is probably a good fit.
Scenario 2:
You have an online store/website, and you want to compute things like
This falls into the analytics/business intelligence domain, and therefore OLAP is probably more suited.
If you think in terms of "It would be nice to know how/what/how much"..., and that involves all "objects" of one or more kind (ex. all the users and most of the products to know the total spent) then OLAP is probably better suited.
Longer answer:
Of course things are not so simple. That's why we have to use short tags like OLTP
and OLAP
in the first place. Each database should be evaluated independently in the end.
So what could be the fundamental difference between OLAP and OLTP?
Well, databases have to store data somewhere. It shouldn't be surprising that the way the data is stored heavily reflects the possible use of said data. Data is usually stored on a hard drive. Let's think of a hard drive as a really wide sheet of paper, where we can read and write things. There are two ways to organize our reads and writes so that they can be efficient and fast.
One way is to make a book that is a bit like a phone book. On each page of the book, we store the information regarding a particular user. Now that's nice, we can find the information for a particular user very easily! Just jump to the page! We can even have a special page at the beginning to tell us on which page the users are if we want. But on the other hand, if we want to find, say, how much money all of our users spent then we would have to read every page, i.e. the whole book! That would be a row-based book/database (OLTP). The optional page at the beginning would be the index.
Another way to use our big sheet of paper is to make an accounting book. I'm no accountant, but let's imagine that we would have a page for "expenditures", "purchases"... That's nice because now we can query things like "give me the total revenue" very quickly (just read the "purchases" page). We can also ask for more involved things like "give me the top ten products sold" and still have acceptable performance. But now consider how painful it would be to find the expenditures for a particular user. You would have to go through the whole list of everyone's expenditures and filter the ones of that particular user, then sum them. Which basically amounts to "read the whole book" again. That would be a column-based database (OLAP).
It follows that:
OLTP
databases are meant to be used to do many small transactions, and usually serve as a "single source of truth".
OLAP
databases on the other hand are more suited for analytics, data mining, fewer queries but they are usually bigger (they operate on more data).
It's a bit more involved than that of course and that's a 20 000 feet overview of how databases differ, but it allows me not to get lost in a sea of acronyms.
Speaking of acronyms:
To read a bit further, here are some relevant links which heavily inspired my answer:
You will need to get the textbox via javascript when moving the mouse over it and change its type
to text
. And when moving it out, you will want to change it back to password
. No chance of doing this in pure CSS.
HTML:
<input type="password" name="password" id="myPassword" size="30" />
<img src="theicon" onmouseover="mouseoverPass();" onmouseout="mouseoutPass();" />
JS:
function mouseoverPass(obj) {
var obj = document.getElementById('myPassword');
obj.type = "text";
}
function mouseoutPass(obj) {
var obj = document.getElementById('myPassword');
obj.type = "password";
}
The best solution probably is to name things instead of returning meaningless tuples (unless there is some logic behind the order of the returned items). You can for example use a dictionary:
def func():
return {'lat': 1, 'lng': 2}
latitude = func()['lat']
You could even use namedtuple if you want to add extra information about what you are returning (it's not just a dictionary, it's a pair of coordinates):
from collections import namedtuple
Coordinates = namedtuple('Coordinates', ['lat', 'lng'])
def func():
return Coordinates(lat=1, lng=2)
latitude = func().lat
If the objects within your dictionary/tuple are strongly tied together then it may be a good idea to even define a class for it. That way you'll also be able to define more complex operations. A natural question that follows is: When should I be using classes in Python?
Most recent versions of python (= 3.7) have dataclasses which you can use to define classes with very few lines of code:
from dataclasses import dataclass
@dataclass
class Coordinates:
lat: float = 0
lng: float = 0
def func():
return Coordinates(lat=1, lng=2)
latitude = func().lat
The primary advantage of dataclasses over namedtuple is that its easier to extend, but there are other differences. Note that by default, dataclasses are mutable, but you can use @dataclass(frozen=True)
instead of @dataclass
to force them being immutable.
With C99 the %j
length modifier can also be used with the printf family of functions to print values of type int64_t
and uint64_t
:
#include <stdio.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
int64_t a = 1LL << 63;
uint64_t b = 1ULL << 63;
printf("a=%jd (0x%jx)\n", a, a);
printf("b=%ju (0x%jx)\n", b, b);
return 0;
}
Compiling this code with gcc -Wall -pedantic -std=c99
produces no warnings, and the program prints the expected output:
a=-9223372036854775808 (0x8000000000000000)
b=9223372036854775808 (0x8000000000000000)
This is according to printf(3)
on my Linux system (the man page specifically says that j
is used to indicate a conversion to an intmax_t
or uintmax_t
; in my stdint.h, both int64_t
and intmax_t
are typedef'd in exactly the same way, and similarly for uint64_t
). I'm not sure if this is perfectly portable to other systems.
For those browsers that do support "position: fixed" you can simply use javascript (jQuery) to change the position to "fixed" when scrolling. This eliminates the jumpiness when scrolling with the $(window).scroll(function()) solutions listed here.
Ben Nadel demonstrates this in his tutorial: Creating A Sometimes-Fixed-Position Element With jQuery
I finally solved the problem!!! You should first set the jre path to system variables by navigating to::
control panel > System and Security > System > Advanced system settings
Under System variables click on new
Variable name: KEY_PATH
Variable value: C:\Program Files (x86)\Java\jre1.8.0_171\bin
Where Variable value should be the path to your JDK's bin folder.
Then open command prompt and Change directory to the same JDK's bin folder like this
C:\Program Files (x86)\Java\jre1.8.0_171\bin
then paste,
keytool -list -v -keystore "C:\Users\user\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
NOTE: People are confusing jre and jdk. All I did applied strictly to jre
From SQLServer 2012 more elegant alter role:
use mydb
go
ALTER ROLE db_datareader
ADD MEMBER MYUSER
go
ALTER ROLE db_datawriter
ADD MEMBER MYUSER
go
Parallel.ForEach
requires a list of user-defined workers and a non-async Action
to perform with each worker.
Task.WaitAll
and Task.WhenAll
require a List<Task>
, which are by definition asynchronous.
I found RiaanDP's response very useful to understand the difference, but it needs a correction for Parallel.ForEach
. Not enough reputation to respond to his comment, thus my own response.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncTest
{
class Program
{
class Worker
{
public int Id;
public int SleepTimeout;
public void DoWork(DateTime testStart)
{
var workerStart = DateTime.Now;
Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
Thread.Sleep(SleepTimeout);
var workerEnd = DateTime.Now;
Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));
}
public async Task DoWorkAsync(DateTime testStart)
{
var workerStart = DateTime.Now;
Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
await Task.Run(() => Thread.Sleep(SleepTimeout));
var workerEnd = DateTime.Now;
Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));
}
}
static void Main(string[] args)
{
var workers = new List<Worker>
{
new Worker { Id = 1, SleepTimeout = 1000 },
new Worker { Id = 2, SleepTimeout = 2000 },
new Worker { Id = 3, SleepTimeout = 3000 },
new Worker { Id = 4, SleepTimeout = 4000 },
new Worker { Id = 5, SleepTimeout = 5000 },
};
var startTime = DateTime.Now;
Console.WriteLine("Starting test: Parallel.ForEach...");
PerformTest_ParallelForEach(workers, startTime);
var endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
startTime = DateTime.Now;
Console.WriteLine("Starting test: Task.WaitAll...");
PerformTest_TaskWaitAll(workers, startTime);
endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
startTime = DateTime.Now;
Console.WriteLine("Starting test: Task.WhenAll...");
var task = PerformTest_TaskWhenAll(workers, startTime);
task.Wait();
endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
Console.ReadKey();
}
static void PerformTest_ParallelForEach(List<Worker> workers, DateTime testStart)
{
Parallel.ForEach(workers, worker => worker.DoWork(testStart));
}
static void PerformTest_TaskWaitAll(List<Worker> workers, DateTime testStart)
{
Task.WaitAll(workers.Select(worker => worker.DoWorkAsync(testStart)).ToArray());
}
static Task PerformTest_TaskWhenAll(List<Worker> workers, DateTime testStart)
{
return Task.WhenAll(workers.Select(worker => worker.DoWorkAsync(testStart)));
}
}
}
The resulting output is below. Execution times are comparable. I ran this test while my computer was doing the weekly anti virus scan. Changing the order of the tests did change the execution times on them.
Starting test: Parallel.ForEach...
Worker 1 started on thread 9, beginning 0.02 seconds after test start.
Worker 2 started on thread 10, beginning 0.02 seconds after test start.
Worker 3 started on thread 11, beginning 0.02 seconds after test start.
Worker 4 started on thread 13, beginning 0.03 seconds after test start.
Worker 5 started on thread 14, beginning 0.03 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.02 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.02 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.03 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.03 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.03 seconds after the test start.
Test finished after 5.03 seconds.
Starting test: Task.WaitAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.01 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.01 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.01 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.01 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.01 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.
Starting test: Task.WhenAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.00 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.00 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.00 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.00 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.00 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.
If you just copy&paste the example URL that Google gives in their website http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false it will fail because of the wrong parameter of the sensor. You should change it to true or false and not the one that they wrote. Maybe is the error that you have had, like it happened to me...
In my case i used directive, but hadn't imported it in my module.ts file. Import fixed it.
In your code behind, set the window's DataContext to the dictionary. In your XAML, you can write:
<ListView ItemsSource="{Binding}" />
This will bind the ListView to the dictionary.
For more complex scenarios, this would be a subset of techniques behind the MVVM pattern.
I think you should add style="background:white;" to make looks like it is writable
<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly" style="background:white;"/>
Not sure if there's terrible reasons to do this or not, but it seems to work with me on the latest version of Chrome/Firefox without any visible performance problems with quite a lot of elements on the page.
*:not(:hover)>.parent-hover-show{
display:none;
}
But this way, all you need is to apply parent-hover-show
to an element and the rest is taken care of, and you can keep whatever default display type you want without it always being "block" or making multiple classes for each type.
Using the JSON.NET NuGet package and anonymous types, you can simplify what the other posters are suggesting:
// ...
string payload = JsonConvert.SerializeObject(new
{
agent = new
{
name = "Agent Name",
version = 1,
},
username = "username",
password = "password",
token = "xxxxx",
});
var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
// ...
Date input = new Date();
LocalDateTime conv=LocalDateTime.ofInstant(input.toInstant(), ZoneId.systemDefault());
LocalDate convDate=conv.toLocalDate();
The Date
instance does contain time too along with the date while LocalDate
doesn't. So you can firstly convert it into LocalDateTime
using its method ofInstant()
then if you want it without time then convert the instance into LocalDate
.
Don't forget that at a later date you can take an existing class, and make it implement IBox
, and it will then become available to all your box-aware code.
This becomes a bit clearer if interfaces are named -able. e.g.
public interface Saveable {
....
public interface Printable {
....
etc. (Naming schemes don't always work e.g. I'm not sure Boxable
is appropriate here)
Visual Studio 2015 doesn't install C++ by default. You have to rerun the setup, select Modify and then check Programming Language -> C++
String str = new String("SOME")
always create a new object on the heap
String str="SOME"
uses the String pool
Try this small example:
String s1 = new String("hello");
String s2 = "hello";
String s3 = "hello";
System.err.println(s1 == s2);
System.err.println(s2 == s3);
To avoid creating unnecesary objects on the heap use the second form.
$("input[attr]").length
might be a better option.
This worked for me:
step 1) Removing the interpreter, auto configuring it again
step 2) Window - Preferences - PyDev - Interpreters - Python Interpreter Go to the Forced builtins tab Click on New... Type the name of the module (curses in my case) and click OK
step 3) Right click in the project explorer on whichever module is giving errors. Go to PyDev->Code analysis.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/activity_register_header"
android:minHeight="50dp"
android:orientation="vertical"
android:visibility="gone" />
Try This Code
Visibility works fine in this code
$emit
It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope
listeners. The event life cycle starts at the scope on which $emit
was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.
$broadcast
It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope
listeners. The event life cycle starts at the scope on which $broadcast
was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.
$on
It listen on events of a given type. It can catch the event dispatched by $broadcast
and $emit
.
Visual demo:
Demo working code, visually showing scope tree (parent/child relationship):
http://plnkr.co/edit/am6IDw?p=preview
Demonstrates the method calls:
$scope.$on('eventEmitedName', function(event, data) ...
$scope.broadcastEvent
$scope.emitEvent
You need an external library for this.
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google GSON is one of such libraries
You can also take a look here for examples on converting Java object collection to JSON string.
Another simpler/lighter alternative to gnuplot is ervy, a NodeJS based terminal charts tool.
Supported types: scatter (XY points), bar, pie, bullet, donut and gauge.
Usage examples with various options can be found on the projects GitHub repo
Try this
var url = ApiUrl(`/customers`);
if(data){
url += '?search='+data;
}
else
{
url += `?page=${page}&per_page=${perpage}`;
}
console.log(url);
You can delete column like this:
df.drop("column Name).columns
In your case :
df.drop("id").columns
If you want to drop more than one column you can do:
dfWithLongColName.drop("ORIGIN_COUNTRY_NAME", "DEST_COUNTRY_NAME")
In Excel 2007, goto Insert/Shape and pick a shape. Colour it and enter whatever text you want. Then right click on the shape and insert a hyperlink
A few tips with shapes..
If you want to easily position the shape with cells, hold down Alt when you move the shape and it will lock to the cell. If you don't want the shape to move or resize with rows/columns, right click the shape, select size and properties and choose the setting which works best.
I spent hours on this and finally figured it out. This problem happens if service account your sender application is using differs from the service account your receiver is using.
You can find out your receiver service account via Firebase -> Project Overview -> Project Settings -> Service Accounts
and generate a new key and use that key when you are initializing your FirebaseApp
in the sender:
FileInputStream serviceAccount = new FileInputStream("YOUR_PATH_TO_GENERATED_KEY.json");
GoogleCredentials googleCredentials = GoogleCredentials.fromStream(serviceAccount);
FirebaseOptions options = new FirebaseOptions.Builder().setCredentials(googleCredentials).build();
firebaseApp = FirebaseApp.initializeApp(options);
This initialization need to be done once before you send push notifications.
In my case, I had done everything correctly and I still had this problem. I had made some changes in the "google-services.json" used in the receiver app and I noticed AndroidStudio was not using my new file. The solution was so simple:
AndroidStudio -> Build -> Clean Project
and Build -> Rebuild Project
You can try a Java Library. FileUtils, It has many functions that write to Files.
I don't think jQuery itself includes datetimepicker. You must use jQuery UI instead (src="jquery.ui").
Simple groovy way to check object type:
somObject in Date
Can be applied also to interfaces.
I use the following PowerShell snippet to get CPU usage for local or remote systems:
Get-Counter -ComputerName localhost '\Process(*)\% Processor Time' | Select-Object -ExpandProperty countersamples | Select-Object -Property instancename, cookedvalue| Sort-Object -Property cookedvalue -Descending| Select-Object -First 20| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100).toString('P')}} -AutoSize
Same script but formatted with line continuation:
Get-Counter -ComputerName localhost '\Process(*)\% Processor Time' `
| Select-Object -ExpandProperty countersamples `
| Select-Object -Property instancename, cookedvalue `
| Sort-Object -Property cookedvalue -Descending | Select-Object -First 20 `
| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100).toString('P')}} -AutoSize
On a 4 core system it will return results that look like this:
InstanceName CPU
------------ ---
_total 399.61 %
idle 314.75 %
system 26.23 %
services 24.69 %
setpoint 15.43 %
dwm 3.09 %
policy.client.invoker 3.09 %
imobilityservice 1.54 %
mcshield 1.54 %
hipsvc 1.54 %
svchost 1.54 %
stacsv64 1.54 %
wmiprvse 1.54 %
chrome 1.54 %
dbgsvc 1.54 %
sqlservr 0.00 %
wlidsvc 0.00 %
iastordatamgrsvc 0.00 %
intelmefwservice 0.00 %
lms 0.00 %
The ComputerName argument will accept a list of servers, so with a bit of extra formatting you can generate a list of top processes on each server. Something like:
$psstats = Get-Counter -ComputerName utdev1,utdev2,utdev3 '\Process(*)\% Processor Time' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty countersamples | %{New-Object PSObject -Property @{ComputerName=$_.Path.Split('\')[2];Process=$_.instancename;CPUPct=("{0,4:N0}%" -f $_.Cookedvalue);CookedValue=$_.CookedValue}} | ?{$_.CookedValue -gt 0}| Sort-Object @{E='ComputerName'; A=$true },@{E='CookedValue'; D=$true },@{E='Process'; A=$true }
$psstats | ft @{E={"{0,25}" -f $_.Process};L="ProcessName"},CPUPct -AutoSize -GroupBy ComputerName -HideTableHeaders
Which would result in a $psstats variable with the raw data and the following display:
ComputerName: utdev1
_total 397%
idle 358%
3mws 28%
webcrs 10%
ComputerName: utdev2
_total 400%
idle 248%
cpfs 42%
cpfs 36%
cpfs 34%
svchost 21%
services 19%
ComputerName: utdev3
_total 200%
idle 200%
If you are still having trouble and you are running something like EC2 AWS instance, it may just be a case of opening the port through the AWS console.
The onSaveInstanceState(bundle)
and onRestoreInstanceState(bundle)
methods are useful for data persistence merely while rotating the screen (orientation change).
They are not even good while switching between applications (since the onSaveInstanceState()
method is called but onCreate(bundle)
and onRestoreInstanceState(bundle)
is not invoked again.
For more persistence use shared preferences. read this article
Use the exp1 if cond else exp2
syntax.
rate = lambda T: 200*exp(-T) if T>200 else 400*exp(-T)
Note you don't use return
in lambda expressions.
1. install moment
npm install moment --save
2. test this code in your typescript file
import moment = require('moment');
console.log(moment().format('LLLL'));
With Bootstrap 3.2 you can wrap each iframe in the responsive-embed wrapper of your choice:
http://getbootstrap.com/components/#responsive-embed
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="…"></iframe>
</div>
<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
<iframe class="embed-responsive-item" src="…"></iframe>
</div>
If you don't want to wrap your iframes, you can use FluidVids https://github.com/toddmotto/fluidvids. See demo here: http://toddmotto.com/labs/fluidvids/
<!-- fluidvids.js -->
<script src="js/fluidvids.js"></script>
<script>
fluidvids.init({
selector: ['iframe'],
players: ['www.youtube.com', 'player.vimeo.com']
});
</script>
background.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:width="3dp"
android:color="#0FECFF" />
//specify gradient
<gradient
android:startColor="#ffffffff"
android:endColor="#110000FF"
android:angle="90"/>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical"
android:layout_marginBottom="10dp"
android:background="@drawable/background">
You could do this:
let thirtyMinutes = 30 * 60 * 1000; // convert 30 minutes to milliseconds_x000D_
let date1 = new Date();_x000D_
let date2 = new Date(date1.getTime() + thirtyMinutes);_x000D_
console.log(date1);_x000D_
console.log(date2);
_x000D_
The xlsxwriter
library is great for creating .xlsx
files. The following snippet generates an .xlsx
file from a list of dicts while stating the order and the displayed names:
from xlsxwriter import Workbook
def create_xlsx_file(file_path: str, headers: dict, items: list):
with Workbook(file_path) as workbook:
worksheet = workbook.add_worksheet()
worksheet.write_row(row=0, col=0, data=headers.values())
header_keys = list(headers.keys())
for index, item in enumerate(items):
row = map(lambda field_id: item.get(field_id, ''), header_keys)
worksheet.write_row(row=index + 1, col=0, data=row)
headers = {
'id': 'User Id',
'name': 'Full Name',
'rating': 'Rating',
}
items = [
{'id': 1, 'name': "Ilir Meta", 'rating': 0.06},
{'id': 2, 'name': "Abdelmadjid Tebboune", 'rating': 4.0},
{'id': 3, 'name': "Alexander Lukashenko", 'rating': 3.1},
{'id': 4, 'name': "Miguel Díaz-Canel", 'rating': 0.32}
]
create_xlsx_file("my-xlsx-file.xlsx", headers, items)
Note 1 - I'm purposely not answering to the exact case the OP presented. Instead, I'm presenting a more generic solution IMHO most visitors seek. This question's title is well-indexed in search engines and tracks lots of traffic
Note 2 - If you're not using Python3.6 or newer, consider using
OrderedDict
inheaders
. Before Python3.6 the order indict
was not preserved.
Based on your requirement i think you are wanted to put dynamic fields in CSS file, however that is not possible as CSS is a static language. However you can simulate the behaviour by using Angular.
Please refer to the below example. I'm here showing only one component.
login.component.html
import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
cssProperty:any;
constructor(private sanitizer: DomSanitizer) {
console.log(window.innerWidth);
console.log(window.innerHeight);
this.cssProperty = 'position:fixed;top:' + Math.floor(window.innerHeight/3.5) + 'px;left:' + Math.floor(window.innerWidth/3) + 'px;';
this.cssProperty = this.sanitizer.bypassSecurityTrustStyle(this.cssProperty);
}
ngOnInit() {
}
}
login.component.ts
<div class="home">
<div class="container" [style]="cssProperty">
<div class="card">
<div class="card-header">Login</div>
<div class="card-body">Please login</div>
<div class="card-footer">Login</div>
</div>
</div>
</div>
login.component.css
.card {
max-width: 400px;
}
.card .card-body {
min-height: 150px;
}
.home {
background-color: rgba(171, 172, 173, 0.575);
}
I had the same problem. mysql -u root -p
worked for me. It later asks you for a password. You should then enter the password that you had set for mysql. The default password could be password
, if you did not set one. More info here.
You need to seperate the functionality into a class or classes and launch that via one of two stubs. The console stub or service stub.
As its plain to see, when running windows, the myriad services that make up the infrastructure do not (and can't directly) present console windows to the user. The service needs to communicate with the user in a non graphical way: via the SCM; in the event log, to some log file etc. The service will also need to communicate with windows via the SCM, otherwise it will get shutdown.
It would obviously be acceptable to have some console app that can communicate with the service but the service needs to run independently without a requirement for GUI interaction.
The Console stub can very useful for debugging service behaviour but should not be used in a "productionized" environment which, after all, is the purpose of creating a service.
I haven't read it fully but this article seems to pint in the right direction.
This will work.
USE INFORMATION_SCHEMA;
SELECT TABLE_SCHEMA, TABLE_NAME
FROM information_schema.tables
WHERE TABLE_TYPE LIKE 'VIEW';
Use following code to perform if-else conditioning in python: Here, I am checking the length of the string. If the length is less than 3 then do nothing, if more then 3 then I check the last 3 characters. If last 3 characters are "ing" then I add "ly" at the end otherwise I add "ing" at the end.
Code-
if (len(s)<=3):
return s
elif s[-3:]=="ing":
return s+"ly"
else: return s + "ing"
NestedScrollView
NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. Nested scrolling is enabled by default.
https://developer.android.com/reference/android/support/v4/widget/NestedScrollView.html
ScrollView
Layout container for a view hierarchy that can be scrolled by the user, allowing it to be larger than the physical display. A ScrollView is a FrameLayout, meaning you should place one child in it containing the entire contents to scroll; this child may itself be a layout manager with a complex hierarchy of objects
https://developer.android.com/reference/android/widget/ScrollView.html
A New Laravel Blade Error Directive comes to Laravel 5.8.13
// Before
@if ($errors->has('email'))
<span>{{ $errors->first('email') }}</span>
@endif
// After:
@error('email')
<span>{{ $message }}</span>
@enderror
import { Router } from '@angular/router';
//in your constructor
constructor(public router: Router){}
//navigation
link.this.router.navigateByUrl('/home');
In Android Studio your resource(images) file name cannot start with NUMERIC
and It cannot contain any BIG
character. To solve your problem, do as Aliyah said. Just restart your IDE. This solved my problem too.
Here is my solution need get Status Http for checking status of server regularly
$url = 'http://www.example.com'; // Your server link
while(true) {
$strHeader = get_headers($url)[0];
$statusCode = substr($strHeader, 9, 3 );
if($statusCode != 200 ) {
echo 'Server down.';
// Send email
}
else {
echo 'oK';
}
sleep(30);
}
static double Evaluate(string expression) {
var loDataTable = new DataTable();
var loDataColumn = new DataColumn("Eval", typeof (double), expression);
loDataTable.Columns.Add(loDataColumn);
loDataTable.Rows.Add(0);
return (double) (loDataTable.Rows[0]["Eval"]);
}
Explanation of how it works:
First, we make a table in the part var loDataTable = new DataTable();
, just like in a Data Base Engine (MS SQL for example).
Then, a column, with some specific parameters (var loDataColumn = new DataColumn("Eval", typeof (double), expression);
).
The "Eval"
parameter is the name of the column (ColumnName attribute).
typeof (double)
is the type of data to be stored in the column, which is equal to put System.Type.GetType("System.Double");
instead.
expression
is the string that the Evaluate
method receives, and is stored in the attribute Expression
of the column. This attribute is for a really specific purpose (obvious), which is that every row that's put on the column will be fullfilled with the "Expression", and it accepts practically wathever can be put in a SQL Query. Refer to http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression(v=vs.100).aspx to know what can be put in the Expression attribute, and how it's evaluated.
Then, loDataTable.Columns.Add(loDataColumn);
adds the column loDataColumn
to the loDataTable
table.
Then, a row is added to the table with a personalized column with a Expression attribute, done via loDataTable.Rows.Add(0);
. When we add this row, the cell of the column "Eval" of the table loDataTable
is fullfilled automatically with its "Expression" attribute, and, if it has operators and SQL Queries, etc, it's evaluated and then stored to the cell, so, here happens the "magic", the string with operators is evaluated and stored to a cell...
Finally, just return the value stored to the cell of the column "Eval" in row 0 (it's an index, starts counting from zero), and making a conversion to a double with return (double) (loDataTable.Rows[0]["Eval"]);
.
And that's all... job done!
And here a code eaiser to understand, which does the same... It's not inside a method, and it's explained too.
DataTable MyTable = new DataTable();
DataColumn MyColumn = new DataColumn();
MyColumn.ColumnName = "MyColumn";
MyColumn.Expression = "5+5/5"
MyColumn.DataType = typeof(double);
MyTable.Columns.Add(MyColumn);
DataRow MyRow = MyTable.NewRow();
MyTable.Rows.Add(MyRow);
return (double)(MyTable.Rows[0]["MyColumn"]);
First, create the table with DataTable MyTable = new DataTable();
Then, a column with DataColumn MyColumn = new DataColumn();
Next, we put a name to the column. This so we can search into it's contents when it's stored to the table. Done via MyColumn.ColumnName = "MyColumn";
Then, the Expression, here we can put a variable of type string, in this case there's a predefined string "5+5/5", which result is 6.
The type of data to be stored to the column MyColumn.DataType = typeof(double);
Add the column to the table... MyTable.Columns.Add(MyColumn);
Make a row to be inserted to the table, which copies the table structure DataRow MyRow = MyTable.NewRow();
Add the row to the table with MyTable.Rows.Add(MyRow);
And return the value of the cell in row 0 of the column MyColumn
of the table MyTable
with return (double)(MyTable.Rows[0]["MyColumn"]);
Lesson done!!!
I hope mine helps
template <typename t_int>
std::array<uint8_t, sizeof (t_int)> int2array(t_int p_value) {
static const uint8_t _size_of (static_cast<uint8_t>(sizeof (t_int)));
typedef std::array<uint8_t, _size_of> buffer;
static const std::array<uint8_t, 8> _shifters = {8*0, 8*1, 8*2, 8*3, 8*4, 8*5, 8*6, 8*7};
buffer _res;
for (uint8_t _i=0; _i < _size_of; ++_i) {
_res[_i] = static_cast<uint8_t>((p_value >> _shifters[_i]));
}
return _res;
}
Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:
$('td').click(function(){
var row_index = $(this).closest("tr").index();
var col_index = $(this).index();
});
I also had this issue and it arose because I re-made the project and then forgot to re-link it by reference in a dependent project.
Thus it was linking by reference to the old project instead of the new one.
It is important to know that there is a bug in re-adding a previously linked project by reference. You've got to manually delete the reference in the vcxproj and only then can you re-add it. This is a known issue in Visual studio according to msdn.
To get upper case version of a string you can use str.upper
:
s = 'sdsd'
s.upper()
#=> 'SDSD'
On the other hand string.ascii_uppercase
is a string containing all ASCII letters in upper case:
import string
string.ascii_uppercase
#=> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Here's my code (not optimized but a full working example):
<head>
<style>
#divtoshow {position:absolute;display:none;color:white;background-color:black}
#onme {width:150px;height:80px;background-color:yellow;cursor:pointer}
</style>
<script type="text/javascript">
var divName = 'divtoshow'; // div that is to follow the mouse (must be position:absolute)
var offX = 15; // X offset from mouse position
var offY = 15; // Y offset from mouse position
function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}
function follow(evt) {
var obj = document.getElementById(divName).style;
obj.left = (parseInt(mouseX(evt))+offX) + 'px';
obj.top = (parseInt(mouseY(evt))+offY) + 'px';
}
document.onmousemove = follow;
</script>
</head>
<body>
<div id="divtoshow">test</div>
<br><br>
<div id='onme' onMouseover='document.getElementById(divName).style.display="block"' onMouseout='document.getElementById(divName).style.display="none"'>Mouse over this</div>
</body>
Some quick benchmarking (each test = 500k appended elements and the results are averages of multiple runs) showed the following:
Firefox 3.6 (Mac):
arr[arr.length] = b
is faster (300ms vs. 800ms)arr.push(b)
is faster (500ms vs. 900ms)Safari 5.0 (Mac):
arr[arr.length] = b
is faster (90ms vs. 115ms)arr[arr.length] = b
is faster (160ms vs. 185ms)Google Chrome 6.0 (Mac):
I like the arr.push()
syntax better, but I think I'd be better off with the arr[arr.length]
Version, at least in raw speed. I'd love to see the results of an IE run though.
My benchmarking loops:
function arrpush_small() {
var arr1 = [];
for (a = 0; a < 100; a++)
{
arr1 = [];
for (i = 0; i < 5000; i++)
{
arr1.push('elem' + i);
}
}
}
function arrlen_small() {
var arr2 = [];
for (b = 0; b < 100; b++)
{
arr2 = [];
for (j = 0; j < 5000; j++)
{
arr2[arr2.length] = 'elem' + j;
}
}
}
function arrpush_large() {
var arr1 = [];
for (i = 0; i < 500000; i++)
{
arr1.push('elem' + i);
}
}
function arrlen_large() {
var arr2 = [];
for (j = 0; j < 500000; j++)
{
arr2[arr2.length] = 'elem' + j;
}
}
Try this:
#include <stdio.h>
int main()
{
printf("Printing quotation mark \" ");
}
Example with float:
public static float getMaxFloat(float[] data) {
float[] copy = Arrays.copyOf(data, data.length);
Arrays.sort(copy);
return copy[data.length - 1];
}
public static float getMinFloat(float[] data) {
float[] copy = Arrays.copyOf(data, data.length);
Arrays.sort(copy);
return copy[0];
}
You can add header "Content-Type: text/html; charset=UTF-8" to your message body.
$headers = "Content-Type: text/html; charset=UTF-8";
If you use native mail()
function $headers array will be the 4th parameter
mail($to, $subject, $message, $headers)
If you user PEAR Mail::factory() code will be:
$smtp = Mail::factory('smtp', $params);
$mail = $smtp->send($to, $headers, $body);
It sounds like the populate method is what your looking for. First make small change to your post schema:
var postSchema = new Schema({
name: String,
postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Then make your model:
var Post = mongoose.model('Post', postSchema);
Then, when you make your query, you can populate references like this:
Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
// do stuff with post
});
Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to utf-8
or other encoder that can represent your data. Then you can print it to sys.stdout
.
First, run following code in the console:
chcp 65001
set PYTHONIOENCODING=utf-8
Then, start python
do anything you want.
Send the passwordbox control as a parameter to your login command.
<Button Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=PasswordBox}"...>
Then you can call CType(parameter, PasswordBox).Password
in your viewmodel.
You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.
You just need to re-open the image with IrfanView after changing the view color to white.
To change the viewing color in Irfanview go to:
Options > Properties/Settings > Viewing > Main window color
An alternative way to do it is:
var div = document.getElementById('myDiv');
while(div.firstChild)
div.removeChild(div.firstChild);
However, using document.getElementById('myDiv').innerHTML = "";
is faster.
See: Benchmark test
N.B.
Both methods preserve the div.
In HTML:
<a href="index.php?link=home" name="home">home</a>
Then in PHP:
if(isset($_GET['link'])){$_SESSION['link'] = $_GET['link'];}
Actually, I'm pretty sure Reflector is considered a disassembler with some decompiler functionality. Disassembler because it reads the bytes out of an assembly's file and converts it to an assembly language (ILasm in this case). The Decompiler functionality it provides by parsing the IL into well known patterns (like expressions and statements) which then get translated into higher level languages like C#, VB.Net, etc. The addin api for Reflector allows you to write your own language translator if you wish ... however the magic of how it parses the IL into the expression trees is a closely guarded secret.
I would recommend looking at any of the three things mentioned above if you want to understand how IL disassemblers work: Dile, CCI and Mono are all good sources for this stuff.
I also highly recommend getting the Ecma 335 spec and Serge Lidin's book too.
I use:
border: 0;
From 8.5.4 in CSS 2.1:
'border'
Value: [ <border-width> || <border-style> || <'border-top-color'> ] | inherit
So either of your methods look fine.
checkout
can be use for many case :
1st case : switch between branch in local repository
For instance :
git checkout exists_branch_to_switch
You can also create new branch and switch out in throught this case with -b
git checkout -b new_branch_to_switch
2nd case : restore file from x rev
git checkout rev file_to_restore
...
Join like this:
ON a.userid = b.sourceid AND a.listid = b.destinationid;
int? is shorthand for Nullable<int>
.
This may be the post you were looking for.
Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:
> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35,
times = 10), rep(45, times = 4)))
$cp
mean s.d. skewness
41.46228 12.47892 0.99527
This probably works better on data that is more skew-normal:
Just complementing @Jonsmoke's answer.
For API level 21 and above you can use :
android:backgroundTint="@android:color/white"
in XML for the button layout.
For API level below 21 use an AppCompatButton using app namespace instead of android for backgroundTint.
For example:
<android.support.v7.widget.AppCompatButton
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Button"
app:backgroundTint="@android:color/white" />
Instead of using a submit button, try using a <button type="button">Submit</button>
You can then call a javascript function in the button, and after the alert popup is confirmed, you can manually submit the form with document.getElementById("form").submit(); ... so you'll need to name and id your form for that to work.
Suppose I have a model User
User.find(id)
Returns a row where primary key = id. The return type will be User
object.
User.find_by(email:"[email protected]")
Returns first row with matching attribute or email in this case. Return type will be User
object again.
Note :- User.find_by(email: "[email protected]")
is similar to User.find_by_email("[email protected]")
User.where(project_id:1)
Returns all users in users table where attribute matches.
Here return type will be ActiveRecord::Relation
object. ActiveRecord::Relation
class includes Ruby's Enumerable
module so you can use it's object like an array and traverse on it.