I think you might want something like this
// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
this works too.
df = NULL
for (k in 1:10)
{
x = 1
y = 2
z = 3
df = rbind(df, data.frame(x,y,z))
}
output will look like this
df #enter
x y z #col names
1 2 3
For agg
, the lambba function gets a Series
, which does not have a 'Short name'
attribute.
stats.mode
returns a tuple of two arrays, so you have to take the first element of the first array in this tuple.
With these two simple changements:
source.groupby(['Country','City']).agg(lambda x: stats.mode(x)[0][0])
returns
Short name
Country City
Russia Sankt-Petersburg Spb
USA New-York NY
Boris Zbarsky (Mozilla), who probably knows more about the innards of Gecko than anyone else, provided at http://lists.w3.org/Archives/Public/public-html/2009Apr/0195.html the pseudocode repeated below to describe what Gecko based browsers do:
if (@type not set or empty) {
if (@language not set or empty) {
// Treat as default script language; what this is depends on the
// content-script-type HTTP header or equivalent META tag
} else {
if (@language is one of "javascript", "livescript", "mocha",
"javascript1.0", "javascript1.1",
"javascript1.2", "javascript1.3",
"javascript1.4", "javascript1.5",
"javascript1.6", "javascript1.7",
"javascript1.8") {
// Treat as javascript
} else {
// Treat as unknown script language; do not execute
}
}
} else {
if (@type is one of "text/javascript", "text/ecmascript",
"application/javascript",
"application/ecmascript",
"application/x-javascript") {
// Treat as javascript
} else {
// Treat as specified (e.g. if pyxpcom is installed and
// python script is allowed in this context and the type
// is one that the python runtime claims to handle, use that).
// If we don't have a runtime for this type, do not execute.
}
}
Just wanted to throw this into the mix for anyone using Microsoft SQL Server instead of MySQL. The keyword 'Limit' isn't supported by MSSQL, so you'll need to use an alternative. This code worked in SQL 2008, and is based on this SO post. https://stackoverflow.com/a/1104447/993856
-- Keep the last 10 most recent passwords for this user.
DECLARE @UserID int; SET @UserID = 1004
DECLARE @ThresholdID int -- Position of 10th password.
SELECT @ThresholdID = UserPasswordHistoryID FROM
(
SELECT ROW_NUMBER()
OVER (ORDER BY UserPasswordHistoryID DESC) AS RowNum, UserPasswordHistoryID
FROM UserPasswordHistory
WHERE UserID = @UserID
) sub
WHERE (RowNum = 10) -- Keep this many records.
DELETE UserPasswordHistory
WHERE (UserID = @UserID)
AND (UserPasswordHistoryID < @ThresholdID)
Admittedly, this is not elegant. If you're able to optimize this for Microsoft SQL, please share your solution. Thanks!
You may just without making the element hidden, simply make it transparent by making its opacity to 0.
Making the input file hidden will make it STOP working. So DON'T DO THAT..
Here you can find an example for a transparent Browse operation;
Determine if property is existing (but is not a falsy value):
if (typeof query !== 'undefined' && query !== null){
doStuff();
}
Usually using
if (query){
doStuff();
}
is sufficient. Please note that:
if (!query){
doStuff();
}
doStuff() will execute even if query was an existing variable with falsy value (0, false, undefined or null)
Btw, there's a sexy coffeescript way of doing this:
if object?.property? then doStuff()
which compiles to:
if ((typeof object !== "undefined" && object !== null ? object.property : void 0) != null)
{
doStuff();
}
I think every process you make start executing the line you create so something like this...
pid=fork() at line 6. fork function returns 2 values
you have 2 pids, first pid=0 for child and pid>0 for parent
so you can use if to separate
.
/*
sleep(int time) to see clearly
<0 fail
=0 child
>0 parent
*/
int main(int argc, char** argv) {
pid_t childpid1, childpid2;
printf("pid = process identification\n");
printf("ppid = parent process identification\n");
childpid1 = fork();
if (childpid1 == -1) {
printf("Fork error !\n");
}
if (childpid1 == 0) {
sleep(1);
printf("child[1] --> pid = %d and ppid = %d\n",
getpid(), getppid());
} else {
childpid2 = fork();
if (childpid2 == 0) {
sleep(2);
printf("child[2] --> pid = %d and ppid = %d\n",
getpid(), getppid());
} else {
sleep(3);
printf("parent --> pid = %d\n", getpid());
}
}
return 0;
}
//pid = process identification
//ppid = parent process identification
//child[1] --> pid = 2399 and ppid = 2398
//child[2] --> pid = 2400 and ppid = 2398
//parent --> pid = 2398
:set list
in Vim will show whitespace. End of lines show as '$
' and carriage returns usually show as '^M
'.
If you are struggling with the connection in the XAMPP environment I suggest uncommenting the following entry in the php.ini
file.
extension = odbc
I received an error without it: Uncaught pdoexception: could not find driver
It seems there is a much better and clean solution: To use google.maps.places.SearchBox
instead of google.maps.places.Autocomplete
.
A code is almost the same, just getting the first from multiple places. On pressing the Enter the the correct list is returned - so it runs out of the box and there is no need for hacks.
See the example HTML page:
The relevant code snippet is:
var searchBox = new google.maps.places.SearchBox(document.getElementById('searchinput'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
var place = searchBox.getPlaces()[0];
if (!place.geometry) return;
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(16);
}
});
The complete source code of the example is at: https://gist.github.com/klokan/8408394
McGarnagle has a great answer, and you'll want to be accepting his, but I thought I'd mention (since you asked) how databinding works.
It's generally implemented by firing events whenever a change is made to the data, which then causes listeners (e.g. the UI) to be updated.
Two-way binding works by doing this twice, with a bit of care taken to ensure that you don't wind up stuck in an event loop (where the update from the event causes another event to be fired).
I was gonna put this in a comment, but it was getting pretty long...
You can not change an immutable object, like str
or tuple
, inside a function in Python, but you can do things like:
def foo(y):
y[0] = y[0]**2
x = [5]
foo(x)
print x[0] # prints 25
That is a weird way to go about it, however, unless you need to always square certain elements in an array.
Note that in Python, you can also return more than one value, making some of the use cases for pass by reference less important:
def foo(x, y):
return x**2, y**2
a = 2
b = 3
a, b = foo(a, b) # a == 4; b == 9
When you return values like that, they are being returned as a Tuple which is in turn unpacked.
edit: Another way to think about this is that, while you can't explicitly pass variables by reference in Python, you can modify the properties of objects that were passed in. In my example (and others) you can modify members of the list that was passed in. You would not, however, be able to reassign the passed in variable entirely. For instance, see the following two pieces of code look like they might do something similar, but end up with different results:
def clear_a(x):
x = []
def clear_b(x):
while x: x.pop()
z = [1,2,3]
clear_a(z) # z will not be changed
clear_b(z) # z will be emptied
You can't do a XMLHttpRequest crossdomain, the only "option" would be a technique called JSONP, which comes down to this:
To start request: Add a new <script>
tag with the remote url, and then make sure that remote url returns a valid javascript file that calls your callback function. Some services support this (and let you name your callback in a GET parameters).
The other easy way out, would be to create a "proxy" on your local server, which gets the remote request and then just "forwards" it back to your javascript.
edit/addition:
I see jQuery has built-in support for JSONP, by checking if the URL contains "callback=?" (where jQuery will replace ? with the actual callback method). But you'd still need to process that on the remote server to generate a valid response.
There is a much easier way to compile and run C code using GCC, no configuration needed:
Ctrl+Alt+N
, or press F1
and then select/type Run Code
, or right click the Text Editor and then click Run Code
in context menu, the code will be compiled and run, and the output will be shown in the Output Window.Moreover you could update the config in settings.json using different C compilers as you want, the default config for C is as below:
"code-runner.executorMap": {
"c": "gcc $fullFileName && ./a.out"
}
I can see the that the others answers shown above are right, but I'll make your life easy.
I even created an example for you. I added some rows and want delete them.
You have to right click on the table and as shown in the figure Script Table a> Delete to> New query Editor widows:
Then another window will open with a script. Delete the line of "where", because you want to delete all rows. Then click Execute.
To make sure you did it right right click over the table and click in "Select Top 1000 rows". Then you can see that the query is empty.
this works for me, sudo apt-get install libx11-dev
If the branch that your stashed changes are based on has changed in the meantime, this command may be useful:
git diff stash@{0}^!
This compares the stash against the commit it is based on.
write.csv(t, "t.csv", row.names=FALSE)
From ?write.csv
:
row.names: either a logical value indicating whether the row names of
‘x’ are to be written along with ‘x’, or a character vector
of row names to be written.
I think the biggest problem is that any elements written via document.write are added to the end of the page's elements. That's rarely the desired effect with modern page layouts and AJAX. (you have to keep in mind that the elements in the DOM are temporal, and when the script runs may affect its behavior).
It's much better to set a placeholder element on the page, and then manipulate it's innerHTML.
Here is another JQuery-based solution without any timers:
<script type="text/javascript">
function loadScript(url, onsuccess, onerror) {
$.get(url)
.done(function() {
// File/url exists
console.log("JS Loader: file exists, executing $.getScript "+url)
$.getScript(url, function() {
if (onsuccess) {
console.log("JS Loader: Ok, loaded. Calling onsuccess() for " + url);
onsuccess();
console.log("JS Loader: done with onsuccess() for " + url);
} else {
console.log("JS Loader: Ok, loaded, no onsuccess() callback " + url)
}
});
}).fail(function() {
// File/url does not exist
if (onerror) {
console.error("JS Loader: probably 404 not found. Not calling $.getScript. Calling onerror() for " + url);
onerror();
console.error("JS Loader: done with onerror() for " + url);
} else {
console.error("JS Loader: probably 404 not found. Not calling $.getScript. No onerror() callback " + url);
}
});
}
</script>
Thanks to: https://stackoverflow.com/a/14691735/1243926
Sample usage (original sample from JQuery getScript documentation):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getScript demo</title>
<style>
.block {
background-color: blue;
width: 150px;
height: 70px;
margin: 10px;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<button id="go">» Run</button>
<div class="block"></div>
<script>
function loadScript(url, onsuccess, onerror) {
$.get(url)
.done(function() {
// File/url exists
console.log("JS Loader: file exists, executing $.getScript "+url)
$.getScript(url, function() {
if (onsuccess) {
console.log("JS Loader: Ok, loaded. Calling onsuccess() for " + url);
onsuccess();
console.log("JS Loader: done with onsuccess() for " + url);
} else {
console.log("JS Loader: Ok, loaded, no onsuccess() callback " + url)
}
});
}).fail(function() {
// File/url does not exist
if (onerror) {
console.error("JS Loader: probably 404 not found. Not calling $.getScript. Calling onerror() for " + url);
onerror();
console.error("JS Loader: done with onerror() for " + url);
} else {
console.error("JS Loader: probably 404 not found. Not calling $.getScript. No onerror() callback " + url);
}
});
}
loadScript("https://raw.github.com/jquery/jquery-color/master/jquery.color.js", function() {
console.log("loaded jquery-color");
$( "#go" ).click(function() {
$( ".block" )
.animate({
backgroundColor: "rgb(255, 180, 180)"
}, 1000 )
.delay( 500 )
.animate({
backgroundColor: "olive"
}, 1000 )
.delay( 500 )
.animate({
backgroundColor: "#00f"
}, 1000 );
});
}, function() { console.error("Cannot load jquery-color"); });
</script>
</body>
</html>
You might want to use jQuery's .addClass and .removeClass commands, and create two different classes for the states. This, to me, would be the best practice way of doing it.
Just thought i'd share this with anyone who needs more clarity on how to achieve this:
myCanvas is a Canvas control and Parent to all other controllers. This code works to neatly resize to any resolution from 1366 x 768 upward. Tested up to 4k resolution 4096 x 2160
Take note of all the MainWindow property settings (WindowStartupLocation, SizeToContent and WindowState) - important for this to work correctly - WindowState for my user case requirement was Maximized
xaml
<Window x:Name="mainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyApp"
xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
x:Class="MyApp.MainWindow"
Title="MainWindow" SizeChanged="MainWindow_SizeChanged"
Width="1366" Height="768" WindowState="Maximized" WindowStartupLocation="CenterOwner" SizeToContent="WidthAndHeight">
<Canvas x:Name="myCanvas" HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1356">
<Image x:Name="maxresdefault_1_1__jpg" Source="maxresdefault-1[1].jpg" Stretch="Fill" Opacity="0.6" Height="767" Canvas.Left="-6" Width="1366"/>
<Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" Height="0" Canvas.Left="-811" Canvas.Top="148" Width="766"/>
<Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" HorizontalAlignment="Right" Width="210" Height="0" Canvas.Left="1653" Canvas.Top="102"/>
<Image x:Name="imgscroll" Source="BcaKKb47i[1].png" Stretch="Fill" RenderTransformOrigin="0.5,0.5" Height="523" Canvas.Left="-3" Canvas.Top="122" Width="580">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="89.093"/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
.cs
private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
{
myCanvas.Width = e.NewSize.Width;
myCanvas.Height = e.NewSize.Height;
double xChange = 1, yChange = 1;
if (e.PreviousSize.Width != 0)
xChange = (e.NewSize.Width / e.PreviousSize.Width);
if (e.PreviousSize.Height != 0)
yChange = (e.NewSize.Height / e.PreviousSize.Height);
ScaleTransform scale = new ScaleTransform(myCanvas.LayoutTransform.Value.M11 * xChange, myCanvas.LayoutTransform.Value.M22 * yChange);
myCanvas.LayoutTransform = scale;
myCanvas.UpdateLayout();
}
there are two columns in the a table ID and name where names are repeating with different IDs so for that you may use this query: . .
DELETE FROM dbo.tbl1
WHERE id NOT IN (
Select MIN(Id) AS namecount FROM tbl1
GROUP BY Name
)
I know this is a bit old, but I had the same problem and my search brought me here. I wanted two select elements and a button all inline, which worked in 2 but not 3. I ended up wrapping the three elements in <form class="form-inline">...</form>
. This actually worked perfectly for me.
There is types.SimpleNamespace
class in Python 3.3+:
obj = someobject
obj.a = SimpleNamespace()
for p in params:
setattr(obj.a, p, value)
# obj.a.attr1
collections.namedtuple
, typing.NamedTuple
could be used for immutable objects. PEP 557 -- Data Classes suggests a mutable alternative.
For a richer functionality, you could try attrs
package. See an example usage.
An additional way to do that (from the command line):
git config --global diff.tool tkdiff
git config --global merge.tool tkdiff
git config --global --add difftool.prompt false
The first two lines will set the difftool and mergetool to tkdiff
- change that according to your preferences. The third line disables the annoying prompt so whenever you hit git difftool
it will automatically launch the difftool.
On Windows 7 setting the proxy to global config will resolve this issue
git config --global http.proxy http://user:password@proxy_addr:port
but the problem here is your password will not be encrypted.. Hopefully that should not be much problem as most of time you will be sole owner of your PC.
You can't achieve POST requests using urllib
(only for GET), instead try using requests
module, e.g.:
Example 1.0:
import requests
base_url="www.server.com"
final_url="/{0}/friendly/{1}/url".format(base_url,any_value_here)
payload = {'number': 2, 'value': 1}
response = requests.post(final_url, data=payload)
print(response.text) #TEXT/HTML
print(response.status_code, response.reason) #HTTP
Example 1.2:
>>> import requests
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
Example 1.3:
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, data=json.dumps(payload))
Suppose you are running a test python file named request.py
In request.py, you write
import request
so this also most likely a circular import.
Solution:
Just change your test file to another name such as aaa.py
, other than request.py
.
Do not use names that are already used by other libs.
I ended up doing this by exporting a frozen object with anonymous getter functions, rather than the constants themselves. This reduces the risk of nasty bugs introduced due to a simple typo of the const name, as a runtime error will be thrown in case of a typo. Here's a full example that also uses ES6 Symbols for the constants, ensuring uniqueness, and ES6 arrow functions. Would appreciate feedback if anything in this approach seems problematic.
'use strict';
const DIRECTORY = Symbol('the directory of all sheets');
const SHEET = Symbol('an individual sheet');
const COMPOSER = Symbol('the sheet composer');
module.exports = Object.freeze({
getDirectory: () => DIRECTORY,
getSheet: () => SHEET,
getComposer: () => COMPOSER
});
For completeness:
Along the lines of Chase's answer, I usually use as.data.frame
to coerce the matrix to a data.frame:
m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))
EDIT: speed test data.frame
vs. as.data.frame
system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
8.005 0.108 8.165
system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
3.759 0.048 3.802
Yes, it appears to be faster (by about 2 times).
The way you have used the HTML syntax is problematic.
This is how the syntax should be
style="property1:value1;property2:value2"
In your case, this will be the way to do
<h2 style="text-align :center; font-family :tahoma" >TITLE</h2>
A further example would be as follows
<div class ="row">
<button type="button" style= "margin-top : 20px; border-radius: 15px"
class="btn btn-primary">View Full Profile</button>
</div>
You need to declare an array in another array.
$arr = array(array(content), array(content));
Example:
$arr = array(array(1,2,3), array(4,5,6));
To get the first item from the array, you'll use $arr[0][0]
, that's like the first item from the first array from the array.
$arr[1][0]
will return the first item from the second array from the array.
As the original question does not state which NuGet frontend should be used, I would like to mention that NuGet 3.5 adds support for updating to a specific version via the command line client (which works for downgrades, too):
NuGet.exe update Common.Logging -Version 1.2.0
For me, it relate to Firewall setting. Go to your firewall setting, allow DTC Service and it worked.
Found following solution working for my similar problem:
private ExtendedHashMap mData = new ExtendedHashMap();
private String[] mKeys;
public void setNewData(ExtendedHashMap data) {
mData.putAll(data);
mKeys = data.keySet().toArray(new String[data.size()]);
notifyDataSetChanged();
}
Using the clear-command
mData.clear()
is not nessescary
This worked for me:
$("#element1").droppable(
{
drop: function(event, ui)
{
var currentPos = ui.helper.position();
alert("left="+parseInt(currentPos.left)+" top="+parseInt(currentPos.top));
}
});
I had the same problem with different assemblies referencing different versions of Newtonsoft.json. The solution that worked for me was running update-package from Nuget Package Manager Console.
I used like this
$option = trim($option);
$option = str_replace(' ', '_', $option);
Swift 3, xcode version 8.3.2, storyboard->choose your table View->inspector->Separator.
Try this:
diff -rq /path/to/folder1 /path/to/folder2
They all perform pretty well, ­
edges it as Google can still index of words containing it.
­
and ­
both display as expected in major browsers (even old IE!). <wbr>
isn't supported in recent versions of IE (10 or 11) and doesn't work properly in Edge.­
and ­
for Chrome and Firefox on Mac, on Windows (10), it keeps the characters and pastes hard hyphens into Notepad and invisible soft hyphens into applications that support them. IE (win7) always pastes with hyphens, even in IE10, and Safari (Mac) copies in a way which pastes as hyphens in some applications (e.g. MS Word), but not others­
and ­
on all browsers except IE which only matches exact copied-and-pasted matches (even up to IE11)­
with words typed normally. As of 2017 it appears to no longer match words containing ­
. Yandex appers to be the same. Bing and Baidu seem to not match either.For up-to-date live testing, here are some examples of unique words with soft hyphens.
­
- confumbabbl­ication­ism
- confumbabblicationism
<wbr>
- donfounbabbl<wbr>ication<wbr>ism
. This site removes <wbr/>
from output. Here's a jsbin.com snippet for testing.
­
- eonfulbabbl­ication­ism
- eonfulbabblicationism
Here they are with no shy hyphens (this is for copying and pasting into find-on-page testing; written in a way which won't break the search engine tests):
ZZZconfumbabblicationismZZZdonfounbabblicationismZZZeonfulbabblicationismZZZ
Success: displaying as a normal word, except where it should break, when it breaks and hyphenates in the specified place.
Failure: displaying unusually, or failing to break in the intended place.
­
success, <wbr>
success, ­
success­
success, <wbr>
success, ­
success­
success, <wbr>
not tested yet, ­
success­
success, <wbr>
fail (break but no hyphen), ­
success­
success, <wbr>
fail (no break), ­
success­
success, <wbr>
fail (no break), ­
successword-wrap
. Sometimes, they seem to all work. Not yet found any clear pattern as to why.­
success, <wbr>
success, ­
successSuccess: copying and pasting the whole word, unhyphenated. (tested on Mac pasting into browser search, MS Word 2011, and Sublime Text)
Failure: pasting with a hyphen, space, line break, or with junk characters.
­
success, <wbr>
success, ­
success­
success, <wbr>
success, ­
success­
fail into MS Word (pastes all as hyphens), success in other applications <wbr>
fail, ­
fail into MS Word (pastes all as hyphens), success in other applications­
fail pastes all as hyphens, <wbr>
fail, ­
fail pastes all as hyphens­
fail pastes all as hyphens, <wbr>
fail, ­
fail pastes all as hyphens­
fail pastes all as hyphens, <wbr>
fail, ­
fail pastes all as hyphensUpdated in November 2017. <wbr>
not tested because StackOverflow's CMS stripped it out.
Success: searches on the whole, non-hyphenated word find this page.
Failure: search engines only find this page on searches for the broken segments of the words, or a word with hyphens.
­
fails, ­
succeeds­
fails, ­
fails­
fails, ­
fails (can match fragments within longer strings but not the words on their own containing a ­
or ­
)­
fails, ­
succeeds (though it's possible it's matching a string fragment like Baidu, not 100% sure)Success and failure as search engine matching.
­
success, <wbr>
success, ­
success­
success, <wbr>
success, ­
success­
success, <wbr>
success, ­
success­
fail only matches when both contain shy hyphens, <wbr>
success, ­
fail only matches when both contain shy hyphens­
fail only matches when both contain shy hyphens, <wbr>
success, ­
fail only matches when both contain shy hyphens­
fail only matches when both contain shy hyphens, <wbr>
success, ­
fail only matches when both contain shy hyphensYou can use reflection.
Type typeOfMyObject = myObject.GetType();
PropertyInfo[] properties =typeOfMyObject.GetProperties();
This is current accepted way to link to a specific lat lon (rather than search for the nearest object).
http://maps.google.com/maps?z=12&t=m&q=loc:38.9419+-78.3020
z
is the zoom level (1-20)t
is the map type ("m" map, "k" satellite, "h" hybrid, "p" terrain, "e" GoogleEarth)q
is the search query, if it is prefixed by loc:
then google assumes it is a lat lon separated by a +
I work on Mercurial, but fundamentally I believe both systems are equivalent. They both work with the same abstractions: a series of snapshots (changesets) which make up the history. Each changeset knows where it came from (the parent changeset) and can have many child changesets. The recent hg-git extension provides a two-way bridge between Mercurial and Git and sort of shows this point.
Git has a strong focus on mutating this history graph (with all the consequences that entails) whereas Mercurial does not encourage history rewriting, but it's easy to do anyway and the consequences of doing so are exactly what you should expect them to be (that is, if I modify a changeset you already have, your client will see it as new if you pull from me). So Mercurial has a bias towards non-destructive commands.
As for light-weight branches, then Mercurial has supported repositories with multiple branches since..., always I think. Git repositories with multiple branches are exactly that: multiple diverged strands of development in a single repository. Git then adds names to these strands and allow you to query these names remotely. The Bookmarks extension for Mercurial adds local names, and with Mercurial 1.6, you can move these bookmarks around when you push/pull..
I use Linux, but apparently TortoiseHg is faster and better than the Git equivalent on Windows (due to better usage of the poor Windows filesystem). Both http://github.com and http://bitbucket.org provide online hosting, the service at Bitbucket is great and responsive (I haven't tried github).
I chose Mercurial since it feels clean and elegant -- I was put off by the shell/Perl/Ruby scripts I got with Git. Try taking a peek at the git-instaweb.sh
file if you want to know what I mean: it is a shell script which generates a Ruby script, which I think runs a webserver. The shell script generates another shell script to launch the first Ruby script. There is also a bit of Perl, for good measure.
I like the blog post that compares Mercurial and Git with James Bond and MacGyver -- Mercurial is somehow more low-key than Git. It seems to me, that people using Mercurial are not so easily impressed. This is reflected in how each system do what Linus described as "the coolest merge EVER!". In Git you can merge with an unrelated repository by doing:
git fetch <project-to-union-merge>
GIT_INDEX_FILE=.git/tmp-index git-read-tree FETCH_HEAD
GIT_INDEX_FILE=.git/tmp-index git-checkout-cache -a -u
git-update-cache --add -- (GIT_INDEX_FILE=.git/tmp-index git-ls-files)
cp .git/FETCH_HEAD .git/MERGE_HEAD
git commit
Those commands look quite arcane to my eye. In Mercurial we do:
hg pull --force <project-to-union-merge>
hg merge
hg commit
Notice how the Mercurial commands are plain and not special at all -- the only unusual thing is the --force
flag to hg pull
, which is needed since Mercurial will abort otherwise when you pull from an unrelated repository. It is differences like this that makes Mercurial seem more elegant to me.
For people who have found this post from Google almost 6 years in the future (and beyond!), you may run into this problem with Apache 2 and PHP 7 while also using the UserDir
module.
Another possible cause of this problem could be that you are trying to run the script in a "user directory" from the the UserDir
module. Running PHP scripts in user directories is disabled by default. You will run into this problem if the script is in the public_html
directory in your home folder and you are trying to access it from http://localhost/~your_username
.
To fix this, open up /etc/apache2/mods-enabled/php7.2.conf
. You must comment or delete the tag block at the bottom that reads
<IfModule mod_userdir.c>
<Directory /home/*/public_html>
php_admin_flag engine Off
</Directory>
</IfModule>
Here is a CoffeeScript solution.
I was looking for the same solution and found seomething very intersting from this answer: Rejecting promises with multiple arguments (like $http) in AngularJS
the answer of this guy Florian
promise = deferred.promise
promise.success = (fn) ->
promise.then (data) ->
fn(data.payload, data.status, {additional: 42})
return promise
promise.error = (fn) ->
promise.then null, (err) ->
fn(err)
return promise
return promise
And to use it:
service.get().success (arg1, arg2, arg3) ->
# => arg1 is data.payload, arg2 is data.status, arg3 is the additional object
service.get().error (err) ->
# => err
I had a similar problem that I resolved myself.... I think it was partially my code hogging too much memory while too many "big things"
in my application - the workbook goes out and grabs another departments "daily report".. and I extract out all the information our team needs (to minimize mistakes and data entry).
I pull in their sheets directly... but I hate the fact that they use Merged cells... which I get rid of (ie unmerge, then find the resulting blank cells, and fill with the values from above)
I made my problem go away by
a)unmerging only the "used cells" - rather than merely attempting to do entire column... ie finding the last used row in the column, and unmerging only this range (there is literally 1000s of rows on each of the sheet I grab)
b) Knowing that the undo only looks after the last ~16 events... between each "unmerge" - i put 15 events which clear out what is stored in the "undo" to minimize the amount of memory held up (ie go to some cell with data in it.. and copy// paste special value... I was GUESSING that the accumulated sum of 30sheets each with 3 columns worth of data might be taxing memory set as side for undoing
Yes it doesn't allow for any chance of an Undo... but the entire purpose is to purge the old information and pull in the new time sensitive data for analysis so it wasn't an issue
Sound corny - but my problem went away
Also you can setup extJs writer
with encode
: true
and it will send data regularly (and, hence, you will be able to retrieve data via $_POST
and $_GET
).
... the values will be sent as part of the request parameters as opposed to a raw post (via docs for encode config of Ext.data.writer.Json)
UPDATE
Also docs say that:
The encode option should only be set to true when a root is defined
So, probably, writer
's root
config is required.
Actually, the ticked answer is exactly right, but the answer can be in ES6
shape:
HTMLInputElementObject.oninput = () => {
console.log('run'); // Do something
}
Or can be written like below:
HTMLInputElementObject.addEventListener('input', (evt) => {
console.log('run'); // Do something
});
I improved nickf's answer, so it recursively loops through objects:
function var_dump(obj, element)
{
var logMsg = objToString(obj, 0);
if (element) // set innerHTML to logMsg
{
var pre = document.createElement('pre');
pre.innerHTML = logMsg;
element.innerHTML = '';
element.appendChild(pre);
}
else // write logMsg to the console
{
console.log(logMsg);
}
}
function objToString(obj, level)
{
var out = '';
for (var i in obj)
{
for (loop = level; loop > 0; loop--)
{
out += " ";
}
if (obj[i] instanceof Object)
{
out += i + " (Object):\n";
out += objToString(obj[i], level + 1);
}
else
{
out += i + ": " + obj[i] + "\n";
}
}
return out;
}
In my case, I was doing:
curl <blabla> | jq | grep <blibli>
With jq .
it worked: curl <blabla> | jq . | grep <blibli>
Just use containsKey()
for clarity. It's fast and keeps the code clean and readable. The whole point of HashMap
s is that the key lookup is fast, just make sure the hashCode()
and equals()
are properly implemented.
Params contains the following three groups of parameters:
match '/user/:id'
in routes.rb will set params[:id]params[:controller]
and params[:action]
is always available and contains the current controller and actionYou can use std::to_string in C++11
float val = 2.5;
std::string my_val = std::to_string(val);
You can using dict
, fillna
with different value for different column
df.fillna({'a':0,'b':0})
Out[829]:
a b c
0 1.0 4.0 NaN
1 2.0 5.0 NaN
2 3.0 0.0 7.0
3 0.0 6.0 8.0
After assign it back
df=df.fillna({'a':0,'b':0})
df
Out[831]:
a b c
0 1.0 4.0 NaN
1 2.0 5.0 NaN
2 3.0 0.0 7.0
3 0.0 6.0 8.0
It was a driver missing problem with me. I had enabled the USB debugging, tried changing the USB cable, tried reinstalling the Google USB drivers, but nothing came to my rescue.
Then ultimately I downloaded the device drivers as suggested here.
To make sure whether you have a device driver problem, go to:
And see if you have your Nexus shown as an "Android device" or as a device in "Others".
If it shows in "Others", your problem should be resolved by downloading & extracting this and then following these steps:
Finally, your device will show up as follows:
As soon as you do this, a popup will show up on your device asking for permission to debug. Once you accept, you are ready!
What I use:
set long 50000
set linesize 130
col x format a80 word_wrapped;
select dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA') x from dual;
Or am I missing something?
If checkout master
was the last thing you did, then the reflog entry HEAD@{1}
will contain your commits (otherwise use git reflog
or git log -p
to find them). Use git merge HEAD@{1}
to fast forward them into master.
EDIT:
As noted in the comments, Git Ready has a great article on this.
git reflog
and git reflog --all
will give you the commit hashes of the mis-placed commits.
Source: http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html
You could use a Data URI to supply the image data, for example:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image width="20" height="20" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>
</svg>
The image will go through all normal svg transformations.
But this technique has disadvantages, for example the image will not be cached by the browser
best and simple way is to put title inside a span and replace then.
'<div id="'+div_id+'" class="widget" style="height:60px;width:110px">\n\
<div class="widget-head ui-widget-header"
style="cursor:move;height:20px;width:130px">'+
'<span id="'+span_id+'" style="float:right; cursor:pointer"
class="dialog_link ui-icon ui-icon-newwin ui-icon-pencil"></span>' +
'<span id="spTitle">'+
dialog_title+ '</span>'
'</div></div>
now you can simply use this:
$('#'+div_id+' .widget-head sp#spTitle').text("new dialog title");
We need to take care of event bubbling. Need to add one line of code
$("#savechanges").on("click", function (e) {
$("#userModal").modal("hide");
e.stopPropagation(); //This line would take care of it
});
I was kind of curious about this too, so I just put together a little sample code where you can see what it is doing:
try {
throw new NullPointerException();
}
catch (NullPointerException e) {
System.out.println(e);
}
try {
throw new IOException();
}
catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
Calling println(e)
:
java.lang.NullPointerException
Calling e.printStackTrace()
:
java.io.IOException at package.Test.main(Test.java:74)
The solution that worked for me was to edit the registry key to enable long path behaviour, setting the value to 1. This is a new opt-in feature for Windows 10
HKLM\SYSTEM\CurrentControlSet\Control\FileSystem LongPathsEnabled (Type: REG_DWORD)
I got this solution from a named section of the article that @james-hill posted.
https://docs.microsoft.com/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation
Instead of %matplotlib inline,it is not a python script so we can write like this it will work from IPython import get_ipython get_ipython().run_line_magic('matplotlib', 'inline')
Don't use IDs at all if you don't need to, instead wrap the input in a label like this:
<label>
My Label
<input type="text"/>
</label>
Then you won't need to worry about unique IDs.
No. I create labels above the listbox to serve as headers. You might think that it's a royal pain to change labels every time your lisbox changes. You'd be right - it is a pain. It's a pain to set up the first time, much less changes. But I haven't found a better way.
Most of these answers circulate around removing a file from the "staging area" pre-commit, but I often find myself looking here after I've already committed and I want to remove some sensitive information from the commit I just made.
An easy to remember trick for all of you git commit --amend
folks out there like me is that you can:
git add .
to add the deletion to the "staging area"git commit --amend
to remove the file from the previous commit.You will notice in the commit message that the unwanted file is now missing. Hooray! (Commit SHA
will have changed, so be careful if you already pushed your changes to the remote.)
Android Studio Users:
If you want to use grade, go to http://search.maven.org/ and search for your maven repo. Then, click on the "latest version" and in the details page on the bottom left you will see "Gradle" where you can then copy/paste that link into your app's build.gradle.
To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.
class YourClass():
def your_function(self, *args):
self.callable_function(param) # if you need to pass any parameter
def callable_function(self, *params):
print('Your param:', param)
I think the question is a little bit fuzzy - for example, it can be interpreted as a question about best practices in programming loops with if
inside. So, I'll try to answer this question with this particular interpretation.
If you have if
inside a loop, then in most cases you'd like to know how the loop has ended - was it "broken" by the if
or was it ended "naturally"? So, your sample code can be modified in this way:
bool intMaxFound = false;
for (size = 0; size < HAY_MAX; size++)
{
// wait for hay until EOF
printf("\nhaystack[%d] = ", size);
int straw = GetInt();
if (straw == INT_MAX)
{intMaxFound = true; break;}
// add hay to stack
haystack[size] = straw;
}
if (intMaxFound)
{
// ... broken
}
else
{
// ... ended naturally
}
The problem with this code is that the if
statement is buried inside the loop body, and it takes some effort to locate it and understand what it does. A more clear (even without the break
statement) variant will be:
bool intMaxFound = false;
for (size = 0; size < HAY_MAX && !intMaxFound; size++)
{
// wait for hay until EOF
printf("\nhaystack[%d] = ", size);
int straw = GetInt();
if (straw == INT_MAX)
{intMaxFound = true; continue;}
// add hay to stack
haystack[size] = straw;
}
if (intMaxFound)
{
// ... broken
}
else
{
// ... ended naturally
}
In this case you can clearly see (just looking at the loop "header") that this loop can end prematurely. If the loop body is a multi-page text, written by somebody else, then you'd thank its author for saving your time.
UPDATE:
Thanks to SO - it has just suggested the already answered question about crash of the AT&T phone network in 1990. It's about a risky decision of C creators to use a single reserved word break
to exit from both loops and switch
.
Anyway this interpretation doesn't follow from the sample code in the original question, so I'm leaving my answer as it is.
you need a file named __init__.py
(two underscores on each side) in every folder in the hierarchy, so one in src/
and one in model/
. This is what python looks for to know that it should access a particular folder. The files are meant to contain initialization instructions but even if you create them empty this will solve it.
Right click your project > Run As > Run Configuration... > Java Application (in left side panel) - double click on it. That will create new configuration. click on search button under Main Class section and select your main class from it.
The best way to do it is to put the Django admin templates inside your project. So your templates would be in templates/admin
while the stock Django admin templates would be in say template/django_admin
. Then, you can do something like the following:
templates/admin/change_form.html
{% extends 'django_admin/change_form.html' %}
Your stuff here
If you're worried about keeping the stock templates up to date, you can include them with svn externals or similar.
As noted by @victor hugo, the "proper" way is to use svn copy. There is one caveat though. The "tag" created that way will not be a true tag, it will be an exact copy of the specified revision, but it will be a different revision itself. So if your build system makes use of svn revision somehow (e.g. incorporates the number obtained with 'svn info' into the version of the product you build), then you won't be able to build exactly the same product from a tag (the result will have the revision of the tag instead of that of the original code).
It looks like by design there is no way in svn to create a truly proper meta tag.
Left click on a method and press the F12 key to Go To Definition. Other Actions also available
Well using find is the best option here
just simply use like this
$(".class").click(function(){
$("this").find('.subclass').css("visibility","visible");
})
and if there are many classes with the same name class its always better to give the class name of parent class like this
$(".parent .class").click(function(){
$("this").find('.subclass').css("visibility","visible");
})
You would need to say which version of Ant and which JVM version.
You can run ant -v
to see which settings Ant is using as per the doc
Ant 1.8* requires JDK 1.4 or higher.
The 'Unsupported major.minor version 51.0' means somewhere code was compiled for a version of the JDK, and that you are trying to run those classes under an older version of the JDK. (see here)
If you are using Maven, add the below config in your pom.xml:
<build>
<testResources>
<testResource>
<directory>src/main/webapp</directory>
</testResource>
</testResources>
</build>
With this config, you will be able to access xml files in WEB-INF folder. From Maven POM Reference: The testResources element block contains testResource elements. Their definitions are similar to resource elements, but are naturally used during test phases.
Building on @rocksportrocker solution, It would make sense to dill when sending and RECVing the results.
import dill
import itertools
def run_dill_encoded(payload):
fun, args = dill.loads(payload)
res = fun(*args)
res = dill.dumps(res)
return res
def dill_map_async(pool, fun, args_list,
as_tuple=True,
**kw):
if as_tuple:
args_list = ((x,) for x in args_list)
it = itertools.izip(
itertools.cycle([fun]),
args_list)
it = itertools.imap(dill.dumps, it)
return pool.map_async(run_dill_encoded, it, **kw)
if __name__ == '__main__':
import multiprocessing as mp
import sys,os
p = mp.Pool(4)
res = dill_map_async(p, lambda x:[sys.stdout.write('%s\n'%os.getpid()),x][-1],
[lambda x:x+1]*10,)
res = res.get(timeout=100)
res = map(dill.loads,res)
print(res)
In the default installation, call a page that doesn't exist and you get an error with the version at the end:
Object not found!
The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
10/03/08 14:41:45
Apache/2.2.8 (Win32) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5
Well, we have few good answers here for resizing image, but I just modify as per my need. hope this help someone like me.
My Requirement was
if (originalImage.size.width > 1920)
{
CGSize newSize;
newSize.width = 1920;
newSize.height = (1920 * originalImage.size.height) / originalImage.size.width;
originalImage = [ProfileEditExperienceViewController imageWithImage:originalImage scaledToSize:newSize];
}
if (originalImage.size.height > 1080)
{
CGSize newSize;
newSize.width = (1080 * originalImage.size.width) / originalImage.size.height;
newSize.height = 1080;
originalImage = [ProfileEditExperienceViewController imageWithImage:originalImage scaledToSize:newSize];
}
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize
{
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Thanks to @Srikar Appal , for resizing I have used his method.
You may like to check this as well for resize calculation.
Try CSS:
<h2 style="color:#069">Process Report</h2>
If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:
<style type="text/css">
h2 {
color:#069;
}
</style>
var str = "xxx_456"; var str_sub = str.substr(str.lastIndexOf("_")+1);
If it is not always three digits at the end (and seperated by an underscore). If the end delimiter is not always an underscore, then you could use regex:
var pat = /([0-9]{1,})$/; var m = str.match(pat);
sentence.sub! 'Robert', 'Joe'
Won't cause an exception if the replaced word isn't in the sentence (the []=
variant will).
The above replaces only the first instance of "Robert".
To replace all instances use gsub
/gsub!
(ie. "global substitution"):
sentence.gsub! 'Robert', 'Joe'
The above will replace all instances of Robert with Joe.
I will like to answer this with numpy, great powerful array computation module in python.
Here is code snippet:
import numpy
a = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats',
'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and',
'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.',
'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats',
'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise',
'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle',
'Moon', 'to', 'rise.', '']
dict(zip(*numpy.unique(a, return_counts=True)))
Output
{'': 1, 'And': 2, 'Cats': 5, 'Jellicle': 6, 'Moon': 1, 'They': 1, 'airs': 1, 'and': 3, 'are': 3, 'black': 2, 'bright': 1, 'bright,': 1, 'caterwaul.': 1, 'cheerful': 1, 'eyes;': 1, 'faces,': 1, 'for': 1, 'graces': 1, 'have': 2, 'hear': 1, 'like': 1, 'merry': 1, 'pleasant': 1, 'practise': 1, 'rather': 1, 'rise.': 1, 'small;': 1, 'the': 1, 'their': 1, 'they': 1, 'to': 3, 'wait': 1, 'when': 1, 'white,': 1}
Output is in dictionary object in format of (key, value) pairs, where value is count of particular word
This answer is inspire by another answer on stackoverflow, you can view it here
It is session-based, when set the way you did in your question.
https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html
According to this, FOREIGN_KEY_CHECKS
is "Both" for scope. This means it can be set for session:
SET FOREIGN_KEY_CHECKS=0;
or globally:
SET GLOBAL FOREIGN_KEY_CHECKS=0;
I solved same problem using modRewrite.
AngularJS is reload page when after # changes.
But HTML5 mode remove # and invalid the reload.
So we should reload manually.
# install connect-modrewrite
$ sudo npm install connect-modrewrite --save
# gulp/build.js
'use strict';
var gulp = require('gulp');
var paths = gulp.paths;
var util = require('util');
var browserSync = require('browser-sync');
var modRewrite = require('connect-modrewrite');
function browserSyncInit(baseDir, files, browser) {
browser = browser === undefined ? 'default' : browser;
var routes = null;
if(baseDir === paths.src || (util.isArray(baseDir) && baseDir.indexOf(paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
browserSync.instance = browserSync.init(files, {
startPath: '/',
server: {
baseDir: baseDir,
middleware: [
modRewrite([
'!\\.\\w+$ /index.html [L]'
])
],
routes: routes
},
browser: browser
});
}
In my case I had a symlink for the 404'd file and my Tomcat was not configured to allow symlinks.
I know that it is not likely to be the cause for most people, but if you are desperate, check this possibility just in case.
assuming your project is maven based, add it to your POM:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
Save > Build > and test connection again. It works! Your actual mysql java connector version may vary.
When you use docker run
to start a container, it actually creates a new container based on the image you have specified.
Besides the other useful answers here, note that you can restart an existing container after it exited and your changes are still there.
docker start f357e2faab77 # restart it in the background
docker attach f357e2faab77 # reattach the terminal & stdin
Using only CSS it is not possible at all to add links :) It is not possible to link a background-image, nor a part of it, using HTML/CSS. However, it can be staged using this method:
<div class="wrapWithBackgroundImage">
<a href="#" class="invisibleLink"></a>
</div>
.wrapWithBackgroundImage {
background-image: url(...);
}
.invisibleLink {
display: block;
left: 55px; top: 55px;
position: absolute;
height: 55px width: 55px;
}
Echo inside an HTML element with class
and style the element:
echo "<span class='name'>" . $ip['cityName'] . "</span>";
why do these two different operators, [ ]
, and [[ ]]
, return the same result?
x = list(1, 2, 3, 4)
[ ]
provides sub setting operation. In general sub set of any object
will have the same type as the original object. Therefore, x[1]
provides a list. Similarly x[1:2]
is a subset of original list,
therefore it is a list. Ex.
x[1:2]
[[1]] [1] 1
[[2]] [1] 2
[[ ]]
is for extracting an element from the list. x[[1]]
is valid
and extract the first element from the list. x[[1:2]]
is not valid as [[ ]]
does not provide sub setting like [ ]
.
x[[2]] [1] 2
> x[[2:3]] Error in x[[2:3]] : subscript out of bounds
I only wanted to change the label color when it is lifted to top. But setting textColorHint
changes the color at every state. So, this worked for me:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
...
<item name="colorControlActivated">@color/colorPrimary</item>
...
</style>
This will change the color when the input is focused.
I had this error recently. Turns out that my cookie settings were incorrect in config.yml. Adding the cookie_path
and cookie_domain
settings to framework.session
fixed it.
First of all, input
element shouldn't have a closing tag (from http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT : End tag: forbidden
).
Second thing, you need the after()
, not append()
function.
/b
parameterstart /b "" "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch
In that case you should use ListBox
control instead of dropdown and Set the SelectionMode
property to Multiple
<asp:ListBox runat="server" SelectionMode="Multiple" >
<asp:ListItem Text="test1"></asp:ListItem>
<asp:ListItem Text="test2"></asp:ListItem>
<asp:ListItem Text="test3"></asp:ListItem>
</asp:ListBox>
Transactions are intended to run completely or not at all. The only way to complete a transaction is to commit, any other way will result in a rollback.
Therefore, if you begin and then not commit, it will be rolled back on connection close (as the transaction was broken off without marking as complete).
If it's a password used for authentication by your application, then hash the password as others suggest.
If you're storing passwords for an external resource, you'll often want to be able to prompt the user for these credentials and give him the opportunity to save them securely. Windows provides the Credentials UI (CredUI) for this purpose - there are a number of samples showing how to use this in .NET, including this one on MSDN.
To connect from Terminal to AWS AMI:
chmod 400 mykey.pem
ssh -i mykey.pem [email protected]
I had the same in IIS 10.
I fixed it by importing the .pfx file using IIS manager.
Select server root (above the sites-node), click 'Server Certificates' in the right hand pane and import pfx there. Then I could select it from the dropdown when creating ssl binding for a website under sites
Use extend to add a list comprehension to the end.
l.extend([x for i in range(100)])
See the Python docs for more information.
I'm trying to learn how to do this myself, and it seems you can install the library like this:
cmake_minimum_required(VERSION 2.4.0)
project(mycustomlib)
# Find source files
file(GLOB SOURCES src/*.cpp)
# Include header files
include_directories(include)
# Create shared library
add_library(${PROJECT_NAME} SHARED ${SOURCES})
# Install library
install(TARGETS ${PROJECT_NAME} DESTINATION lib/${PROJECT_NAME})
# Install library headers
file(GLOB HEADERS include/*.h)
install(FILES ${HEADERS} DESTINATION include/${PROJECT_NAME})
Scanner's buffer full when we take a input string through scan.nextLine(); so it skips the input next time . So solution is that we can create a new object of Scanner , the name of the object can be same as previous object......
Try looking at the return value of execute
, which is TRUE
on success, and FALSE
on failure.
I had this same problem, because my line of code was:
txtTotalInvoice.setText(var1.divide(var2).doubleValue() + "");
I change to this, reading previous Answer, because I was not writing decimal precision:
txtTotalInvoice.setText(var1.divide(var2,4, RoundingMode.HALF_UP).doubleValue() + "");
4 is Decimal Precison
AND RoundingMode are Enum constants, you could choose any of this
UP, DOWN, CEILING, FLOOR, HALF_DOWN, HALF_EVEN, HALF_UP
In this Case HALF_UP, will have this result:
2.4 = 2
2.5 = 3
2.7 = 3
You can check the RoundingMode
information here: http://www.javabeat.net/precise-rounding-of-decimals-using-rounding-mode-enumeration/
You could use negative lookahead, or something like this:
^([^A]|A([^B]|B([^C]|$)|$)|$).*$
Maybe it could be simplified a bit.
Comilation error is due arguments are not properly provided, replaceFirst accepts regx as initial arg. [a-z]{1} will match string of simple alpha characters of length 1.
Try this.
betterIdea = userIdea.replaceFirst("[a-z]{1}", userIdea.substring(0,1).toUpperCase())
For future googlers, FYI, the method in the answer by @meder , can be used with any element that has a name attribute, so lets say theres an <iframe>
with the name xyz
then you can use the rule as belows.
iframe[name=xyz] {
display: none;
}
The name
attribute can be used on the following elements:
<button>
<fieldset>
<form>
<iframe>
<input>
<keygen>
<map>
<meta>
<object>
<output>
<param>
<select>
<textarea>
Put it in a separate, custom header.
Overloading the standard HTTP headers is probably going to cause more confusion than it's worth, and will violate the principle of least surprise. It might also lead to interoperability problems for your API client programmers who want to use off-the-shelf tool kits that can only deal with the standard form of typical HTTP headers (such as Authorization
).
You can use the auto_now
and auto_now_add
options for updated_at
and created_at
respectively.
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
Note that Gene Burinsky's answer (at the time of writing the selected answer) keeps the first of each duplicated column. To keep the last:
df=df.loc[:, ~df.columns[::-1].duplicated()[::-1]]
I was using CakePHP and I was seeing this error:
This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500
I went to see the CakePHP Debug Level defined at app\config\core.php:
/**
* CakePHP Debug Level:
*
* Production Mode:
* 0: No error messages, errors, or warnings shown. Flash messages redirect.
*
* Development Mode:
* 1: Errors and warnings shown, model caches refreshed, flash messages halted.
* 2: As in 1, but also with full debug messages and SQL output.
* 3: As in 2, but also with full controller dump.
*
* In production mode, flash messages redirect after a time interval.
* In development mode, you need to click the flash message to continue.
*/
Configure::write('debug', 0);
I chanted the value from 0 to 1:
Configure::write('debug', 1);
After this change, when trying to reload the page again, I saw the corresponding error:
Fatal error: Uncaught Exception: Facebook needs the CURL PHP extension.
Conclusion: The solution in my case to see the errors was to change the CakePHP Debug Level from 0 to 1 in order to show errors and warnings.
Using RxJs, you can declare a Subject
in your parent component and pass it as Observable
to child component, child component just need to subscribe to this Observable
.
Parent-Component
eventsSubject: Subject<void> = new Subject<void>();
emitEventToChild() {
this.eventsSubject.next();
}
Parent-HTML
<child [events]="eventsSubject.asObservable()"> </child>
Child-Component
private eventsSubscription: Subscription;
@Input() events: Observable<void>;
ngOnInit(){
this.eventsSubscription = this.events.subscribe(() => doSomething());
}
ngOnDestroy() {
this.eventsSubscription.unsubscribe();
}
raw_input is your helper here. From documentation -
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
So your code will basically look like this.
num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
n = raw_input("num :")
num_array.append(int(n))
print 'ARRAY: ',num_array
P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input
does not do any type checking, so you need to be careful...
setInterval
sets up a recurring timer. It returns a handle that you can pass into clearInterval
to stop it from firing:
var handle = setInterval(drawAll, 20);
// When you want to cancel it:
clearInterval(handle);
handle = 0; // I just do this so I know I've cleared the interval
On browsers, the handle is guaranteed to be a number that isn't equal to 0
; therefore, 0
makes a handy flag value for "no timer set". (Other platforms may return other values; NodeJS's timer functions return an object, for instance.)
To schedule a function to only fire once, use setTimeout
instead. It won't keep firing. (It also returns a handle you can use to cancel it via clearTimeout
before it fires that one time if appropriate.)
setTimeout(drawAll, 20);
Explicitly Target IE versions without hacks using HTML and CSS
Use this approach if you don't want hacks in your CSS. Add a browser-unique class to the <html>
element so you can select based on browser later.
Example
<!doctype html>
<!--[if IE]><![endif]-->
<!--[if lt IE 7 ]> <html lang="en" class="ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
<head></head>
<body></body>
</html>
Then in your CSS you can very strictly access your target browser.
Example
.ie6 body {
border:1px solid red;
}
.ie7 body {
border:1px solid blue;
}
For more information check out http://html5boilerplate.com/
Target IE versions with CSS "Hacks"
More to your point, here are the hacks that let you target IE versions.
Use "\9" to target IE8 and below.
Use "*" to target IE7 and below.
Use "_" to target IE6.
Example:
body {
border:1px solid red; /* standard */
border:1px solid blue\9; /* IE8 and below */
*border:1px solid orange; /* IE7 and below */
_border:1px solid blue; /* IE6 */
}
Update: Target IE10
IE10 does not recognize the conditional statements so you can use this to apply an "ie10" class to the <html>
element
<!doctype html>
<html lang="en">
<!--[if !IE]><!--><script>if (/*@cc_on!@*/false) {document.documentElement.className+=' ie10';}</script><!--<![endif]-->
<head></head>
<body></body>
</html>
These are the two options for Windows and Visual Studio users that share code with Mac or Linux users. For an extended explanation, read the gitattributes manual.
In your repo's .gitattributes
file add:
* text=auto
This will normalize all the files with LF
line endings in the repo.
And depending on your operating system (core.eol
setting), files in the working tree will be normalized to LF
for Unix based systems or CRLF
for Windows systems.
This is the configuration that Microsoft .NET repos use.
Example:
Hello\r\nWorld
Will be normalized in the repo always as:
Hello\nWorld
On checkout, the working tree in Windows will be converted to:
Hello\r\nWorld
On checkout, the working tree in Mac will be left as:
Hello\nWorld
Note: If your repo already contains files not normalized,
git status
will show these files as completely modified the next time you make any change on them, and it could be a pain for other users to merge their changes later. See refreshing a repository after changing line endings for more information.
If text
is unspecified in the .gitattributes
file, Git uses the core.autocrlf
configuration variable to determine if the file should be converted.
For Windows users, git config --global core.autocrlf true
is a great option because:
LF
line endings only when added to the repo. If there are files not normalized in the repo, this setting will not touch them.CRLF
line endings in the working directory.The problem with this approach is that:
autocrlf = input
, you will see a bunch of files with LF
line endings. Not a hazard for the rest of the team, because your commits will still be normalized with LF
line endings.core.autocrlf = false
, you will see a bunch of files with LF
line endings and you may introduce files with CRLF
line endings into the repo.autocrlf = input
and may get files with CRLF
file endings, probably from Windows users with core.autocrlf = false
.As a variant in the ComboBox SelectionChanged
event handler:
private void ComboBoxName_SelectionChanged(object send ...
{
string s = ComboBoxName.Items.GetItemAt(ComboBoxName.SelectedIndex).ToString();
}
In addition to other answers which helped me, you can also add to surrounding div. In my case this was for sign on with user Name/Password fields.
<div (keyup.enter)="login()" class="container-fluid">
A quick benchmark:
import collections
import itertools
def count_iter_items(iterable):
counter = itertools.count()
collections.deque(itertools.izip(iterable, counter), maxlen=0)
return next(counter)
def count_lencheck(iterable):
if hasattr(iterable, '__len__'):
return len(iterable)
d = collections.deque(enumerate(iterable, 1), maxlen=1)
return d[0][0] if d else 0
def count_sum(iterable):
return sum(1 for _ in iterable)
iter = lambda y: (x for x in xrange(y))
%timeit count_iter_items(iter(1000))
%timeit count_lencheck(iter(1000))
%timeit count_sum(iter(1000))
The results:
10000 loops, best of 3: 37.2 µs per loop
10000 loops, best of 3: 47.6 µs per loop
10000 loops, best of 3: 61 µs per loop
I.e. the simple count_iter_items is the way to go.
Adjusting this for python3:
61.9 µs ± 275 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
74.4 µs ± 190 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
82.6 µs ± 164 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
When you are building a basic asp.net website using webcontrols is a good idea when you want to be able to use your controls at more then one location in your website. Separating code from the layout ascx files will be holding the controls that are used to display the layout, the cs files that belong to the ascx files will be holding the code that fills those controls.
For some basic understanding of usercontrols you can try this website
/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g
(123) 456-7890
+(123) 456-7890
+(123)-456-7890
+(123) - 456-7890
+(123) - 456-78-90
123-456-7890
123.456.7890
1234567890
+31636363634
075-63546725
This is a very loose option and I prefer to keep it this way, mostly I use it in registration forms where the users need to add their phone number. Usually users have trouble with forms that enforce strict formatting rules, I prefer user to fill in the number and the format it in the display or before saving it to the database. http://regexr.com/3c53v
Just to add something noteworthy here. One can define methods of a templated class just fine in the implementation file when they are not function templates.
myQueue.hpp:
template <class T>
class QueueA {
int size;
...
public:
template <class T> T dequeue() {
// implementation here
}
bool isEmpty();
...
}
myQueue.cpp:
// implementation of regular methods goes like this:
template <class T> bool QueueA<T>::isEmpty() {
return this->size == 0;
}
main()
{
QueueA<char> Q;
...
}
You can use this option provided by dataTable itself using buttons.
dom: 'Bfrtip',
buttons: [
'selectAll',
'selectNone'
]'
Here is a sample code
var tableFaculty = $('#tableFaculty').DataTable({
"columns": [
{
data: function (row, type, set) {
return '';
}
},
{data: "NAME"}
],
"columnDefs": [
{
orderable: false,
className: 'select-checkbox',
targets: 0
}
],
select: {
style: 'multi',
selector: 'td:first-child'
},
dom: 'Bfrtip',
buttons: [
'selectAll',
'selectNone'
],
"order": [[0, 'desc']]
});
You could simply apply one of the bootstrap contextual background colors to the header row. In this case (blue background, white text): primary.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
<table class="table" >_x000D_
<tr class="bg-primary">_x000D_
<th>_x000D_
Firstname_x000D_
</th>_x000D_
<th>_x000D_
Surname_x000D_
</th>_x000D_
<th></th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>John</td>_x000D_
<td>Doe</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jane</td>_x000D_
<td>Roe</td>_x000D_
</tr>_x000D_
</table>
_x000D_
I wanted to make public once me too a google code fix and got the same error. Started with This video, but at Save and publish got an error. I have seen there are several question regarding to this. Some are Windows users, those are the most lucky, because usually no problems with permissions and some are Linux users.
I have a mac for mobile development use and very often meet this problems. The source for this problems is the "platform independent" solutions, which doesn't care enough for mac and they don't have access to keychain, where are stored the certificates, .pem files and so on.
All I wanted is to not make any environment settings, nor command line, just simple GUI based clicks, like a regular user.
Half part was done with Eclipse Git plugin, second part (push to Github) was done with Mac Github
Nice and easy :)
All can be done with with that native appp if I would start to learn it, I just need the push functionality from him.
Hoping it will help a mac user once.
I have done that the more simple way, not as clean as it should be but it was a quick hack
$htmlContent = file_get_contents('pageURL');
// read all image tags into an array
preg_match_all('/<img[^>]+>/i',$htmlContent, $imgTags);
for ($i = 0; $i < count($imgTags[0]); $i++) {
// get the source string
preg_match('/src="([^"]+)/i',$imgTags[0][$i], $imgage);
// remove opening 'src=' tag, can`t get the regex right
$origImageSrc[] = str_ireplace( 'src="', '', $imgage[0]);
}
// will output all your img src's within the html string
print_r($origImageSrc);
This will make the scroll bars always display when there is content within windows that must be scrolled to access, it applies to all windows and all apps on the Mac:
Launch System Preferences from the ? Apple menu Click on the “General” settings panel Look for ‘Show scroll bars’ and select the radiobox next to “Always” Close out of System Preferences when finished
Another approach could be using Array.prototype.forEach()
as
Array.from({_x000D_
length: 5_x000D_
}, () => Math.floor(Math.random() * 5)).forEach((val, index) => {_x000D_
console.log(val, index)_x000D_
})
_x000D_
This is pretty much the complete list of keyCodes:
3: "break",
8: "backspace / delete",
9: "tab",
12: 'clear',
13: "enter",
16: "shift",
17: "ctrl",
18: "alt",
19: "pause/break",
20: "caps lock",
27: "escape",
28: "conversion",
29: "non-conversion",
32: "spacebar",
33: "page up",
34: "page down",
35: "end",
36: "home ",
37: "left arrow ",
38: "up arrow ",
39: "right arrow",
40: "down arrow ",
41: "select",
42: "print",
43: "execute",
44: "Print Screen",
45: "insert ",
46: "delete",
48: "0",
49: "1",
50: "2",
51: "3",
52: "4",
53: "5",
54: "6",
55: "7",
56: "8",
57: "9",
58: ":",
59: "semicolon (firefox), equals",
60: "<",
61: "equals (firefox)",
63: "ß",
64: "@ (firefox)",
65: "a",
66: "b",
67: "c",
68: "d",
69: "e",
70: "f",
71: "g",
72: "h",
73: "i",
74: "j",
75: "k",
76: "l",
77: "m",
78: "n",
79: "o",
80: "p",
81: "q",
82: "r",
83: "s",
84: "t",
85: "u",
86: "v",
87: "w",
88: "x",
89: "y",
90: "z",
91: "Windows Key / Left ? / Chromebook Search key",
92: "right window key ",
93: "Windows Menu / Right ?",
96: "numpad 0 ",
97: "numpad 1 ",
98: "numpad 2 ",
99: "numpad 3 ",
100: "numpad 4 ",
101: "numpad 5 ",
102: "numpad 6 ",
103: "numpad 7 ",
104: "numpad 8 ",
105: "numpad 9 ",
106: "multiply ",
107: "add",
108: "numpad period (firefox)",
109: "subtract ",
110: "decimal point",
111: "divide ",
112: "f1 ",
113: "f2 ",
114: "f3 ",
115: "f4 ",
116: "f5 ",
117: "f6 ",
118: "f7 ",
119: "f8 ",
120: "f9 ",
121: "f10",
122: "f11",
123: "f12",
124: "f13",
125: "f14",
126: "f15",
127: "f16",
128: "f17",
129: "f18",
130: "f19",
131: "f20",
132: "f21",
133: "f22",
134: "f23",
135: "f24",
144: "num lock ",
145: "scroll lock",
160: "^",
161: '!',
163: "#",
164: '$',
165: 'ù',
166: "page backward",
167: "page forward",
169: "closing paren (AZERTY)",
170: '*',
171: "~ + * key",
173: "minus (firefox), mute/unmute",
174: "decrease volume level",
175: "increase volume level",
176: "next",
177: "previous",
178: "stop",
179: "play/pause",
180: "e-mail",
181: "mute/unmute (firefox)",
182: "decrease volume level (firefox)",
183: "increase volume level (firefox)",
186: "semi-colon / ñ",
187: "equal sign ",
188: "comma",
189: "dash ",
190: "period ",
191: "forward slash / ç",
192: "grave accent / ñ / æ",
193: "?, / or °",
194: "numpad period (chrome)",
219: "open bracket ",
220: "back slash ",
221: "close bracket / å",
222: "single quote / ø",
223: "`",
224: "left or right ? key (firefox)",
225: "altgr",
226: "< /git >",
230: "GNOME Compose Key",
231: "ç",
233: "XF86Forward",
234: "XF86Back",
240: "alphanumeric",
242: "hiragana/katakana",
243: "half-width/full-width",
244: "kanji",
255: "toggle touchpad"
So, we have a project with one solution that contains several projects that have assemblies with different version numbers.
After investigating several of the above methods, I just implemented a build step to run a Powershell script that does a find-and-replace on the AssemblyInfo.cs file. I still use the 1.0.* version number in source control, and Jenkins just manually updates the version number before msbuild runs.
dir **/Properties/AssemblyInfo.cs | %{ (cat $_) | %{$_ -replace '^(\s*)\[assembly: AssemblyVersion\("(.*)\.\*"\)', "`$1[assembly: AssemblyVersion(`"`$2.$build`")"} | Out-File $_ -Encoding "UTF8" }
dir **/Properties/AssemblyInfo.cs | %{ (cat $_) | %{$_ -replace '^(\s*)\[assembly: AssemblyFileVersion\("(.*)\.\*"\)', "`$1[assembly: AssemblyFileVersion(`"`$2.$build`")"} | Out-File $_ -Encoding "UTF8" }
I added the -Encoding "UTF8" option because git started treating the .cs file as binary files if I didn't. Granted, this didn't matter, since I never actually commit the result; it just came up as I was testing.
Our CI environment already has a facility to associate the Jenkins build with the particular git commit (thanks Stash plugin!), so I don't worry that there's no git commit with the version number attached to it.
The easiest way is start the simulator from the Xcode
, and then on the dock, Ctrl
+ Click
on the icon and select Keep in Dock
Just for the sake of completeness: there are IPv4-mapped IPv6 addresses, where you can embed an IPv4 address in an IPv6 address (may not be supported by every IPv6 equipment).
Example: I run a server on my machine, which can be accessed via http://127.0.0.1:19983/solr
. If I access it via an IPv4-mapped IPv6 address then I access it via http://[::ffff:127.0.0.1]:19983/solr
(which will be converted to http://[::ffff:7f00:1]:19983/solr
)
jQuery('#testID2').find('.test2').replaceWith('.test3');
Semantically, you are selecting the element with the ID testID2
, then you are looking for any descendent elements with the class test2
(does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3
) that also do not exist.
You need to do this:
jQuery('#testID2').addClass('test3').removeClass('test2');
This selects the element with the ID testID2
, then adds the class test3
to it. Last, it removes the class test2
from that element.
I know this is a very old post but this may help someone:
You can create a method, so whenever you need to pause you can type pause(1000)
or any other millisecond value:
public static void pause(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
System.err.format("IOException: %s%n", e);
}
}
This is inserted just above the public static void main(String[] args)
, inside the class. Then, to call on the method, type pause(ms)
but replace ms
with the number of milliseconds to pause. That way, you don't have to insert the entire try-catch statement whenever you want to pause.
Try something like this:
Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bmp.recycle();
This answer is late but it might help someone like it helped me
Just ensure you have given the user permission for the destination file
sudo chown -R www-data:www-data /Users/George/Desktop/uploads/
For me the following lines of code did the trick
mysqldump --quote-names -q -u username1 --password='password1' originalDB | mysql -u username2 --password='password2' duplicateDB
From SDK:
Cancelling a task
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true.
After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.
To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)
So your code is right for dialog listener:
uploadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
myTask.cancel(true);
//finish();
}
});
Now, as I have mentioned earlier from SDK, you have to check whether the task is cancelled or not, for that you have to check isCancelled() inside the onPreExecute() method.
For example:
if (isCancelled())
break;
else
{
// do your work here
}
To contribute with something new here, I'd like to share the link of my article that Conceptualize REST through a practical and objective approach.
I'm covering main concepts such as:
I've created a GitHub project as well that you can run easily with docker, which covers the content that I've presented in this article.
https://itnext.io/how-to-build-a-restful-api-a-deep-dive-into-rest-apis-215188f80854
str.append(10u,'d'); //appends character d 10 times
Notice I have written 10u and not 10 for the number of times I'd like to append the character; replace 10 with whatever number.
Get all distinct id
, name
and address
columns and count the resulting rows.
SELECT COUNT(*) FROM mytable GROUP BY id, name, address
How to Bold entire row 10 example:
workSheet.Cells[10, 1].EntireRow.Font.Bold = true;
More formally:
Microsoft.Office.Interop.Excel.Range rng = workSheet.Cells[10, 1] as Xl.Range;
rng.EntireRow.Font.Bold = true;
How to Bold Specific Cell 'A10' for example:
workSheet.Cells[10, 1].Font.Bold = true;
Little more formal:
int row = 1;
int column = 1; /// 1 = 'A' in Excel
Microsoft.Office.Interop.Excel.Range rng = workSheet.Cells[row, column] as Xl.Range;
rng.Font.Bold = true;
You may be able to approximate the size by pretending to serializing it with a binary serializer (but routing the output to oblivion) if you're working with serializable objects.
class Program
{
static void Main(string[] args)
{
A parent;
parent = new A(1, "Mike");
parent.AddChild("Greg");
parent.AddChild("Peter");
parent.AddChild("Bobby");
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
SerializationSizer ss = new SerializationSizer();
bf.Serialize(ss, parent);
Console.WriteLine("Size of serialized object is {0}", ss.Length);
}
}
[Serializable()]
class A
{
int id;
string name;
List<B> children;
public A(int id, string name)
{
this.id = id;
this.name = name;
children = new List<B>();
}
public B AddChild(string name)
{
B newItem = new B(this, name);
children.Add(newItem);
return newItem;
}
}
[Serializable()]
class B
{
A parent;
string name;
public B(A parent, string name)
{
this.parent = parent;
this.name = name;
}
}
class SerializationSizer : System.IO.Stream
{
private int totalSize;
public override void Write(byte[] buffer, int offset, int count)
{
this.totalSize += count;
}
public override bool CanRead
{
get { return false; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override void Flush()
{
// Nothing to do
}
public override long Length
{
get { return totalSize; }
}
public override long Position
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
}
Another solution here but only for the virtual box of windows 10 to test explorer. ssh user: IEUser ssh pass:Passw0rd!
Tables work differently; sometimes counter-intuitively.
The solution is to use width
on the table cells instead of max-width
.
Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.
I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.
table {_x000D_
width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
min-width: 10px;_x000D_
width: 20px;_x000D_
max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
min-width: 40px;_x000D_
width: 45px;_x000D_
max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="a">A</td>_x000D_
<td class="b">B</td>_x000D_
<td class="c">C</td>_x000D_
</tr>_x000D_
</table>
_x000D_
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
<input type="text" id="inputName" placeholder="Enter name" required oninvalid="this.setCustomValidity('Your Message')" oninput="this.setCustomValidity('') />
this can help you even more better, Fast, Convenient & Easiest.
Variables set at the root-scope are available to the controller scope via prototypical inheritance.
Here is a modified version of @Nitish's demo that shows the relationship a bit clearer: http://jsfiddle.net/TmPk5/6/
Notice that the rootScope's variable is set when the module initializes, and then each of the inherited scope's get their own copy which can be set independently (the change
function). Also, the rootScope's value can be updated too (the changeRs
function in myCtrl2
)
angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
})
.controller('myCtrl2', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.changeRs = function() {
$rootScope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
});
private void button1_Click( object sender, EventArgs e )
{
string s = @"p1=6&p2=7&p3=8";
NameValueCollection nvc = new NameValueCollection();
foreach ( string vp in Regex.Split( s, "&" ) )
{
string[] singlePair = Regex.Split( vp, "=" );
if ( singlePair.Length == 2 )
{
nvc.Add( singlePair[ 0 ], singlePair[ 1 ] );
}
}
}
Open up Keyboard preferences and click modifier keys... you can change the caps lock key to control, option, escape, or command.
So my question is: Is there a way to tell the compiler that a long long int is the also a int64_t, just like long int is?
This is a good question or problem, but I suspect the answer is NO.
Also, a long int
may not be a long long int
.
# if __WORDSIZE == 64 typedef long int int64_t; # else __extension__ typedef long long int int64_t; # endif
I believe this is libc. I suspect you want to go deeper.
In both 32-bit compile with GCC (and with 32- and 64-bit MSVC), the output of the program will be:
int: 0 int64_t: 1 long int: 0 long long int: 1
32-bit Linux uses the ILP32 data model. Integers, longs and pointers are 32-bit. The 64-bit type is a long long
.
Microsoft documents the ranges at Data Type Ranges. The say the long long
is equivalent to __int64
.
However, the program resulting from a 64-bit GCC compile will output:
int: 0 int64_t: 1 long int: 1 long long int: 0
64-bit Linux uses the LP64
data model. Longs are 64-bit and long long
are 64-bit. As with 32-bit, Microsoft documents the ranges at Data Type Ranges and long long is still __int64
.
There's a ILP64
data model where everything is 64-bit. You have to do some extra work to get a definition for your word32
type. Also see papers like 64-Bit Programming Models: Why LP64?
But this is horribly hackish and does not scale well (actual functions of substance, uint64_t, etc)...
Yeah, it gets even better. GCC mixes and matches declarations that are supposed to take 64 bit types, so its easy to get into trouble even though you follow a particular data model. For example, the following causes a compile error and tells you to use -fpermissive
:
#if __LP64__
typedef unsigned long word64;
#else
typedef unsigned long long word64;
#endif
// intel definition of rdrand64_step (http://software.intel.com/en-us/node/523864)
// extern int _rdrand64_step(unsigned __int64 *random_val);
// Try it:
word64 val;
int res = rdrand64_step(&val);
It results in:
error: invalid conversion from `word64* {aka long unsigned int*}' to `long long unsigned int*'
So, ignore LP64
and change it to:
typedef unsigned long long word64;
Then, wander over to a 64-bit ARM IoT gadget that defines LP64
and use NEON:
error: invalid conversion from `word64* {aka long long unsigned int*}' to `uint64_t*'
I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
It's written as:
def my_function(self, param_one=None): # Or custom sentinel if None is vaild
if param_one is None:
param_one = self.one_of_the_vars
And I think it's safe to say that will never happen in Python due to the nature that self
doesn't really exist until the function starts... (you can't reference it, in its own definition - like everything else)
For example: you can't do d = {'x': 3, 'y': d['x'] * 5}
Why does it have to be encoded? A request looks like this:
GET /url HTTP/1.1
(Ignoring headers)
There are 3 fields separated by a white space. If you put a space in your url:
GET /url end_url HTTP/1.1
You know have 4 fields, the HTTP server will tell you it is an invalid request.
GET /url%20end_url HTTP/1.1
3 fields => valid
Note: in the query string (after ?), a space is usually encoded as a +
GET /url?var=foo+bar HTTP/1.1
rather than
GET /url?var=foo%20bar HTTP/1.1
Maximum time between connection request and a timeout error. When the client tries to make a connection, if the timeout wait limit is reached, it will stop trying and raise an error.
Click Your app from Xcode Under Targets. (Under project.) Here you see Summary info, build settings, Build phases, build rules.
Okay go to Build Settings. Go down to Code Signing.
You see you have two fields Debug and Release. You have two profiles to choose from in each of those fields, Distributing and developing.
Let distributing be the one from the Release field. Let Developing be the one from the Debug field.
Doing this solved this problem, and let that error message go away. Now I can run my application fine.
if you follow
UPDATE table SET name = NULL
then name is "" not NULL IN MYSQL means your query
SELECT * FROM table WHERE name = NULL
not work or disappoint yourself
You are probably looking for get_attribute()
. An example is shown here as well
def test_chart_renders_from_url(self):
url = 'http://localhost:8000/analyse/'
self.browser.get(url)
org = driver.find_element_by_id('org')
# Find the value of org?
val = org.get_attribute("attribute name")
systemd
sudo systemctl stop mysqld.service && sudo yum remove -y mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf
sysvinit
sudo service mysql stop && sudo apt-get remove mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf
extension UITapGestureRecognizer {
func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: CGSize.zero)
let textStorage = NSTextStorage(attributedString: label.attributedText!)
// Configure layoutManager and textStorage
layoutManager.addTextContainer(textContainer)
textStorage.addLayoutManager(layoutManager)
// Configure textContainer
textContainer.lineFragmentPadding = 0.0
textContainer.lineBreakMode = label.lineBreakMode
textContainer.maximumNumberOfLines = label.numberOfLines
textContainer.size = label.bounds.size
// main code
let locationOfTouchInLabel = self.location(in: label)
let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInLabel, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
let indexOfCharacterRange = NSRange(location: indexOfCharacter, length: 1)
let indexOfCharacterRect = layoutManager.boundingRect(forGlyphRange: indexOfCharacterRange, in: textContainer)
let deltaOffsetCharacter = indexOfCharacterRect.origin.x + indexOfCharacterRect.size.width
if locationOfTouchInLabel.x > deltaOffsetCharacter {
return false
} else {
return NSLocationInRange(indexOfCharacter, targetRange)
}
}
}
In development, activating a Spring Boot profile when a specific Maven profile is activate is straight. You should use the profiles
property of the spring-boot-maven-plugin in the Maven profile such as :
<project>
<...>
<profiles>
<profile>
<id>development</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<profiles>
<profile>development</profile>
</profiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profiles>
</...>
</project>
You can run the following command to use both the Spring Boot and the Maven development
profile :
mvn spring-boot:run -Pdevelopment
If you want to be able to map any Spring Boot profiles to a Maven profile with the same profile name, you could define a single Maven profile and enabling that as the presence of a Maven property is detected. This property would be the single thing that you need to specify as you run the mvn
command.
The profile would look like :
<profile>
<id>spring-profile-active</id>
<activation>
<property>
<name>my.active.spring.profiles</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<profiles>
<profile>${my.active.spring.profiles}</profile>
</profiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
And you can run the following command to use both the Spring Boot and the Maven development
profile :
mvn spring-boot:run -Dmy.active.spring.profiles=development
or :
mvn spring-boot:run -Dmy.active.spring.profiles=integration
or :
mvn spring-boot:run -Dmy.active.spring.profiles=production
And so for...
This kind of configuration makes sense as in the generic Maven profile you rely on the my.active.spring.profiles
property that is passed to perform some tasks or value some things.
For example I use this way to configure a generic Maven profile that packages the application and build a docker image specific to the environment selected.
Now that it's 2018 here's a quick and simple method.
This will add an event listener, but if it already fired we'll check that the dom is in a ready state or that it's complete. This can fire before or after sub-resources have finished loading (images, stylesheets, frames, etc).
function domReady(fn) {_x000D_
// If we're early to the party_x000D_
document.addEventListener("DOMContentLoaded", fn);_x000D_
// If late; I mean on time._x000D_
if (document.readyState === "interactive" || document.readyState === "complete" ) {_x000D_
fn();_x000D_
}_x000D_
}_x000D_
_x000D_
domReady(() => console.log("DOM is ready, come and get it!"));
_x000D_
Here's some quick utility helpers using standard ES6 Import & Export I wrote that include TypeScript as well. Maybe I can get around to making these a quick library that can be installed into projects as a dependency.
export const domReady = (callBack) => {
if (document.readyState === "loading") {
document.addEventListener('DOMContentLoaded', callBack);
}
else {
callBack();
}
}
export const windowReady = (callBack) => {
if (document.readyState === 'complete') {
callBack();
}
else {
window.addEventListener('load', callBack);
}
}
export const domReady = (callBack: () => void) => {
if (document.readyState === "loading") {
document.addEventListener('DOMContentLoaded', callBack);
}
else {
callBack();
}
}
export const windowReady = (callBack: () => void) => {
if (document.readyState === 'complete') {
callBack();
}
else {
window.addEventListener('load', callBack);
}
}
export const domReady = new Promise(resolve => {
if (document.readyState === "loading") {
document.addEventListener('DOMContentLoaded', resolve);
}
else {
resolve();
}
});
export const windowReady = new Promise(resolve => {
if (document.readyState === 'complete') {
resolve();
}
else {
window.addEventListener('load', resolve);
}
});
It depends on what the span is for. If it refers to the text of the link, and not the fact that it is a link, choose #1. If the span refers to the link as a whole, then choose #2. Unless you explain what the span represents, there's not much more of an answer than that. They're both inline elements, can be syntactically nested in any order.
For example: Add this data-attr to your primary slick div: data-space="7"
$('[data-space]').each(function () {
var $this = $(this),
$space = $this.attr('data-space');
$('.slick-slide').css({
marginLeft: $space + 'px',
marginRight: $space + 'px'
});
$('.slick-list').css({
marginLeft: -$space + 'px',
marginRight: -$space/2 + 'px'
})
});
To create a UNIQUE constraint on one or multiple columns when the table is already created, use the following SQL:
ALTER TABLE TableName ADd UNIQUE (ColumnName1,ColumnName2, ColumnName3, ...)
To allow naming of a UNIQUE constraint for above query
ALTER TABLE TableName ADD CONSTRAINT un_constaint_name UNIQUE (ColumnName1,ColumnName2, ColumnName3, ...)
The query supported by MySQL / SQL Server / Oracle / MS Access.
getchar() is a standard function that on many platforms requires you to press ENTER to get the input, because the platform buffers input until that key is pressed. Many compilers/platforms support the non-standard getch() that does not care about ENTER (bypasses platform buffering, treats ENTER like just another key).
You could do this with an INSTEAD OF INSERT
trigger on the table, that checks for the existance of the row and then updates/inserts depending on whether it exists already. There is an example of how to do this for SQL Server 2000+ on MSDN here:
CREATE TRIGGER IO_Trig_INS_Employee ON Employee
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
-- Check for duplicate Person. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT P.SSN
FROM Person P, inserted I
WHERE P.SSN = I.SSN))
INSERT INTO Person
SELECT SSN,Name,Address,Birthdate
FROM inserted
ELSE
-- Log attempt to insert duplicate Person row in PersonDuplicates table.
INSERT INTO PersonDuplicates
SELECT SSN,Name,Address,Birthdate,SUSER_SNAME(),GETDATE()
FROM inserted
-- Check for duplicate Employee. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT E.SSN
FROM EmployeeTable E, inserted
WHERE E.SSN = inserted.SSN))
INSERT INTO EmployeeTable
SELECT EmployeeID,SSN, Department, Salary
FROM inserted
ELSE
--If duplicate, change to UPDATE so that there will not
--be a duplicate key violation error.
UPDATE EmployeeTable
SET EmployeeID = I.EmployeeID,
Department = I.Department,
Salary = I.Salary
FROM EmployeeTable E, inserted I
WHERE E.SSN = I.SSN
END
I realize that this is an old question but perhaps someone will find my code sample useful. This code encodes a file in Base64 then decodes it and saves it in a new location.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.apache.commons.codec.binary.Base64;
public class Base64Example {
public static void main(String[] args) {
Base64Example tempObject = new Base64Example();
// convert file to regular byte array
byte[] codedFile = tempObject.convertFileToByteArray("your_input_file_path");
// encoded file in Base64
byte[] encodedFile = Base64.encodeBase64(codedFile);
// print out the byte array
System.out.println(Arrays.toString(encodedFile));
// print the encoded String
System.out.println(encodedFile);
// decode file back to regular byte array
byte[] decodedByteArray = Base64.decodeBase64(encodedFile);
// save decoded byte array to a file
boolean success = tempObject.saveFileFromByteArray("your_output_file_path", decodedByteArray);
// print out success
System.out.println("success : " + success);
}
public byte[] convertFileToByteArray(String filePath) {
Path path = Paths.get(filePath);
byte[] codedFile = null;
try {
codedFile = Files.readAllBytes(path);
} catch (IOException e) {
e.printStackTrace();
}
return codedFile;
}
public boolean saveFileFromByteArray(String filePath, byte[] decodedByteArray) {
boolean success = false;
Path path = Paths.get(filePath);
try {
Files.write(path, decodedByteArray);
success = true;
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
}
Short answer:
const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];
git revert HEAD -m 1
In the above code line. "Last argument represents"
or
git reset --hard siriwjdd
Ran into the same problem and was able to tweak the resize mode until I found something I was happy with. Alternative approaches include:
To prevent loss of quality while tweaking images consider working with vector graphics so you can experiment with different sizes easily. Inkscape is free tool and works well for this purpose.
Cygwin is an attempt to create a complete UNIX/POSIX environment on Windows. To do this it uses various DLLs. While these DLLs are covered by GPLv3+, their license contains an exception that does not force a derived work to be covered by the GPLv3+. MinGW is a C/C++ compiler suite which allows you to create Windows executables without dependency on such DLLs - you only need the normal MSVC runtimes, which are part of any normal Microsoft Windows installation.
You can also get a small UNIX/POSIX like environment, compiled with MinGW called MSYS. It doesn't have anywhere near all the features of Cygwin, but is ideal for programmers wanting to use MinGW.
Adding to Winnie's great answer,
If anyone is not able to find the postgresql.conf file location in your setup, you can always ask the postgres itself.
SHOW config_file;
For me changing the max_connections alone made the trick.
The WHERE
clause is evaluated after the JOIN
conditions have been processed.
Why not just do this take 010010001001001 split it into two bits 8 letter each (01001000, 01001001). Then issue the powers
01001000. 01001001.
The first 8 ignore the first three they determine if it's capital or not, the go right to left doing powers of 2 (2^1, 2^2 2^3 2^4 2^5). So then add all the ones up , there's only one, and it = 8, and te eight letter in the alphabet is h so our first bit is the letter h, try it on the other bit
IF you want to filter with NOT IN for a subquery containg NULLs justcheck for not null
SELECT blah FROM t WHERE blah NOT IN
(SELECT someotherBlah FROM t2 WHERE someotherBlah IS NOT NULL )
If you use make generators like cmake, JUCE, etc. try to set a correct VS version target (2013, 2015, 2017) and regenerate the solution again.
Try this. It works with me. Hope you too!
List<YOUR_OBJECT> testList = new ArrayList<>();_x000D_
testList.add(test1);_x000D_
_x000D_
Gson gson = new Gson();_x000D_
_x000D_
String json = gson.toJson(testList);_x000D_
_x000D_
Type type = new TypeToken<ArrayList<YOUR_OBJECT>>(){}.getType();_x000D_
_x000D_
ArrayList<YOUR_OBJECT> array = gson.fromJson(json, type);
_x000D_
Use output buffering:
<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>
You must detach your entity from session before modifying its ID fields
Since id is an attribute don't create an id element, just do this:
myPara.setAttribute("id", "id_you_like");
<form class="col-xs-12" method="post" action="/News/AddNews" enctype="multipart/form-data">
<div class="form-group">
<input type="file" class="form-control" name="image" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary col-xs-12">Add</button>
</div>
</form>
My Action Is
[HttpPost]
public IActionResult AddNews(IFormFile image)
{
Tbl_News tbl_News = new Tbl_News();
if (image!=null)
{
//Set Key Name
string ImageName= Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);
//Get url To Save
string SavePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot/img",ImageName);
using(var stream=new FileStream(SavePath, FileMode.Create))
{
image.CopyTo(stream);
}
}
return View();
}
m <- matrix(1:20, ncol = 4)
colnames(m) <- letters[1:4]
The following command will select the first row of the matrix above.
subset(m, m[,4] == 16)
And this will select the last three.
subset(m, m[,4] > 17)
The result will be a matrix in both cases. If you want to use column names to select columns then you would be best off converting it to a dataframe with
mf <- data.frame(m)
Then you can select with
mf[ mf$a == 16, ]
Or, you could use the subset command.
https://www.youtube.com/watch?v=QjtW-wnXlUY&t=38s
Follow as in the url
This is how i do : 1) create an app.py in Sublime Text or Pycharm, or whatever the ide, and in that app.py have this code
from flask import Flask
app = Flask(__name__)
@app.route('/')
def helloWorld():
return'<h1>Hello!</h1>'
This is a very basic program to printout a hello , to test flask is working.I would advise to create app.py in a new folder, then locate where the folder is on command prompt enter image description here type in these line of codes on command prompt
>py -m venv env
>env\Scripts\activate
>pip install flask
Then
>set FLASK_APP=app.py
>flask run
Then press enter all will work
The name of my file is app.py, give the relevant name as per your file in code line
set FLASK_APP=app.py
Also if your python path is not set, in windows python is in AppData folder its hidden, so first have to view it and set the correct path under environment variables. This is how you reach environment variables
Control panel ->> system and security ->> system ->> advanced system setting
Then in system properties you get environment variables
I use it like this:
switch (true){
case /Pressure/.test(sensor):
{
console.log('Its pressure!');
break;
}
case /Temperature/.test(sensor):
{
console.log('Its temperature!');
break;
}
}
var sample_data = '';
$.getJSON("sample.json", function (data) {
sample_data = data;
$.each(data, function (key, value) {
console.log(sample_data);
});
});
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
connection = DriverManager.getConnection("jdbc:oracle:thin:@machinename:portnum:schemaname","userid","password");
If the javascript file is loaded from the admin dashboard, this javascript function will give you the root of your WordPress installation. I use this a lot when I'm building plugins that need to make ajax requests from the admin dashboard.
function getHomeUrl() {
var href = window.location.href;
var index = href.indexOf('/wp-admin');
var homeUrl = href.substring(0, index);
return homeUrl;
}
I ran into the same situation where when I copied the formula to another cell the formula was still referencing the cell used in the first formula. To correct this when you set up the rules, select the option "use a formula to determine which cells to format. Then type in the box your formula, for example H23*.25. When you copy the cells down the formulas will change to H24*.25, H25*.25 and so on. Hope this helps.
Like this:
String[][] arrays = { array1, array2, array3, array4, array5 };
or
String[][] arrays = new String[][] { array1, array2, array3, array4, array5 };
(The latter syntax can be used in assignments other than at the point of the variable declaration, whereas the shorter syntax only works with declarations.)
Check this out, you may like it (previously, please, clone table1 to table2):
table1.AsEnumerable().Take(recodCount).CopyToDataTable(table2,LoadOption.OverwriteChanges);
Or:
table1.AsEnumerable().Where ( yourcondition ) .CopyToDataTable(table2,LoadOption.OverwriteChanges);
Use colSds
function from matrixStats
library.
library(matrixStats)
set.seed(42)
M <- matrix(rnorm(40),ncol=4)
colSds(M)
[1] 0.8354488 1.6305844 1.1560580 1.1152688
I think that the reason for this warning is config in Pycharm. You can uncheck the selection Method may be static in Editor->Inspection
Create a function anywhere in your project and simply call that function where ever you need it.
Guys you got to remember that you guys are calling active threads that you are not calling asynchronously and since it would likely be a good 5 to 10 pages to get it done right. Why not spend more time on your project and forget about writing anything already written. Properly
//Adding a static modifier would make this accessible anywhere in your app
public Logger getLogger()
{
return java.util.logging.Logger.getLogger("MyLogFileName");
}
//call the method anywhere and append what you want to log
//Logger class will take care of putting timestamps for you
//plus the are ansychronously done so more of the
//processing power will go into your application
//from inside a function body in the same class ...{...
getLogger().log(Level.INFO,"the text you want to append");
...}...
/*********log file resides in server root log files********/
three lines of code two really since the third actually appends text. :P
You can cast a method group into a delegate.
The delegate signature selects 1 method out of the group.
This example picks the ToString()
overload which takes a string parameter:
Func<string,string> fn = 123.ToString;
Console.WriteLine(fn("00000000"));
This example picks the ToString()
overload which takes no parameters:
Func<string> fn = 123.ToString;
Console.WriteLine(fn());