table{
height:1px;
}
table > td{
height:100%;
}
table > td > .inner{
height:100%;
}
Confirmed working on:
Use
jQuery(document).
instead of
$(document).
or
Within the function, $ points to jQuery as you would expect
(function ($) {
$(document).
}(jQuery));
In Chart.js version 2.0, it is possible to set labels for axes:
options = {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
See Labelling documentation for more details.
Services
Syntax: module.service( 'serviceName', function ); Result: When declaring serviceName as an injectable argument you will be provided the actual function reference passed to module.service.
Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference. Could also be run with injectedArg.call( this ) or similar.
Factories
Syntax: module.factory( 'factoryName', function );
Result: When declaring factoryName as an injectable argument you will be provided the value that is returned by invoking the function reference passed to module.factory.
Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.
Providers
Syntax: module.provider( 'providerName', function );
Result: When declaring providerName as an injectable argument you will be provided the value that is returned by invoking the $get method of the function reference passed to module.provider.
Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances but that requires some sort of configuration before being injected. Perhaps useful for classes that are reusable across projects? Still kind of hazy on this one.
Use single forward slash and always type the path manually. For example:
FileInputStream fi= new FileInputStream("D:/excelfiles/myxcel.xlsx");
Note: This answer covers several versions of Chrome, scroll to see v52, v48, v46, v43 and v42 each with their updated changes.
Assuming you are just using Set
temporarily to get unique values in an array and then converting back to an Array, try using this:
_.uniq([])
This relies on using underscore or lo-dash.
Old question, but hopefully this'll help someone else.
In my case I was using a toolchain on Ubuntu 12.04 that was built on Ubuntu 10.04 (requires GCC 4.1 to build). As most of the libraries have moved to multiarch dirs, it couldn't find ld.so. So, make a symlink for it.
Check required path:
$ readelf -a arm-linux-gnueabi-gcc | grep interpreter: [Requesting program interpreter: /lib/ld-linux-x86-64.so.2]
Create symlink:
$ sudo ln -s /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 /lib/ld-linux-x86-64.so.2
If you're on 32bit, it'll be i386-linux-gnu and not x86_64-linux-gnu.
For me, The problem was solved after I close Visual Studio and Open it again
Answers of getting all file names recursively with C++11 for Windows and Linux(with experimental/filesystem
):
For Windows:
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <windows.h>
void getFiles_w(string path, vector<string>& files) {
intptr_t hFile = 0;
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) {
do {
if ((fileinfo.attrib & _A_SUBDIR)) {
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
getFiles(p.assign(path).append("/").append(fileinfo.name), files);
}
else {
files.push_back(p.assign(path).append("/").append(fileinfo.name));
}
} while (_findnext(hFile, &fileinfo) == 0);
}
}
For Linux:
#include <experimental/filesystem>
bool getFiles(std::experimental::filesystem::path path, vector<string>& filenames) {
namespace stdfs = std::experimental::filesystem;
// http://en.cppreference.com/w/cpp/experimental/fs/directory_iterator
const stdfs::directory_iterator end{} ;
for (stdfs::directory_iterator iter{path}; iter != end ; ++iter) {
// http://en.cppreference.com/w/cpp/experimental/fs/is_regular_file
if (!stdfs::is_regular_file(*iter)) { // comment out if all names (names of directories tc.) are required
if (getFiles(iter->path(), filenames))
return true;
}
else {
filenames.push_back(iter->path().string()) ;
cout << iter->path().string() << endl;
}
}
return false;
}
Just remember to link -lstdc++fs
when you compile it with g++
in Linux.
I obtained much better results with wxPython than tkinter, as suggested in this answer to a later duplicate question:
https://stackoverflow.com/a/9319832
The wxPython version produced the file dialog that looked the same as the open file dialog from just about any other application on my OpenSUSE Tumbleweed installation with the xfce desktop, whereas tkinter produced something cramped and hard to read with an unfamiliar side-scrolling interface.
I just shortened the answer I selected a bit:
var selectedGroups = new Array();
$("input[@name='user_group[]']:checked").each(function() {
selectedGroups.push($(this).val());
});
and it works like a charm, thanks!
If you want to center map onto a marker and you have the cordinate, something like click on a list item and the map should center on that coordinate then the following code will work:
In HTML:
<ul class="locationList" ng-repeat="LocationDetail in coordinateArray| orderBy:'LocationName'">
<li>
<div ng-click="focusMarker(LocationDetail)">
<strong><div ng-bind="locationDetail.LocationName"></div></strong>
<div ng-bind="locationDetail.AddressLine"></div>
<div ng-bind="locationDetail.State"></div>
<div ng-bind="locationDetail.City"></div>
<div>
</li>
</ul>
In Controller:
$scope.focusMarker = function (coords) {
map.setCenter(new google.maps.LatLng(coords.Latitude, coords.Longitude));
map.setZoom(14);
}
Location Object:
{
"Name": "Taj Mahal",
"AddressLine": "Tajganj",
"City": "Agra",
"State": "Uttar Pradesh",
"PhoneNumber": "1234 12344",
"Latitude": "27.173891",
"Longitude": "78.042068"
}
No, how you are doing it is correct.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.2
There is a great and exhaustive comparison tables and charts on git, Mercurial and Bazaar over at InfoQ's guide about DVCS.
git clone git://github.com/ryanb/railscasts-episodes.git
String img = "example.jpg";
// String imgLink = "http://www.example.com/example.jpg";
URI uri = null;
try {
uri = new URI(img);
String[] segments = uri.getPath().split("/");
System.out.println(segments[segments.length-1].split("\\.")[0]);
} catch (Exception e) {
e.printStackTrace();
}
This will output example for both img and imgLink
Try:
alter table <your table> modify <column name> null;
(This is basically a rewrite of Wayne's answer but with the confusion around the caret cleared up. So I've posted it as a CW. I'm not shy about editing answers, but completely rewriting them seems inappropriate.)
You can break up long lines with the caret (^
), just remember that the caret and the newline that follows it are removed entirely from the command, so if you put it where a space would be required (such as between parameters), be sure to include the space as well (either before the ^
, or at the beginning of the next line — that latter choice may help make it clearer it's a continuation).
Examples: (all tested on Windows XP and Windows 7)
xcopy file1.txt file2.txt
can be written as:
xcopy^
file1.txt^
file2.txt
or
xcopy ^
file1.txt ^
file2.txt
or even
xc^
opy ^
file1.txt ^
file2.txt
(That last works because there are no spaces betwen the xc
and the ^
, and no spaces at the beginning of the next line. So when you remove the ^
and the newline, you get...xcopy
.)
For readability and sanity, it's probably best breaking only between parameters (be sure to include the space).
Be sure that the ^
is not the last thing in a batch file, as there appears to be a major issue with that.
While looping through your string one character at a time is a viable method, there's no need. VBA has built-in functions for this kind of thing:
Public Function ProcessString(input_string As String) As String
ProcessString=Replace(input_string,"*","")
End Function
$('#test').click(function() {_x000D_
var startDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
var endDate = moment("01.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
This approach makes use of modern Javascript features like async/await
and the fetch
API. It downloads HTML as text and then feeds it to the innerHTML
of your container element.
/**
* @param {String} url - address for the HTML to fetch
* @return {String} the resulting HTML string fragment
*/
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
// this is your `load_home() function`
async function loadHome() {
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
The await (await fetch(url)).text()
may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:
async function fetchHtmlAsText(url) {
const response = await fetch(url);
return await response.text();
}
See the fetch API documentation for more details.
I always use pseudo elements :before
and :after
for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
Steps
visibility:hidden
or opacity:0
or position:absolute;left:-9999px
etc.:before
element and pass either an empty or a non-breaking space '\00a0'
;:checked
state, pass the unicode content: "\2713"
, which is a checkmark;:focus
style to make the checkbox accessible.Here is how I did it.
.box {_x000D_
background: #666666;_x000D_
color: #ffffff;_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
margin: 1.5em 0;_x000D_
padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
visibility: hidden;_x000D_
}_x000D_
label {_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
border: 1px solid #333;_x000D_
content: "\00a0";_x000D_
display: inline-block;_x000D_
font: 16px/1em sans-serif;_x000D_
height: 16px;_x000D_
margin: 0 .25em 0 0;_x000D_
padding: 0;_x000D_
vertical-align: top;_x000D_
width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
background: #fff;_x000D_
color: #333;_x000D_
content: "\2713";_x000D_
text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="box">_x000D_
<p>_x000D_
<input type="checkbox" id="c1" name="cb">_x000D_
<label for="c1">Option 01</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c2" name="cb">_x000D_
<label for="c2">Option 02</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c3" name="cb">_x000D_
<label for="c3">Option 03</label>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Much more stylish using :before
and :after
body{_x000D_
font-family: sans-serif; _x000D_
}_x000D_
_x000D_
.container {_x000D_
margin-top: 50px;_x000D_
margin-left: 20px;_x000D_
margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
width: 100%;_x000D_
margin: 15px auto;_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
width: auto;_x000D_
opacity: 0.00000001;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
margin: 4px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
transition: transform 0.28s ease;_x000D_
border-radius: 3px;_x000D_
border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
content: '';_x000D_
display: block;_x000D_
width: 10px;_x000D_
height: 5px;_x000D_
border-bottom: 2px solid #7bbe72;_x000D_
border-left: 2px solid #7bbe72;_x000D_
-webkit-transform: rotate(-45deg) scale(0);_x000D_
transform: rotate(-45deg) scale(0);_x000D_
transition: transform ease 0.25s;_x000D_
will-change: transform;_x000D_
position: absolute;_x000D_
top: 12px;_x000D_
left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
-webkit-transform: rotate(-45deg) scale(1);_x000D_
transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
min-height: 34px;_x000D_
display: block;_x000D_
padding-left: 40px;_x000D_
margin-bottom: 0;_x000D_
font-weight: normal;_x000D_
cursor: pointer;_x000D_
vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox" name="" value="">_x000D_
<label for="checkbox"><span>Checkbox</span></label>_x000D_
</div>_x000D_
_x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox2" name="" value="">_x000D_
<label for="checkbox2"><span>Checkbox</span></label>_x000D_
</div>_x000D_
</div>
_x000D_
If the new branch contains edits that are different from the current branch for that particular changed file, then it will not allow you to switch branches until the change is committed or stashed. If the changed file is the same on both branches (that is, the committed version of that file), then you can switch freely.
Example:
$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "adding file.txt"
$ git checkout -b experiment
$ echo 'goodbye world' >> file.txt
$ git add file.txt
$ git commit -m "added text"
# experiment now contains changes that master doesn't have
# any future changes to this file will keep you from changing branches
# until the changes are stashed or committed
$ echo "and we're back" >> file.txt # making additional changes
$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
file.txt
Please, commit your changes or stash them before you can switch branches.
Aborting
This goes for untracked files as well as tracked files. Here's an example for an untracked file.
Example:
$ git checkout -b experimental # creates new branch 'experimental'
$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "added file.txt"
$ git checkout master # master does not have file.txt
$ echo 'goodbye world' > file.txt
$ git checkout experimental
error: The following untracked working tree files would be overwritten by checkout:
file.txt
Please move or remove them before you can switch branches.
Aborting
A good example of why you WOULD want to move between branches while making changes would be if you were performing some experiments on master, wanted to commit them, but not to master just yet...
$ echo 'experimental change' >> file.txt # change to existing tracked file
# I want to save these, but not on master
$ git checkout -b experiment
M file.txt
Switched to branch 'experiment'
$ git add file.txt
$ git commit -m "possible modification for file.txt"
See this article on SQL Server Helper - SQL Server 2008 Date Format
Search all .npmrc file in your system.
Please verify that the path you have given is correct. If not please remove the incorrect path.
same issue on centos server 7, but this solved my problem:
node --max-old-space-size=X node_modules/@angular/cli/bin/ng build --prod
Where X = (2048 or 4096 or 8192 o..)
is the value of memory
Specific actions you can do from SQL client and you don't need to restart anything:
SET GLOBAL log = 'ON';
FLUSH LOGS;
If you have an issue, you need to locate your pg_hba.conf
. The command is:
find / -name 'pg_hba.conf' 2>/dev/null
and after that change the configuration file:
Postgresql 9.3
Postgresql 9.4
The next step is: Restarting your db instance:
service postgresql-9.3 restart
If you have any problems, you need to set password again:
ALTER USER db_user with password 'db_password';
I was also getting the error:
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
... with a Xamarin Forms Android-targeting application attempting to request resources from an API provider that required TLS 1.3.
The solution was to update the project configuration to swap out the Xamarin "managed" (.NET) http client (that doesn't support TLS 1.3 as of Xamarin Forms v2.5), and instead use the android native client.
It's a simple project toggle in visual studio. See screenshot below.
I had PHP7.2 on a Ubuntu 16.04 server and it solved my problem:
sudo apt-get install zip unzip php-zip
Update
Tried this for Ubuntu 18.04 and worked as well.
Here is one possiblity for you if you are using Bootstrap 3
live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/
edit view: http://jsfiddle.net/panchroma/vPH8N/
I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive
ie:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
<script id="add-active-to-current-page-nav-link" type="text/javascript">
function setSelectedPageNav() {
var pathName = document.location.pathname;
if ($("nav ul li a") != null) {
var currentLink = $("nav ul li a[href='" + pathName + "']");
currentLink.addClass("active");
}
}
setSelectedPageNav();
</script>
What works for me is that, I created a new folder that doesn't contain any other files, and selected that new folder I created and put the clone there.
I hope this helps
From https://idlebox.net/2010/apidocs/gdb-7.0.zip/gdb_9.html
The values of arguments that were not saved in their stack frames are shown as `value optimized out'.
Im guessing you compiled with -O(somevalue) and are accessing variables a,b,c in a function where optimization has occurred.
By the way it is written, clean rule is invoked only if it is explicitly called:
make clean
I think it is better, than make clean every time. If you want to do this by your way, try this:
CXX = g++ -O2 -Wall all: clean code1 code2 code1: code1.cc utilities.cc $(CXX) $^ -o $@ code2: code2.cc utilities.cc $(CXX) $^ -o $@ clean: rm ... echo Clean done
Instead of using older drawable id "abc_ic_ab_back_material", use the new one abc_ic_ab_back_material in every api version. I have tested it in 19, 21, 27 and working fine with below code and configuration.
compileSdkVersion = 27
public static Drawable changeBackArrowColor(Context context, int color) {
int res;
res = context.getResources().getIdentifier("abc_ic_ab_back_material", "drawable", context.getPackageName());
if (res == 0)
return null;
final Drawable upArrow = ContextCompat.getDrawable(context, res);
upArrow.setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_ATOP);
return upArrow;
}
Hold ctrl key and then click on class of which you want to see the inner working (for ex: String
) then you will find there button "Attach Source". Click on it. Then click on External Folder. Then browse to your jdk location, per instance C:\Program Files\Java\jdk1.6.0
. That's it.
In WAMP, right click on WAMP tray icon then change the port from 3308 to 3306 like this:
There's a good implementation of the Effective Java's hashcode()
and equals()
logic in Apache Commons Lang. Checkout HashCodeBuilder and EqualsBuilder.
Variables are not defined, but declared.
This is possible duplicate of declare variables in a pl/sql block
But you can look here :
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/fundamentals.htm#i27306
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/overview.htm
UPDATE:
Refer here : How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?
You need to use the Navigation component in the template of ObservingComponent ( dont't forget to add a selector to Navigation component .. navigation-component for ex )
<navigation-component (navchange)='onNavGhange($event)'></navigation-component>
And implement onNavGhange() in ObservingComponent
onNavGhange(event) {
console.log(event);
}
Last thing .. you don't need the events attribute in @Componennt
events : ['navchange'],
The angular way is shown in the angular docs :)
https://docs.angularjs.org/api/ng/directive/ngReadonly
Here is the example they use:
<body>
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
<input type="text" ng-readonly="checked" value="I'm Angular"/>
</body>
Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).
So basically in your case you would want to do something like below or check out this working example.
<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>
the easiest way is to use position:absolute
on both elements. You can absolutely position relative to the page, or you can absolutely position relative to a container div by setting the container div to position:relative
<div id="container" style="position:relative;">
<div id="div1" style="position:absolute; top:0; left:0;"></div>
<div id="div2" style="position:absolute; top:0; left:0;"></div>
</div>
You could either use a lookahead assertion like others have suggested. Or, if you just want to use basic regular expression syntax:
^(.?$|[^m].+|m[^y].*)
This matches strings that are either zero or one characters long (^.?$
) and thus can not be my
. Or strings with two or more characters where when the first character is not an m
any more characters may follow (^[^m].+
); or if the first character is a m
it must not be followed by a y
(^m[^y]
).
You are in the "Output" tab instead of the Terminal. The output tab is actually only for you to read from.
Press F5
to begin Debugging
and it'll bring you into the Terminal tab.
The terminal is interactive, so you can read output AND type back. It is indeed a console prompt/ terminal (hence its name).
thanks :
Kiwy
with AIX:
getPathByPid()
{
if [[ -e /proc/$1/object/a.out ]]; then
inode=`ls -i /proc/$1/object/a.out 2>/dev/null | awk '{print $1}'`
if [[ $? -eq 0 ]]; then
strnode=${inode}"$"
strNum=`ls -li /proc/$1/object/ 2>/dev/null | grep $strnode | awk '{print $NF}' | grep "[0-9]\{1,\}\.[0-9]\{1,\}\."`
if [[ $? -eq 0 ]]; then
# jfs2.10.6.5869
n1=`echo $strNum|awk -F"." '{print $2}'`
n2=`echo $strNum|awk -F"." '{print $3}'`
# brw-rw---- 1 root system 10, 6 Aug 23 2013 hd9var
strexp="^b.*"$n1,"[[:space:]]\{1,\}"$n2"[[:space:]]\{1,\}.*$" # "^b.*10, \{1,\}5 \{1,\}.*$"
strdf=`ls -l /dev/ | grep $strexp | awk '{print $NF}'`
if [[ $? -eq 0 ]]; then
strMpath=`df | grep $strdf | awk '{print $NF}'`
if [[ $? -eq 0 ]]; then
find $strMpath -inum $inode 2>/dev/null
if [[ $? -eq 0 ]]; then
return 0
fi
fi
fi
fi
fi
fi
return 1
}
There should be one - and preferably only one - obvious way to do it.
Therefore list(dictionary.values())
is the one way.
[*L]
vs. [].extend(L)
vs. list(L)
small_ds = {x: str(x+42) for x in range(10)}
small_df = {x: float(x+42) for x in range(10)}
print('Small Dict(str)')
%timeit [*small_ds.values()]
%timeit [].extend(small_ds.values())
%timeit list(small_ds.values())
print('Small Dict(float)')
%timeit [*small_df.values()]
%timeit [].extend(small_df.values())
%timeit list(small_df.values())
big_ds = {x: str(x+42) for x in range(1000000)}
big_df = {x: float(x+42) for x in range(1000000)}
print('Big Dict(str)')
%timeit [*big_ds.values()]
%timeit [].extend(big_ds.values())
%timeit list(big_ds.values())
print('Big Dict(float)')
%timeit [*big_df.values()]
%timeit [].extend(big_df.values())
%timeit list(big_df.values())
Small Dict(str)
256 ns ± 3.37 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
338 ns ± 0.807 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Small Dict(float)
268 ns ± 0.297 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
343 ns ± 15.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 0.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Big Dict(str)
17.5 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.5 ms ± 338 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.2 ms ± 19.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Big Dict(float)
13.2 ms ± 41 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
13.1 ms ± 919 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
12.8 ms ± 578 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Done on Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz.
# Name Version Build
ipython 7.5.0 py37h24bf2e0_0
* operator
is quickerlist()
is maybe slightly quickerTry
echo -e "hello\nworld"
hello
world
worked for me in nano
editor.
From the man page:
-e
enable interpretation of backslash escapes
Short answers:
Q1: Yes.
Q2: Doesn't matter which you use.
Long answer:
A select ... for update
will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.
Another way of looking at it, it is as if the following two statements are executed atomically:
select * from my_table where my_condition;
update my_table set my_column = my_column where my_condition;
Since the rows affected by my_condition
are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.
Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.
What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.
Use this annotation
@RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})
Use the layout_weight
attribute. The layout will roughly look like this:
<LinearLayout android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<LinearLayout
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="0dp"/>
<LinearLayout
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="0dp"/>
</LinearLayout>
What do you want to search near that known place?
For example if you want to search a restaurant near a known place you can use the parameters "q=" and "near=" and construct this URL: maps.google.com/?q=restaurant&near=47.154719,27.60551
For a list of complete parameters you can see this: https://web.archive.org/web/20070708030513/http://mapki.com/wiki/Google_Map_Parameters
Depending on what is the format you want your information in you can add at the end of the url the parameter output like this: maps.google.com/?q=restaurant&near=47.154719,27.60551&output=kml
For more types of output format you can read chapter 2 of this: http://csie-tw.blogspot.de/2009/06/android-driving-direction-route-path.html
The compile()
method is always called at some point; it's the only way to create a Pattern object. So the question is really, why should you call it explicitly? One reason is that you need a reference to the Matcher object so you can use its methods, like group(int)
to retrieve the contents of capturing groups. The only way to get ahold of the Matcher object is through the Pattern object's matcher()
method, and the only way to get ahold of the Pattern object is through the compile()
method. Then there's the find()
method which, unlike matches()
, is not duplicated in the String or Pattern classes.
The other reason is to avoid creating the same Pattern object over and over. Every time you use one of the regex-powered methods in String (or the static matches()
method in Pattern), it creates a new Pattern and a new Matcher. So this code snippet:
for (String s : myStringList) {
if ( s.matches("\\d+") ) {
doSomething();
}
}
...is exactly equivalent to this:
for (String s : myStringList) {
if ( Pattern.compile("\\d+").matcher(s).matches() ) {
doSomething();
}
}
Obviously, that's doing a lot of unnecessary work. In fact, it can easily take longer to compile the regex and instantiate the Pattern object, than it does to perform an actual match. So it usually makes sense to pull that step out of the loop. You can create the Matcher ahead of time as well, though they're not nearly so expensive:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("");
for (String s : myStringList) {
if ( m.reset(s).matches() ) {
doSomething();
}
}
If you're familiar with .NET regexes, you may be wondering if Java's compile()
method is related to .NET's RegexOptions.Compiled
modifier; the answer is no. Java's Pattern.compile()
method is merely equivalent to .NET's Regex constructor. When you specify the Compiled
option:
Regex r = new Regex(@"\d+", RegexOptions.Compiled);
...it compiles the regex directly to CIL byte code, allowing it to perform much faster, but at a significant cost in up-front processing and memory use--think of it as steroids for regexes. Java has no equivalent; there's no difference between a Pattern that's created behind the scenes by String#matches(String)
and one you create explicitly with Pattern#compile(String)
.
(EDIT: I originally said that all .NET Regex objects are cached, which is incorrect. Since .NET 2.0, automatic caching occurs only with static methods like Regex.Matches()
, not when you call a Regex constructor directly. ref)
My pure-JS function:
/**
* HTML entities encode
*
* @param {string} str Input text
* @return {string} Filtered text
*/
function htmlencode (str){
var div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
I used the javascript date funtion toLocaleDateString to get
var Today = new Date();
var r = Today.toLocaleDateString();
The result of r will be
11/29/2016
More info at: http://www.w3schools.com/jsref/jsref_tolocaledatestring.asp
Now there is the pandas_profiling
package, which is a more complete alternative to df.describe()
.
If your pandas dataframe is df
, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.
import pandas_profiling
pandas_profiling.ProfileReport(df)
See the example notebook detailing the usage.
If you don't want to use setMaxResults()
on the Query
object then you could always revert back to using normal SQL.
To hide the arrow:
input::-webkit-calendar-picker-indicator{
display: none;
}
And to hide the prompt:
input[type="date"]::-webkit-input-placeholder{
visibility: hidden !important;
}
Load data infile query is much better option but some servers like godaddy restrict this option on shared hosting so , only two options left then one is insert record on every iteration or batch insert , but batch insert has its limitaion of characters if your query exceeds this number of characters set in mysql then your query will crash , So I suggest insert data in chunks withs batch insert , this will minimize number of connections established with database.best of luck guys
I ran into the same problem and reported it as a bug on the Facebook developer site. It seems pretty clear that og:image
URIs using HTTP work just fine and URIs using HTTPS do not. They have now acknowledged that they are "looking into this."
Update: As of 2020, the bug is no longer visible in Facebook's ticket system. They never responded and I don't believe this behavior has changed. However, specifying HTTPS URI in og:image:secure
does seem to be working fine.
the same problem also happened to me when i training my classification model. the reason caused this problem is as what the warning message said "in labels with no predicated samples", it will caused the zero-division when compute f1-score. I found another solution when i read sklearn.metrics.f1_score doc, there is a note as follows:
When true positive + false positive == 0, precision is undefined; When true positive + false negative == 0, recall is undefined. In such cases, by default the metric will be set to 0, as will f-score, and UndefinedMetricWarning will be raised. This behavior can be modified with zero_division
the zero_division
default value is "warn"
, you could set it to 0
or 1
to avoid UndefinedMetricWarning
.
it works for me ;) oh wait, there is another problem when i using zero_division
, my sklearn report that no such keyword argument by using scikit-learn 0.21.3. Just update your sklearn to the latest version by running pip install scikit-learn -U
What you need to do is create a dataset. If you take a look at the quickstart guide, it shows you that you need to use the file object in order to create a dataset. So, f.create_dataset
and then you can read the data. This is explained in the docs.
May be this will help:
wget --no-check-certificate https://blah-blah.tld/path/filename
This is how you do it column-wise:
[df[col].update((df[col] - df[col].min()) / (df[col].max() - df[col].min())) for col in df.columns]
The console.log
should be wrapped in a function , the "default" function for every class is its constructor
so it should be declared there.
import { Component } from '@angular/core';
console.log("Hello1");
@Component({
selector: 'hello-console',
})
export class App {
s: string = "Hello2";
constructor(){
console.log(s);
}
}
In most cases where Equals() compares multiple fields it doesn't really matter if your GetHash() hashes on one field or on many. You just have to make sure that calculating the hash is really cheap (No allocations, please) and fast (No heavy computations and certainly no database connections) and provides a good distribution.
The heavy lifting should be part of the Equals() method; the hash should be a very cheap operation to enable calling Equals() on as few items as possible.
And one final tip: Don't rely on GetHashCode() being stable over multiple aplication runs. Many .Net types don't guarantee their hash codes to stay the same after a restart, so you should only use the value of GetHashCode() for in memory data structures.
len(list_name)
function takes list as a parameter and it calls list's __len__()
function.
Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime
class, which along with it's related classes, really should be in any PHP developer's toolkit.
// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it.
$datetime = DateTime::createFromFormat('g:i:s', $selectedTime);
$datetime->modify('+15 minutes');
echo $datetime->format('g:i:s');
Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:
!g:i:s
12-hour format without leading zeroes on hour
!G:i:s
12-hour format with leading zeroes
Note the !
item in format. This would set date component to first day in Linux epoch (1-1-1970)
Um...
with open(os.path.join(src_dir, f)) as fin:
for line in fin:
Also, you never output to a new file.
Go to Build Phases-> Compile Sources and add your new .m files.
Simply call the ordinal()
method on an enum value, to retrieve its corresponding number. There's no need to declare an addition attribute with its value, each enumerated value gets its own number by default, assigned starting from zero, incrementing by one for each value in the same order they were declared.
You shouldn't depend on the int
value of an enum
, only on its actual value. Enums in Java are a different kind of monster and are not like enums in C, where you depend on their integer code.
Regarding the example you provided in the question, Font.PLAIN
works because that's just an integer constant of the Font class. If you absolutely need a (possibly changing) numeric code, then an enum
is not the right tool for the job, better stick to numeric constants.
I just got the same problem and to fix it, I opened the task manager and killed the adb.exe process, then I restarted Eclipse.
Got it from here. It works for iOS 9
UIApplication *app = [UIApplication sharedApplication];
NSArray *eventArray = [app scheduledLocalNotifications];
for (int i=0; i<[eventArray count]; i++)
{
UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
}
There's a shortcut to delete the branch in the origin:
git push origin :<branch_name>
Which is the same as doing git push origin --delete <branch_name>
You can do the following:
String [] strings = new String [] {"1", "2" };
List<String> stringList = new ArrayList<String>(Arrays.asList(strings)); //new ArrayList is only needed if you absolutely need an ArrayList
This finally became a part of support v4 library, NestedScrollView. So, no longer local hacks is needed for most of cases I'd guess.
You can use df.index
to access the index object and then get the values in a list using df.index.tolist()
. Similarly, you can use df['col'].tolist()
for Series.
Use this:
#head {
border: green solid 1px;
height:auto;
}
#content{
border: red solid 1px;
overflow-y: scroll;
height:150px;
}
You can also specify the TNS name in the JDBC URL as below
jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))
I tried almost all of these techniques (except FXLabel) and couldn't get any of them to work with iOS 7. I did eventually find THLabel which is working perfectly for me. I used THLabel in Interface Builder and setup User Defined Runtime Attributes so that it's easy for a non programmer to control the look and feel.
Just in case you actually mean discard changes whenever you use git stash
(and don't really use git stash to stash it temporarily), in that case you can use
git checkout -- <file>
[NOTE]
That git stash
is just a quicker and simple alternative to branching and doing stuff.
Override the onBackPressed method and do nothing if you meant to handle the back button on the device.
@Override
public void onBackPressed() {
if (shouldAllowBack()) {
super.onBackPressed();
} else {
doSomething();
}
}
Updated for iOS 8.0
Since iOS 8.0, you will need to use UIAlertController as the following:
-(void)alertMessage:(NSString*)message
{
UIAlertController* alert = [UIAlertController
alertControllerWithTitle:@"Alert"
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction
actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
Where self in my example is a UIViewController, which implements "presentViewController" method for a popup.
David
Please install App Script for Ionic 3 Solution npm i -D -E @ionic/app-scripts
It should be legal to put a semicolon directly before the WITH keyword.
Use ENUM in MySQL for true / false it gives and accepts the true / false values without any extra code.
ALTER TABLE `itemcategory` ADD `aaa` ENUM('false', 'true') NOT NULL DEFAULT 'false'
For your case, just use:
var votevalue = +$(this).data('votevalue');
There are some ways to convert string to number in javascript.
The best way:
var str = "1";
var num = +str; //simple enough and work with both int and float
You also can:
var str = "1";
var num = Number(str); //without new. work with both int and float
or
var str = "1";
var num = parseInt(str,10); //for integer number
var num = parseFloat(str); //for float number
DON'T:
var str = "1";
var num = new Number(str); //num will be an object. typeof num == 'object'
Use parseInt only for special case, for example
var str = "ff";
var num = parseInt(str,16); //255
var str = "0xff";
var num = parseInt(str); //255
if (!secondaryPassword.equals(initialPassword))
A @ViewScoped
bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null
or void
(and thus navigates back to the same view). Once you refresh the page, or return a non-null
string (even an empty string!) navigation outcome, then the view scope will end.
A @RequestScoped
bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.
A @ViewScoped
bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped
one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped
bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped
bean. Every view has its own unique @ViewScoped
bean.
To make it visible between the instances of T1
and T2
you could make the two classes contain a reference to an object that contains the variable.
If the variable is to be modified when the threads are running, you need to consider synchronization. The best approach depends on your exact requirements, but the main options are as follows:
volatile
;AtomicBoolean
;Based on saikirans solution, I have written this, which helped me. On the .m file:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(selectedRowIndex && indexPath.row == selectedRowIndex.row) {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
selectedRowIndex = nil;
}
else { self.selectedRowIndex = [indexPath retain]; }
[tableView beginUpdates];
[tableView endUpdates];
}
And on the header file:
@property (retain, nonatomic) NSIndexPath* selectedRowIndex;
I am not very experienced either, so double check for memory leaks etc.
b = email.message_from_string(a)
if b.is_multipart():
for payload in b.get_payload():
# if payload.is_multipart(): ...
print payload.get_payload()
else:
print b.get_payload()
I use this:
use YourDB;
SELECT
object_name(object_id),
last_execution_time,
last_elapsed_time,
execution_count
FROM
sys.dm_exec_procedure_stats ps
where
lower(object_name(object_id)) like 'Appl-Name%'
order by 1
It's worth investigating the Pipeline plugin. With the plugin you can checkout multiple VCS projects into relative directory paths. Beforehand creating a directory per VCS checkout. Then issue commands to the newly checked out VCS workspace. In my case I am using git. But you should get the idea.
node{
def exists = fileExists 'foo'
if (!exists){
new File('foo').mkdir()
}
dir ('foo') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
def exists = fileExists 'bar'
if (!exists){
new File('bar').mkdir()
}
dir ('bar') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
def exists = fileExists 'baz'
if (!exists){
new File('baz').mkdir()
}
dir ('baz') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
}
In the specific case of the code example from the original question, the
System.out.print("\n");
is there to move to a new line between incrementing i.
So the first print statement prints all of the elements of Grid[0][j]. When the innermost for loop has completed, the "\n" gets printed and then all of the elements of Grid[1][j] are printed on the next line, and this is repeated until you have a 10x10 grid of the elements of the 2-dimensional array, Grid.
Sorry the problem is me! the was out of sync but this was because I have the HTML text the wrong way around. On the first click I want the div to fade out and the text to say "Show Text".
Will check more thoroughly next time before I ask!
My code is now:
$(function() {
$("#show-background").toggle(function (){
$("#content-area").animate({opacity: '0'}, 'slow')
$("#show-background").text("Show Text")
.stop();
}, function(){
$("#content-area").animate({opacity: '1'}, 'slow')
$("#show-background").text("Show Background")
.stop();
});
});
Thanks again for the help!
Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.
OR
y + ̆ = y̆ which actually is
y + ̆ = y̆
Since you can stack them one atop the other you can produce the following:
y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
which actually is:
y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
The same goes for putting stuff underneath:
y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
that in fact is:
y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.
To produce a list of combining diacritical marks you can use the following script (since links keep on dying)
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +" "+"&#"+i+";");}
_x000D_
Also check em out
Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾
The Function adds gaussian , salt-pepper , poisson and speckle noise in an image
Parameters
----------
image : ndarray
Input image data. Will be converted to float.
mode : str
One of the following strings, selecting the type of noise to add:
'gauss' Gaussian-distributed additive noise.
'poisson' Poisson-distributed noise generated from the data.
's&p' Replaces random pixels with 0 or 1.
'speckle' Multiplicative noise using out = image + n*image,where
n is uniform noise with specified mean & variance.
import numpy as np
import os
import cv2
def noisy(noise_typ,image):
if noise_typ == "gauss":
row,col,ch= image.shape
mean = 0
var = 0.1
sigma = var**0.5
gauss = np.random.normal(mean,sigma,(row,col,ch))
gauss = gauss.reshape(row,col,ch)
noisy = image + gauss
return noisy
elif noise_typ == "s&p":
row,col,ch = image.shape
s_vs_p = 0.5
amount = 0.004
out = np.copy(image)
# Salt mode
num_salt = np.ceil(amount * image.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
for i in image.shape]
out[coords] = 1
# Pepper mode
num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
for i in image.shape]
out[coords] = 0
return out
elif noise_typ == "poisson":
vals = len(np.unique(image))
vals = 2 ** np.ceil(np.log2(vals))
noisy = np.random.poisson(image * vals) / float(vals)
return noisy
elif noise_typ =="speckle":
row,col,ch = image.shape
gauss = np.random.randn(row,col,ch)
gauss = gauss.reshape(row,col,ch)
noisy = image + image * gauss
return noisy
A much simpler way could be
/(\D+)/.match('1221').nil? #=> true
/(\D+)/.match('1a221').nil? #=> false
/(\D+)/.match('01221').nil? #=> true
It sounds like you're trying to link with your resulting object file with gcc
instead of g++
:
Note that programs using C++ object files must always be linked with g++, in order to supply the appropriate C++ libraries. Attempting to link a C++ object file with the C compiler gcc will cause "undefined reference" errors for C++ standard library functions:
$ g++ -Wall -c hello.cc
$ gcc hello.o (should use g++)
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
.....
hello.o(.eh_frame+0x11):
undefined reference to `__gxx_personality_v0'
Source: An Introduction to GCC - for the GNU compilers gcc and g++
For PHP 5.3 this should work. You may need to fiddle with passing $dateInfo['is_dst'], wasn't working for me anyhow.
$date = '05/Feb/2010:14:00:01';
$dateInfo = date_parse_from_format('d/M/Y:H:i:s', $date);
$unixTimestamp = mktime(
$dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
$dateInfo['month'], $dateInfo['day'], $dateInfo['year'],
$dateInfo['is_dst']
);
Versions prior, this should work.
$date = '05/Feb/2010:14:00:01';
$format = '@^(?P<day>\d{2})/(?P<month>[A-Z][a-z]{2})/(?P<year>\d{4}):(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})$@';
preg_match($format, $date, $dateInfo);
$unixTimestamp = mktime(
$dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
date('n', strtotime($dateInfo['month'])), $dateInfo['day'], $dateInfo['year'],
date('I')
);
You may not like regular expressions. You could annotate it, of course, but not everyone likes that either. So, this is an alternative.
$day = $date[0].$date[1];
$month = date('n', strtotime($date[3].$date[4].$date[5]));
$year = $date[7].$date[8].$date[9].$date[10];
$hour = $date[12].$date[13];
$minute = $date[15].$date[16];
$second = $date[18].$date[19];
Or substr, or explode, whatever you wish to parse that string.
The problem was the box "open new connection" that was checked. So I couldn't use my temporary table.
In my case, I had to remove it with
rm -r /var/lib/docker/containers/<container-id>/
and it worked. Maybe that's how you solve it in docker version ~19. My docker version was 19.03.12
,
Why not use MySQL LIMIT keyword?
SELECT [t2].[AnotherColumn], [t2].[SomeColumn]
FROM [Table] AS [t2]
WHERE (([t1].[SomeColumn] IS NULL) AND ([t2].[SomeColumn] IS NULL))
OR (([t1].[SomeColumn] IS NOT NULL) AND ([t2].[SomeColumn] IS NOT NULL)
AND ([t1].[SomeColumn] = [t2].[SomeColumn]))
ORDER BY [t2].[AnotherColumn]
LIMIT 1
To update the local list of remote branches:
git remote update origin --prune
To show all local and remote branches that (local) Git knows about
git branch -a
As stated in the other answers use event.preventDefault() to prevent form submitting.
To check the form before I wrote a little jQuery function you may use (note that the element needs an ID!)
(function( $ ){
$.fn.isValid = function() {
return document.getElementById(this[0].id).checkValidity();
};
})( jQuery );
example usage
$('#submitBtn').click( function(e){
if ($('#registerForm').isValid()){
// do the request
} else {
e.preventDefault();
}
});
trick:
int time_len = 0, n;
struct tm *tm_info;
struct timeval tv;
gettimeofday(&tv, NULL);
tm_info = localtime(&tv.tv_sec);
time_len+=strftime(log_buff, sizeof log_buff, "%y%m%d %H:%M:%S", tm_info);
time_len+=snprintf(log_buff+time_len,sizeof log_buff-time_len,".%03ld ",tv.tv_usec/1000);
Read one character at a time (using getc(stdin)
) and grow the string (realloc
) as you go.
Here's a function I wrote some time ago. Note it's intended only for text input.
char *getln()
{
char *line = NULL, *tmp = NULL;
size_t size = 0, index = 0;
int ch = EOF;
while (ch) {
ch = getc(stdin);
/* Check if we need to stop. */
if (ch == EOF || ch == '\n')
ch = 0;
/* Check if we need to expand. */
if (size <= index) {
size += CHUNK;
tmp = realloc(line, size);
if (!tmp) {
free(line);
line = NULL;
break;
}
line = tmp;
}
/* Actually store the thing. */
line[index++] = ch;
}
return line;
}
Here is where I found it on a Windows 2008R2 server. Elevated Task Scheduler Click on "Task Scheduler Library" It appears as an option on the right hand "Actions" panel.
confirmed roadkill, create a .htaccess file in the web root with a single line which allows you to add php code to a .html file.
AddType application/x-httpd-php .html
I think what you want is to have access to the request context, see RequestContext.
For each works with JQuery as in
$(<selector>).each(function() {
//this points to item
alert('<msg>');
});
JQuery also, for a popup, has in the UI library a dialog widget: http://jqueryui.com/demos/dialog/
Check it out, works really well.
HTH.
Following worked for me on Android Studio 3.x.
Step 1: Open AVD Manager.
Step 2: Right click and Wipe data for the virtual device you're testing on.
You just need to add this line to the window there:
exec (your stored proc name) (and possibly add parameters)
What is your stored proc called, and what parameters does it expect?
Try this
String[] arr = list.toArray(new String[list.size()]);
ps -eaf | grep [j]ava
It's better since it will only show you the active processes not including this command that also got java string the []
does the trick
I had this problem, and turns out the problem was that I had used
new SimpleJdbcCall(jdbcTemplate)
.withProcedureName("foo")
instead of
new SimpleJdbcCall(jdbcTemplate)
.withFunctionName("foo")
Here is a core JavaScript function to wait for the display of an element (well, its insertion into the DOM to be more accurate).
// Call the below function
waitForElementToDisplay("#div1",function(){alert("Hi");},1000,9000);
function waitForElementToDisplay(selector, callback, checkFrequencyInMs, timeoutInMs) {
var startTimeInMs = Date.now();
(function loopSearch() {
if (document.querySelector(selector) != null) {
callback();
return;
}
else {
setTimeout(function () {
if (timeoutInMs && Date.now() - startTimeInMs > timeoutInMs)
return;
loopSearch();
}, checkFrequencyInMs);
}
})();
}
This call will look for the HTML tag whose id="div1"
every 1000 milliseconds. If the element is found, it will display an alert message Hi. If no element is found after 9000 milliseconds, this function stops its execution.
Parameters:
selector
: String : This function looks for the element ${selector}.callback
: Function : This is a function that will be called if the element is found.checkFrequencyInMs
: Number : This function checks whether this element exists every ${checkFrequencyInMs} milliseconds.timeoutInMs
: Number : Optional. This function stops looking for the element after ${timeoutInMs} milliseconds.NB : Selectors are explained at https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not
Another way of doing it is using HttpResponsePermanentRedirect like so:
In view.py
def url_redirect(request):
return HttpResponsePermanentRedirect("/new_url/")
In the url.py
url(r'^old_url/$', "website.views.url_redirect", name="url-redirect"),
Here's how to get the command yourself. This works for any version:
Update the download URL in this command and you should be good to go:
wget --no-check-certificate -c --header "Cookie: oraclelicense=accept-securebackup-cookie" https://download.oracle.com/otn/java/jdk/11.0.6+8/90eb79fb590d45c8971362673c5ab495/jdk-11.0.6_linux-x64_bin.tar.gz
To further explain the wget, the --no-check-certificate should be clear enough, but the header content (for any call) is discoverable by using the Developer Tools Network Tab in your browser. The developer tools are powerful and are well worth the time to learn. Enjoy.
Check out this plunkr.
When you're binding to variables, you need to use the brackets. Also, you use the hashtag when you want to get references to elements in your html, not for declaring variables inside of templates like that.
<md-button-toggle *ngFor="let indicador of indicadores; let first = first;" [value]="indicador.id" [checked]="first">
...
Edit: Thanks to Christopher Moore: Angular exposes the following local variables:
index
first
last
even
odd
Use a DataTrigger
:
<DataGrid ItemsSource="{Binding YourItemsSource}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="State1">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="State2">
<Setter Property="Background" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
Please check if you open up a new connection with each of your requests (mysql_connect(...)). If you do so, make sure you close the connection afterwards (using mysql_close($link)).
Also, you should consider changing this behaviour as keeping one steady connection for each user may be a better way to accomplish your task.
If you didn't already, take a look at this obvious, but nonetheless useful information resource: http://php.net/manual/function.mysql-connect.php
One way to get this error in Eclipse :
A
in src/test/java
.B
in src/main/java
that uses class A
.Result : Eclipse will compile the code, but maven will give "Cannot find symbol".
Underlying cause : Eclipse is using a combined build path for the main and test trees. Unfortunately, it does not support using different build paths for different parts of an Eclipse project, which is what Maven requires.
Solution :
Post json data (e.g. with curl)
curl -X POST -H 'Content-Type: application/json' \
'http://<host>:<port>/solr/<core>/update?commit=true' \
-d '{ "delete": {"query":"*:*"} }'
You can check it with for example jQuery:
$("#elementID").css('display');
It will return string with information about display property of this element.
Append .done()
to your ajax request.
$.ajax({
url: "test.html",
context: document.body
}).done(function() { //use this
alert("DONE!");
});
See the JQuery Doc for .done()
in javascript :
document.getElementById("message").value
Referring to @dylanvanw answer. You might still out of luck. I found that you might have a different path that you have installed Python. In my case, I have to move Chromedriver.exe from the cache path (C:\Users\Poom.wdm\drivers\chromedriver\win32\84.0.4147.30) to C:\Python38 then it work!
When you change an ASP.NET website's configuration file, it restarts the application to reflect the changes...
When you do an IIS reset, that restarts all applications running on that IIS instance.
The strcmp and strcmpi functions are the most direct way to do this. They search through arrays.
strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ix = find(strcmp(strs, 'KU'))
In IIS 10, we use a similar solution to Drew's approach, i.e.:
using System;
using System.Web;
namespace Common.Web.Modules.Http
{
/// <summary>
/// Sets custom headers in all requests (e.g. "Server" header) or simply remove some.
/// </summary>
public class CustomHeaderModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreSendRequestHeaders += OnPreSendRequestHeaders;
}
public void Dispose() { }
/// <summary>
/// Event handler that implements the desired behavior for the PreSendRequestHeaders event,
/// that occurs just before ASP.NET sends HTTP headers to the client.
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void OnPreSendRequestHeaders(object sender, EventArgs e)
{
//HttpContext.Current.Response.Headers.Remove("Server");
HttpContext.Current.Response.Headers.Set("Server", "MyServer");
}
}
}
And obviously add a reference to that dll in your project(s) and also the module in the config(s) you want:
<system.webServer>_x000D_
<modules>_x000D_
<!--Use http module to remove/customize IIS "Server" header-->_x000D_
<add name="CustomHeaderModule" type="Common.Web.Modules.Http.CustomHeaderModule" />_x000D_
</modules>_x000D_
</system.webServer>
_x000D_
IMPORTANT NOTE1: This solution needs an application pool set as integrated;
IMPORTANT NOTE2: All responses within the web app will be affected by this (css and js included);
I have the problem because I updated Java version.
The following steps work for me:
- Run
\Tomcat\bin\tomcat7w.exe
- Confirm "Startup" tab -> "Mode" choose "jvm"
- "Java" tab -> update "Java Virtual Machine" path to new version path
- Restart Tomcat
Done.
I know this is old, but I had a similar problem and found a fix:
I had the same issue with a module I ported from Excel into Access, in an unrelated UDF I was dimming 'As Range' but ranges don't exist in Access. You may be using a variable type without having the proper reference library turned on.
If you have any non-standard dims google them and see if you're missing the reference to that library under tools.
-E
Sometimes it is not desirable to use interpolation on title attribute or on any other attributes as for that matter, because they get parsed before the interpolation takes place. So:
<!-- dont do this -->
<!-- <a title="{{product.shortDesc}}" ...> -->
If an attribute with a binding is prefixed with the ngAttr prefix (denormalized as ng-attr-) then during the binding will be applied to the corresponding unprefixed attribute. This allows you to bind to attributes that would otherwise be eagerly processed by browsers. The attribute will be set only when the binding is done. The prefix is then removed:
<!-- do this -->
<a ng-attr-title="{{product.shortDesc}}" ...>
(Ensure that you are not using a very earlier version of Angular). Here's a demo fiddle using v1.2.2:
All you had to do is go to styles.xml file and replace your parent theme from
Theme.AppCompat.Light.DarkActionBar
to
Base.Theme.AppCompat.Light.DarkActionBar
your issue will be resolved by properly defining cascading depedencies or by saving the referenced entities before saving the entity that references. Defining cascading is really tricky to get right because of all the subtle variations in how they are used.
Here is how you can define cascades:
@Entity
public class Userrole implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long userroleid;
private Timestamp createddate;
private Timestamp deleteddate;
private String isactive;
//bi-directional many-to-one association to Role
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="ROLEID")
private Role role;
//bi-directional many-to-one association to User
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="USERID")
private User user;
}
In this scenario, every time you save, update, delete, etc Userrole, the assocaited Role and User will also be saved, updated...
Again, if your use case demands that you do not modify User or Role when updating Userrole, then simply save User or Role before modifying Userrole
Additionally, bidirectional relationships have a one-way ownership. In this case, User owns Bloodgroup. Therefore, cascades will only proceed from User -> Bloodgroup. Again, you need to save User into the database (attach it or make it non-transient) in order to associate it with Bloodgroup.
Q1:
Business logics can be considered in two categories:
Domain logics like controls on an email address (uniqueness, constraints, etc.), obtaining the price of a product for invoice, or, calculating the shoppingCart's total price based of its product objects.
More broad and complicated workflows which are called business processes, like controlling the registration process for the student (which usually includes several steps and needs different checks and has more complicated constraints).
The first category goes into model and the second one belongs to controller. This is because the cases in the second category are broad application logics and putting them in the model may mix the model's abstraction (for example, it is not clear if we need to put those decisions in one model class or another, since they are related to both!).
See this answer for a specific distinction between model and controller, this link for very exact definitions and also this link for a nice Android example.
The point is that the notes mentioned by "Mud" and "Frank" above both can be true as well as "Pete"'s (business logic can be put in model, or controller, according to the type of business logic).
Finally, note that MVC differs from context to context. For example, in Android applications, some alternative definitions are suggested that differs from web-based ones (see this post for example).
Q2:
Business logic is more general and (as "decyclone" mentioned above) we have the following relation between them:
business rules ? business logics
I think this timeout you are experiencing is actually part of TCP/IP and the solution is to just send empty messages once in a while.
Here is a modified form of the source based on my comment. Note that GUIs should be constructed & updated on the EDT, though I did not go that far.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
public class Calc {
public static void main(String[] args) {
JFrame calcFrame = new JFrame();
// usually a good idea.
calcFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final JButton button1 = new JButton("1");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(
button1, "..is the loneliest number");
}
});
calcFrame.add(button1);
// don't do this..
// calcFrame.setSize(100, 100);
// important!
calcFrame.pack();
calcFrame.setVisible(true);
}
}
Once you are able to parse those strings into a Date object comparing them is easy (Using the <
operator). Parsing the dates will depend on the format. You may take a look at Datejs which might simplify this task.
I don't like to create a new settings/
directory. I simply add files named settings_dev.py
and settings_production.py
so I don't have to edit the BASE_DIR
.
The approach below increase the default structure instead of changing it.
mysite/ # Project
conf/
locale/
en_US/
fr_FR/
it_IT/
mysite/
__init__.py
settings.py
settings_dev.py
settings_production.py
urls.py
wsgi.py
static/
admin/
css/ # Custom back end styles
css/ # Project front end styles
fonts/
images/
js/
sass/
staticfiles/
templates/ # Project templates
includes/
footer.html
header.html
index.html
myapp/ # Application
core/
migrations/
__init__.py
templates/ # Application templates
myapp/
index.html
static/
myapp/
js/
css/
images/
__init__.py
admin.py
apps.py
forms.py
models.py
models_foo.py
models_bar.py
views.py
templatetags/ # Application with custom context processors and template tags
__init__.py
context_processors.py
templatetags/
__init__.py
templatetag_extras.py
gulpfile.js
manage.py
requirements.txt
I think this:
settings.py
settings_dev.py
settings_production.py
is better than this:
settings/__init__.py
settings/base.py
settings/dev.py
settings/production.py
This concept applies to other files as well.
I usually place node_modules/
and bower_components/
in the project directory within the default static/
folder.
Sometime a vendor/
directory for Git Submodules but usually I place them in the static/
folder.
Your myCoolDiv
element isn't a child of the player container. It's a child of the div
you created as a wrapper for it (markerDiv
in the first part of the code). Which is why it fails, removeChild
only removes children, not descendants.
You'd want to remove that wrapper div, or not add it at all.
Here's the "not adding it at all" option:
var markerDiv = document.createElement("div");_x000D_
markerDiv.innerHTML = "<div id='MyCoolDiv' style='color: #2b0808'>123</div>";_x000D_
document.getElementById("playerContainer").appendChild(markerDiv.firstChild);_x000D_
// -------------------------------------------------------------^^^^^^^^^^^_x000D_
_x000D_
setTimeout(function(){ _x000D_
var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
Or without using the wrapper (although it's quite handy for parsing that HTML):
var myCoolDiv = document.createElement("div");_x000D_
// Don't reall need this: myCoolDiv.id = "MyCoolDiv";_x000D_
myCoolDiv.style.color = "#2b0808";_x000D_
myCoolDiv.appendChild(_x000D_
document.createTextNode("123")_x000D_
);_x000D_
document.getElementById("playerContainer").appendChild(myCoolDiv);_x000D_
_x000D_
setTimeout(function(){ _x000D_
// No need for this, we already have it from the above:_x000D_
// var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
When trying to make changes to a Pandas dataframe using a function, we use 'inplace=True' if we want to commit the changes to the dataframe. Therefore, the first line in the following code changes the name of the first column in 'df' to 'Grades'. We need to call the database if we want to see the resulting database.
df.rename(columns={0: 'Grades'}, inplace=True)
df
We use 'inplace=False' (this is also the default value) when we don't want to commit the changes but just print the resulting database. So, in effect a copy of the original database with the committed changes is printed without altering the original database.
Just to be more clear, the following codes do the same thing:
#Code 1
df.rename(columns={0: 'Grades'}, inplace=True)
#Code 2
df=df.rename(columns={0: 'Grades'}, inplace=False}
You can use the JAVA 7 Files api
Path myDirectoryPath = Paths.get("path to my directory");
List<Path> subDirectories = Files.find(
myDirectoryPath ,
Integer.MAX_VALUE,
(filePath, fileAttr) -> fileAttr.isDirectory() && !filePath.equals(myDirectoryPath )
).collect(Collectors.toList());
If you want a specific value you can call map with the value you want before collecting the data.
The coalesce operator (??) is what you want, I believe.
You have two common ways to do that in case your URL looks like that:
https://domain/method/?a=x&b=y
Version 1:
If a specific key is mandatory you can use:
key_a = request.GET['a']
This will return a value of a
if the key exists and an exception if not.
Version 2:
If your keys are optional:
request.GET.get('a')
You can try that without any argument and this will not crash.
So you can wrap it with try: except:
and return HttpResponseBadRequest()
in example.
This is a simple way to make your code less complex, without using special exceptions handling.
In Python instead of language enforcing something, people use naming conventions e.g __method
for private methods and using _method
for protected methods.
So in same manner you can simply declare the constant as all caps e.g.
MY_CONSTANT = "one"
If you want that this constant never changes, you can hook into attribute access and do tricks, but a simpler approach is to declare a function
def MY_CONSTANT():
return "one"
Only problem is everywhere you will have to do MY_CONSTANT(), but again MY_CONSTANT = "one"
is the correct way in python(usually).
You can also use namedtuple to create constants:
>>> from collections import namedtuple
>>> Constants = namedtuple('Constants', ['pi', 'e'])
>>> constants = Constants(3.14, 2.718)
>>> constants.pi
3.14
>>> constants.pi = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
Declaring objects in the smallest scope improve readability.
Performance doesn't matter for today's compilers.(in this scenario)
From a maintenance perspective, 2nd option is better.
Declare and initialize variables in the same place, in the narrowest scope possible.
As Donald Ervin Knuth told:
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"
i.e) situation where a programmer lets performance considerations affect the design of a piece of code. This can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted by optimizing.
It's a bit more readable using literals:
self.navigationController.navigationBar.titleTextAttributes = @{
NSFontAttributeName:[UIFont fontWithName:@"mplus-1c-regular" size:21],
NSForegroundColorAttributeName: [UIColor whiteColor]
};
You can get a View's coordinates using getLocationOnScreen()
or getLocationInWindow()
Afterwards, x
and y
should be the top-left corner of the view. If your root layout is smaller than the screen (like in a Dialog), using getLocationInWindow
will be relative to its container, not the entire screen.
int[] point = new int[2];
view.getLocationOnScreen(point); // or getLocationInWindow(point)
int x = point[0];
int y = point[1];
NOTE: If value is always 0, you are likely changing the view immediately before requesting location.
To ensure view has had a chance to update, run your location request after the View's new layout has been calculated by using view.post
:
view.post(() -> {
// Values should no longer be 0
int[] point = new int[2];
view.getLocationOnScreen(point); // or getLocationInWindow(point)
int x = point[0];
int y = point[1];
});
~~
val point = IntArray(2)
view.getLocationOnScreen(point) // or getLocationInWindow(point)
val (x, y) = point
NOTE: If value is always 0, you are likely changing the view immediately before requesting location.
To ensure view has had a chance to update, run your location request after the View's new layout has been calculated by using view.post
:
view.post {
// Values should no longer be 0
val point = IntArray(2)
view.getLocationOnScreen(point) // or getLocationInWindow(point)
val (x, y) = point
}
I recommend creating an extension function for handling this:
// To use, call:
val (x, y) = view.screenLocation
val View.screenLocation get(): IntArray {
val point = IntArray(2)
getLocationOnScreen(point)
return point
}
And if you require reliability, also add:
view.screenLocationSafe { x, y -> Log.d("", "Use $x and $y here") }
fun View.screenLocationSafe(callback: (Int, Int) -> Unit) {
post {
val (x, y) = screenLocation
callback(x, y)
}
}
In My Case, after a fews days of research,
All I did to revolve is listed below:
This should work for similar codesign issues.
Note, during this process the OS would ask for your credential validation.
EDIT: as pointed out by @mmyers, this method doesn't work on input that contains substrings corresponding to bytes with the high bit set ("80" - "FF"). The explanation is at Bug ID: 6259307 Byte.parseByte not working as advertised in the SDK Documentation.
public static final byte[] fromHexString(final String s) {
byte[] arr = new byte[s.length()/2];
for ( int start = 0; start < s.length(); start += 2 )
{
String thisByte = s.substring(start, start+2);
arr[start/2] = Byte.parseByte(thisByte, 16);
}
return arr;
}
adding -vm C:/Program Files/Java/jdk1.6.0_29/bin/javaw.exe
to the .ini file helped me.
If the shell scripts start with #!/bin/bash
, they will always run with bash
from /bin
. If they however start with #!/usr/bin/env bash
, they will search for bash
in $PATH
and then start with the first one they can find.
Why would this be useful? Assume you want to run bash
scripts, that require bash 4.x or newer, yet your system only has bash
3.x installed and currently your distribution doesn't offer a newer version or you are no administrator and cannot change what is installed on that system.
Of course, you can download bash source code and build your own bash from scratch, placing it to ~/bin
for example. And you can also modify your $PATH
variable in your .bash_profile
file to include ~/bin
as the first entry (PATH=$HOME/bin:$PATH
as ~
will not expand in $PATH
). If you now call bash
, the shell will first look for it in $PATH
in order, so it starts with ~/bin
, where it will find your bash
. Same thing happens if scripts search for bash
using #!/usr/bin/env bash
, so these scripts would now be working on your system using your custom bash
build.
One downside is, that this can lead to unexpected behavior, e.g. same script on the same machine may run with different interpreters for different environments or users with different search paths, causing all kind of headaches.
The biggest downside with env
is that some systems will only allow one argument, so you cannot do this #!/usr/bin/env <interpreter> <arg>
, as the systems will see <interpreter> <arg>
as one argument (they will treat it as if the expression was quoted) and thus env
will search for an interpreter named <interpreter> <arg>
. Note that this is not a problem of the env
command itself, which always allowed multiple parameters to be passed through but with the shebang parser of the system that parses this line before even calling env
. Meanwhile this has been fixed on most systems but if your script wants to be ultra portable, you cannot rely that this has been fixed on the system you will be running.
It can even have security implications, e.g. if sudo
was not configured to clean environment or $PATH
was excluded from clean up. Let me demonstrate this:
Usually /bin
is a well protected place, only root
is able to change anything there. Your home directory is not, though, any program you run is able to make changes to it. That means malicious code could place a fake bash
into some hidden directory, modify your .bash_profile
to include that directory in your $PATH
, so all scripts using #!/usr/bin/env bash
will end up running with that fake bash
. If sudo
keeps $PATH
, you are in big trouble.
E.g. consider a tool creates a file ~/.evil/bash
with the following content:
#!/bin/bash
if [ $EUID -eq 0 ]; then
echo "All your base are belong to us..."
# We are root - do whatever you want to do
fi
/bin/bash "$@"
Let's make a simple script sample.sh
:
#!/usr/bin/env bash
echo "Hello World"
Proof of concept (on a system where sudo
keeps $PATH
):
$ ./sample.sh
Hello World
$ sudo ./sample.sh
Hello World
$ export PATH="$HOME/.evil:$PATH"
$ ./sample.sh
Hello World
$ sudo ./sample.sh
All your base are belong to us...
Hello World
Usually the classic shells should all be located in /bin
and if you don't want to place them there for whatever reason, it's really not an issue to place a symlink in /bin
that points to their real locations (or maybe /bin
itself is a symlink), so I would always go with #!/bin/sh
and #!/bin/bash
. There's just too much that would break if these wouldn't work anymore. It's not that POSIX would require these position (POSIX does not standardize path names and thus it doesn't even standardize the shebang feature at all) but they are so common, that even if a system would not offer a /bin/sh
, it would probably still understand #!/bin/sh
and know what to do with it and may it only be for compatibility with existing code.
But for more modern, non standard, optional interpreters like Perl, PHP, Python, or Ruby, it's not really specified anywhere where they should be located. They may be in /usr/bin
but they may as well be in /usr/local/bin
or in a completely different hierarchy branch (/opt/...
, /Applications/...
, etc.). That's why these often use the #!/usr/bin/env xxx
shebang syntax.
7-zip understands most kinds of archives, including rpm and the included cpio.
You can use getFragmentManager().popBackStack()
in basic Fragment
to go back.
while you should show how your code looks like that gives the problem, i think this scenario is very common. See copy/deepcopy
$arr1 = array(
array('id'=>1,'name'=>'aA','cat'=>'cc'),
array('id'=>2,'name'=>'aa','cat'=>'dd'),
array('id'=>3,'name'=>'bb','cat'=>'cc'),
array('id'=>4,'name'=>'bb','cat'=>'dd')
);
$result1 = array_msort($arr1, array('name'=>SORT_DESC);
$result2 = array_msort($arr1, array('cat'=>SORT_ASC);
$result3 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));
function array_msort($array, $cols)
{
$colarr = array();
foreach ($cols as $col => $order) {
$colarr[$col] = array();
foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}
$eval = 'array_multisort(';
foreach ($cols as $col => $order) {
$eval .= '$colarr[\''.$col.'\'],'.$order.',';
}
$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
foreach ($arr as $k => $v) {
$k = substr($k,1);
if (!isset($ret[$k])) $ret[$k] = $array[$k];
$ret[$k][$col] = $array[$k][$col];
}
}
return $ret;
}
Look at the traceback:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
out = iter(out)
TypeError: 'bool' object is not iterable
Your code isn't iterating the value, but the code receiving it is.
The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)
) or enclose it in a tuple ((False,)
).
Always read the traceback: it's correct, and it's helpful.
Set also android:gravity
parameter in TextView
to center
.
For testing the effects of different layout parameters I recommend to use different background color for every element, so you can see how your layout changes with parameters like gravity, layout_gravity or others.
For those who need to 'run as root' remotely through a script logging into a user account in the sudoers file, I found an evil horrible hack, that is no doubt very insecure:
sshpass -p 'userpass' ssh -T -p port user@server << EOSSH
sudo -S su - << RROOT
userpass
echo ""
echo "*** Got Root ***"
echo ""
#[root commands go here]
useradd -m newuser
echo "newuser:newpass" | chpasswd
RROOT
EOSSH
use this command php artisan migrate --path=/database/migrations/my_migration.php
it worked for me..
Use:
document.location.href = "http://yoursite.com" + document.getElementById('somefield');
That would get the value of some text field or hidden field, and add it to your site URL to get a new URL (href). You can modify this to suit your needs.
In Android Studio 3:
or use Android Debug Database
Identify the hash of the commit, using git log
, then use git revert <commit>
to create a new commit that removes these changes. In a way, git revert
is the converse of git cherry-pick
-- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.
You can serialize simple data to check for equality:
data1 = {firstName: 'John', lastName: 'Smith'};
data2 = {firstName: 'Jane', lastName: 'Smith'};
JSON.stringify(data1) === JSON.stringify(data2)
This will give you something like
'{firstName:"John",lastName:"Smith"}' === '{firstName:"Jane",lastName:"Smith"}'
As a function...
function compare(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
compare(data1, data2);
If you're using chai like you say, check out http://chaijs.com/api/bdd/#equal-section
If you just want to check keys...
function compareKeys(a, b) {
var aKeys = Object.keys(a).sort();
var bKeys = Object.keys(b).sort();
return JSON.stringify(aKeys) === JSON.stringify(bKeys);
}
should do it.
You can modify just the two lines:
->where('(library.available_until >=', date("Y-m-d H:i:s"), FALSE)
->or_where("library.available_until = '00-00-00 00:00:00')", NULL, FALSE)
EDIT:
Omitting the FALSE
parameter would have placed the backticks before the brackets and make them a part of the table name/value, making the query unusable.
The NULL
parameter is there just because the function requires the second parameter to be a value, and since we don't have one, we send NULL.
link_to "+ Service", controller_action_path(:account_id => acct.id)
If it is still not working check the path:
$ rake routes
@cmaster made the best elaborated answer. In brief:
git checkout master #
git pull # update local master from remote master
git checkout <your_branch>
git merge master # solve merge conflicts if you have`
You should not rewrite branch history instead keep them in actual state for future references. While merging to master, it creates one extra commit but that is cheap. Commits does not cost.
Or add this part
<script type="text/javascript">
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
</script>
after the HTML, like:
<html>
<head>...</head>
<body>...</body>
<script type="text/javascript">
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
</script>
</html>
When you mark your method as @Transactional
, occurrence of any exception inside your method will mark the surrounding TX as roll-back only (even if you catch them). You can use other attributes of @Transactional
annotation to prevent it of rolling back like:
@Transactional(rollbackFor=MyException.class, noRollbackFor=MyException2.class)
In new version of Laravel you can use "Service Injection".
https://laravel.com/docs/5.8/blade#service-injection
/resources/views/main.blade.php
@inject('project', 'App\Project')
<h1>{{ $project->get_title() }}</h1>
The problem here was a typo error in the password used, which was not easily identified due to the characters / letters used in the password.
So I started experimenting with the different things that FileReader API had to offer and could create an IMG tag with a DATA URL.
Drawback: It doesn't work on mobile phones, but it works fine on Google Chrome.
$('input').change(function() {_x000D_
_x000D_
var fr = new FileReader;_x000D_
_x000D_
fr.onload = function() {_x000D_
var img = new Image;_x000D_
_x000D_
img.onload = function() { _x000D_
//I loaded the image and have complete control over all attributes, like width and src, which is the purpose of filereader._x000D_
$.ajax({url: img.src, async: false, success: function(result){_x000D_
$("#result").html("READING IMAGE, PLEASE WAIT...")_x000D_
$("#result").html("<img src='" + img.src + "' />");_x000D_
console.log("Finished reading Image");_x000D_
}});_x000D_
};_x000D_
_x000D_
img.src = fr.result;_x000D_
};_x000D_
_x000D_
fr.readAsDataURL(this.files[0]);_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" accept="image/*" capture="camera">_x000D_
<div id='result'>Please choose a file to view it. <br/>(Tested successfully on Chrome - 100% SUCCESS RATE)</div>
_x000D_
(see this on a jsfiddle at http://jsfiddle.net/eD2Ez/530/)
(see the original jsfiddle that i added upon to at http://jsfiddle.net/eD2Ez/)
In Ruby ruby you can use the 'm
' option (multiline):
/YOUR_REGEXP/m
See the Regexp documentation on ruby-doc.org for more information.
To use Objectid method you don't need to import it. It is already on the mongodb object.
var ObjectId = new db.ObjectId('58c85d1b7932a14c7a0a320d');_x000D_
db.yourCollection.findOne({ _id: ObjectId }, function (err, info) {_x000D_
console.log(info)_x000D_
});_x000D_
_x000D_
I faced this error (errno 121) but it was caused by mysql-created intermediate tables that had been orphaned, preventing me from altering a table even though no such constraint name existed across any of my tables. At some point, my MySQL had crashed or failed to cleanup an intermediate table (table name starting with a #sql-) which ended up presenting me with an error such as: Can't create table '#sql-' (errno 121) when trying to run an ALTER TABLE with certain constraint names.
According to the docs at http://dev.mysql.com/doc/refman/5.7/en/innodb-troubleshooting-datadict.html , you can search for these orphan tables with:
SELECT * FROM INFORMATION_SCHEMA.INNODB_SYS_TABLES WHERE NAME LIKE '%#sql%';
The version I was working with was 5.1, but the above command only works on versions >= 5.6 (manual is incorrect about it working for 5.5 or earlier, because INNODB_SYS_TABLES does not exist in such versions). I was able to find the orphaned temporary table (which did not match the one named in the message) by searching my mysql data directory in command line:
find . -iname '#*'
After discovering the filename, such as #sql-9ad_15.frm, I was able to drop that orphaned table in MySQL:
USE myschema;
DROP TABLE `#mysql50##sql-9ad_15`;
After doing so, I was then able to successfully run my ALTER TABLE.
For completeness, as per the MySQL documentation linked, "the #mysql50# prefix tells MySQL to ignore file name safe encoding introduced in MySQL 5.1."
Also a nice way of doing this :)
Map<Integer,JsonObject> requestOutput = getRequestOutput(client,post);
int statusCode = requestOutput.keySet().stream().findFirst().orElseThrow(() -> new RuntimeException("Empty"));
Change the port number and remove script debugging (if enabled) to resolve in localhost
.
You can use @font-face in most modern browsers.
Here's some articles on how it works:
Here is a good syntax for adding the font to your app:
Here are a couple of places to convert fonts for use with @font-face:
Also cufon will work if you don't want to use font-face, and it has good documentation on the web site:
This is another option, using jQuery and getting only tbody
rows (with the data) and desconsidering thead/tfoot
.
$("#tableId > tbody > tr").length
console.log($("#myTableId > tbody > tr").length);
_x000D_
.demo {
width:100%;
height:100%;
border:1px solid #C0C0C0;
border-collapse:collapse;
border-spacing:2px;
padding:5px;
}
.demo caption {
caption-side:top;
text-align:center;
}
.demo th {
border:1px solid #C0C0C0;
padding:5px;
background:#F0F0F0;
}
.demo td {
border:1px solid #C0C0C0;
text-align:left;
padding:5px;
background:#FFFFFF;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTableId" class="demo">
<caption>Table 1</caption>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>Header 4</th>
</tr>
</thead>
<tbody>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan=4 style="background:#F0F0F0"> </td>
</tr>
</tfoot>
</table>
_x000D_
The setInterval
function returns an integer value, which is the id of the "timer instance" that you've created.
It is this integer value that you need to pass to clearInterval
e.g:
var timerID = setInterval(fontChange,500);
and later
clearInterval(timerID);
The full solution is not often found in one place ...
1) Create an app config file and name it "yourDllName.dll.config"
2) Right click on the config file created above in VS Solution Explorer, click properties
--- set "Build Action" = Content
--- set "Copy To Output Directory" = Always
3) Add an appSettings section to the configuration file (yourDllName.dll.config) with your yourKeyName and yourKeyValue
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="yourKeyName" value="yourKeyValue"/>
</appSettings>
</configuration>
4) Add System.Configuration to your dll/class/project references
5) Add the using statements to your code where you intend to access the config setting
using System.Configuration;
using System.Reflection;
6) To access the value
string keyValue = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings.Settings["yourKeyName"].Value;
7) rejoice, it works
IMHO, this should only be used when developing a new dll/library.
#if (DEBUG && !FINALTESTING)
string keyValue = ConfigurationManager.OpenExeConfiguration...(see 6 above)
#else
string keyValue = ConfigurationManager.AppSettings["yourKeyName"];
#endif
The config file ends up being a great reference, for when you add the dll's appSettings to your actual application.
You can do this, I am using
DataTable 1.10.5
using this code:
var versionNo = $.fn.dataTable.version;
alert(versionNo);
This is how I insert new record on my DataTable using row.add (My table has 10 columns), which can also includes HTML tag elements:
function fncInsertNew() {
var table = $('#tblRecord').DataTable();
table.row.add([
"Tiger Nixon",
"System Architect",
"$3,120",
"2011/04/25",
"Edinburgh",
"5421",
"Tiger Nixon",
"System Architect",
"$3,120",
"<p>Hello</p>"
]).draw();
}
For multiple inserts at the same time, use rows.add instead:
var table = $('#tblRecord').DataTable();
table.rows.add( [ {
"Tiger Nixon",
"System Architect",
"$3,120",
"2011/04/25",
"Edinburgh",
"5421"
}, {
"Garrett Winters",
"Director",
"$5,300",
"2011/07/25",
"Edinburgh",
"8422"
}]).draw();
How does a return statement differ from break statement?. Return statement exits current method execution and returns value to calling method. Break is used to exit from any loop.
If I have to exit an if condition, which one should I prefer, return or break?
To exit from method execution use return. to exit from any loop you can use either break or return based on your requirement.
The only point that everyone seems to have overlooked is that you may want integrated security = true. You may have the site running under a pool account. That's all fine so and it's still possible to hit the SQL server with the original user credential and not the pool's. It's called constrained delegation. If you enable it and set up an SPN windows will translate the pool's credentials with the user's on requests going to the final service (SQL is just one such service). You have to register the ONE AND ONLY SQL server that services SQL requests on the web server. Setting this all up is too much for me to try to accurately describe here. It took me quite a while to work through it myself.
EXEC sp_helplogins
You can also pass an "@LoginNamePattern" parameter to get information about a specific login:
EXEC sp_helplogins @LoginNamePattern='fred'
While working on a .Net app build with EF code first, I got this error message when trying to apply my migration where I had a Sql("UPDATE tableName SET columnName = value");
statement.
Turns out I misspelled the columnName.
>>> class A(object): pass
>>> e = A()
>>> e
<__main__.A object at 0xb6d464ec>
>>> print type(e)
<class '__main__.A'>
>>> print type(e).__name__
A
>>>
what do you mean by convert into a string? you can define your own repr and str_ methods:
>>> class A(object):
def __repr__(self):
return 'hei, i am A or B or whatever'
>>> e = A()
>>> e
hei, i am A or B or whatever
>>> str(e)
hei, i am A or B or whatever
or i dont know..please add explainations ;)
Check what git remote -v
returns: the account used to push to an http url is usually embedded into the remote url itself.
https://[email protected]/...
If that is the case, put an url which will force Git to ask for the account to use when pushing:
git remote set-url origin https://github.com/<user>/<repo>
Or one to use the Fre1234 account:
git remote set-url origin https://[email protected]/<user>/<repo>
Also check if you installed your Git For Windows with or without a credential helper as in this question.
The OP Fre1234 adds in the comments:
I finally found the solution.
Go to:Control Panel -> User Accounts -> Manage your credentials -> Windows Credentials
Under
Generic Credentials
there are some credentials related to Github,
Click on them and click "Remove
".
That is because the default installation for Git for Windows set a Git-Credential-Manager-for-Windows.
See git config --global credential.helper
output (it should be manager
)
Try this
function pad (str, max) {
return str.length < max ? pad("0" + str, max) : str;
}
alert(pad("5", 2));
Example
Or
var number = 5;
var i;
if (number < 10) {
alert("0"+number);
}
Example
Use this function to check if a string is alphanumeric:
public boolean isAlphanumeric(String str)
{
char[] charArray = str.toCharArray();
for(char c:charArray)
{
if (!Character.isLetterOrDigit(c))
return false;
}
return true;
}
It saves having to import external libraries and the code can easily be modified should you later wish to perform different validation checks on strings.