Just use basename
:
echo `basename "$filename"`
The quotes are needed in case $filename contains e.g. spaces.
Another option is to use Javascript:
if (document.getElementById('selectID').value == '1') {
document.getElementById('optionID').style.color = '#000';
(Not as clean as the CSS attribute selector, but more powerful)
I would recommend you to use background-image instead of default list.
.listStyle {
list-style: none;
background: url(image_path.jpg) no-repeat left center;
padding-left: 30px;
width: 20px;
height: 20px;
}
Or, if you don't want to use background-image as bullet, there is an option to do it with pseudo element:
.liststyle{
list-style: none;
margin: 0;
padding: 0;
}
.liststyle:before {
content: "• ";
color: red; /* or whatever color you prefer */
font-size: 20px;/* or whatever the bullet size you prefer */
}
Sometimes changing the header is not enough, some sites check the referer as well:
curl -v \
-H 'Host: restapi.some-site.com' \
-H 'Connection: keep-alive' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
-H 'Accept-Language: en-GB,en-US;q=0.8,en;q=0.6' \
-e localhost \
-A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36' \
'http://restapi.some-site.com/getsomething?argument=value&argument2=value'
In this example the referer (-e or --referer in curl) is 'localhost'.
I am just throwing in another one for reference since there was an additional question to Mark Edgars input and here is an additional example and touches on the topic overall:
[[ `cmd` ]] && echo success_else_silence
Which is the same as cmd || exit errcode
as someone showed.
For example, I want to make sure a partition is unmounted if mounted:
[[ `mount | grep /dev/sda1` ]] && umount /dev/sda1
This is my solution:
# your test class
class TestingClass(unittest.TestCase):
# This will only run once for all the tests within this class
@classmethod
def setUpClass(cls) -> None:
if len(sys.argv) > 1:
cls.email = sys.argv[1]
def testEmails(self):
assertEqual(self.email, "[email protected]")
if __name__ == "__main__":
unittest.main()
you could have a runner.py
file with something like this:
# your runner.py
loader = unittest.TestLoader()
tests = loader.discover('.') # note that this will find all your tests, you can also provide the name of the package e.g. `loader.discover('tests')
runner = unittest.TextTestRunner(verbose=3)
result = runner.run(tests
with the above code, you should be to run your tests with runner.py [email protected]
Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):
// did not work in IE10
$(function() {
$(window).resize(CmsContent.adjustSize);
});
while this worked in both browsers:
// did work in IE10
$(function() {
$(window).bind('resize', function() {
CmsContent.adjustSize();
};
});
Edit:
)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.
You can use the transpose
function from the data.table
library. Simple and fast solution that keeps numeric
values as numeric
.
library(data.table)
# get data
data("mtcars")
# transpose
t_mtcars <- transpose(mtcars)
# get row and colnames in order
colnames(t_mtcars) <- rownames(mtcars)
rownames(t_mtcars) <- colnames(mtcars)
how to completely clear localstorage
localStorage.clear();
how to completely clear sessionstorage
sessionStorage.clear();
[...] Cookies ?
var cookies = document.cookie;
for (var i = 0; i < cookies.split(";").length; ++i)
{
var myCookie = cookies[i];
var pos = myCookie.indexOf("=");
var name = pos > -1 ? myCookie.substr(0, pos) : myCookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
is there any way to get the value back after clear these ?
No, there isn't. But you shouldn't rely on this if this is related to a security question.
$scope.$emit: This method dispatches the event in the upwards direction (from child to parent)
$scope.$broadcast: Method dispatches the event in the downwards direction (from parent to child) to all the child controllers.
$scope.$on: Method registers to listen to some event. All the controllers which are listening to that event get notification of the broadcast or emit based on the where those fit in the child-parent hierarchy.
The $emit event can be cancelled by any one of the $scope who is listening to the event.
The $on provides the "stopPropagation" method. By calling this method the event can be stopped from propagating further.
Plunker :https://embed.plnkr.co/0Pdrrtj3GEnMp2UpILp4/
In case of sibling scopes (the scopes which are not in the direct parent-child hierarchy) then $emit and $broadcast will not communicate to the sibling scopes.
For more details please refer to http://yogeshtutorials.blogspot.in/2015/12/event-based-communication-between-angularjs-controllers.html
The simplest way : grep -Ril "Your text" /
Use numpy.concatenate(list1 , list2)
or numpy.append()
Look into the thread at Append a NumPy array to a NumPy array.
Simplyfing for the begginers:
If you want to select an element immediatly after another element you use the +
selector.
For example:
div + p
The "+" element selects all <p>
elements that are placed immediately after <div>
elements
If you want to learn more about selectors use this table
Public Class ClassDateOperation
Private prop_DifferenceInDay As Integer
Private prop_DifferenceInMonth As Integer
Private prop_DifferenceInYear As Integer
Public Function DayMonthYearFromTwoDate(ByVal DateStart As Date, ByVal DateEnd As Date) As ClassDateOperation
Dim differenceInDay As Integer
Dim differenceInMonth As Integer
Dim differenceInYear As Integer
Dim myDate As Date
DateEnd = DateEnd.AddDays(1)
differenceInYear = DateEnd.Year - DateStart.Year
If DateStart.Month <= DateEnd.Month Then
differenceInMonth = DateEnd.Month - DateStart.Month
Else
differenceInYear -= 1
differenceInMonth = (12 - DateStart.Month) + DateEnd.Month
End If
If DateStart.Day <= DateEnd.Day Then
differenceInDay = DateEnd.Day - DateStart.Day
Else
myDate = CDate("01/" & DateStart.AddMonths(1).Month & "/" & DateStart.Year).AddDays(-1)
If differenceInMonth <> 0 Then
differenceInMonth -= 1
Else
differenceInMonth = 11
differenceInYear -= 1
End If
differenceInDay = myDate.Day - DateStart.Day + DateEnd.Day
End If
prop_DifferenceInDay = differenceInDay
prop_DifferenceInMonth = differenceInMonth
prop_DifferenceInYear = differenceInYear
Return Me
End Function
Public ReadOnly Property DifferenceInDay() As Integer
Get
Return prop_DifferenceInDay
End Get
End Property
Public ReadOnly Property DifferenceInMonth As Integer
Get
Return prop_DifferenceInMonth
End Get
End Property
Public ReadOnly Property DifferenceInYear As Integer
Get
Return prop_DifferenceInYear
End Get
End Property
End Class
here you go get_the_category( $post->ID );
will return the array of categories of that post you need to loop through the array
$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}
Fix the looming 2002 socket error – which is linking where MySQL places the socket and where OSX thinks it should be, MySQL puts it in /tmp and OSX looks for it in /var/mysql the socket is a type of file that allows mysql client/server communication.
sudo mkdir /var/mysql
and then
sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock
source: http://coolestguidesontheplanet.com/get-apache-mysql-php-phpmyadmin-working-osx-10-10-yosemite/
by using css we can easily add width to the column.
here im adding first column width to 300px on header (thead)
::ng-deep table thead tr:last-child th:nth-child(1) {_x000D_
width: 300px!important;_x000D_
}
_x000D_
now add same width to tbody first column by,
<table datatable class="display table ">_x000D_
<thead>_x000D_
<tr>_x000D_
<th class="text-left" style="width: 300px!important;">name</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
_x000D_
<tr>_x000D_
<td class="text-left" style="width: 300px!important;">jhon mathew</td>_x000D_
_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
by this way you can easily change width by changing the order of nth child. if you want 3 column then ,add nth-child(3)
I think this is closer to the answer you're looking for:
<input type="file">
$file = $(file);
var filename = fileElement[0].files[0].name;
This would be a proper CSS solution which works for IE8/9 as well (IE8 with html5shiv ofcourse): codepen
nav {
margin:0px auto;
height:50px;
background-color:gray;
padding:10px;
border:2px solid red;
position: relative;
color: white;
z-index: 1;
}
nav:after {
content: '';
background: black;
display: block;
position: absolute;
margin: 10px;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: -1;
}
Use runlike from git repository https://github.com/lavie/runlike
To install runlike
pip install runlike
As it accept container id as an argument so to extract container id use following command
docker ps -a -q
You are good to use runlike to extract complete docker run command with following command
runlike <docker container ID>
In addition to
Mac:
~/.vagrant.d/
Windows:
C:\Users\%userprofile%\.vagrant.d\boxes
You have to delete the files in VirtualBox/OtherVMprovider to make a clean start.
The one-to-many table relationship looks as follows:
In a relational database system, a one-to-many table relationship links two tables based on a Foreign Key
column in the child which references the Primary Key
of the parent table row.
In the table diagram above, the post_id
column in the post_comment
table has a Foreign Key
relationship with the post
table id Primary Key
column:
ALTER TABLE
post_comment
ADD CONSTRAINT
fk_post_comment_post_id
FOREIGN KEY (post_id) REFERENCES post
The one-to-one table relationship looks as follows:
In a relational database system, a one-to-one table relationship links two tables based on a Primary Key
column in the child which is also a Foreign Key
referencing the Primary Key
of the parent table row.
Therefore, we can say that the child table shares the Primary Key
with the parent table.
In the table diagram above, the id
column in the post_details
table has also a Foreign Key
relationship with the post
table id
Primary Key
column:
ALTER TABLE
post_details
ADD CONSTRAINT
fk_post_details_id
FOREIGN KEY (id) REFERENCES post
The many-to-many table relationship looks as follows:
In a relational database system, a many-to-many table relationship links two parent tables via a child table which contains two Foreign Key
columns referencing the Primary Key
columns of the two parent tables.
In the table diagram above, the post_id
column in the post_tag
table has also a Foreign Key
relationship with the post
table id Primary Key
column:
ALTER TABLE
post_tag
ADD CONSTRAINT
fk_post_tag_post_id
FOREIGN KEY (post_id) REFERENCES post
And, the tag_id
column in the post_tag
table has a Foreign Key
relationship with the tag
table id Primary Key
column:
ALTER TABLE
post_tag
ADD CONSTRAINT
fk_post_tag_tag_id
FOREIGN KEY (tag_id) REFERENCES tag
Couldn't you just pass the arguments
array along?
function mainfunc (func){
// remove the first argument containing the function name
arguments.shift();
window[func].apply(null, arguments);
}
function calledfunc1(args){
// Do stuff here
}
function calledfunc2(args){
// Do stuff here
}
mainfunc('calledfunc1','hello','bye');
mainfunc('calledfunc2','hello','bye','goodbye');
You need set the keyframes animation in you CSS. And use the keyframe with jQuery:
$('#myTest').css({"animation":"my-animation 2s infinite"});
_x000D_
#myTest {_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
background: black;_x000D_
}_x000D_
_x000D_
@keyframes my-animation {_x000D_
0% {_x000D_
background: red; _x000D_
}_x000D_
50% {_x000D_
background: blue; _x000D_
}_x000D_
100% {_x000D_
background: green; _x000D_
}_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myTest"></div>
_x000D_
Try setting: AllowOverride All
.
Second most common issue is not having mod rewrite enabled: a2enmod rewrite
and then restart apache.
Riya,
Making the assumption that you want to split on the full stop (.), then here's an approach that would capture all occurences:
// add @ to the string to allow split over multiple lines
// (display purposes to save scroll bar appearing on SO question :))
string strBig = @"Retrieves a substring from this instance.
The substring starts at a specified character position. great";
// split the string on the fullstop, if it has a length>0
// then, trim that string to remove any undesired spaces
IEnumerable<string> subwords = strBig.Split('.')
.Where(x => x.Length > 0).Select(x => x.Trim());
// iterate around the new 'collection' to sanity check it
foreach (var subword in subwords)
{
Console.WriteLine(subword);
}
enjoy...
rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.
There is a performance comparison with YAJL and JsonCPP.
Update:
I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.
the first two bounds default to 0 and the length of the sequence, as before, and a stride of -1 indicates that the slice should go from right to left instead of the usual left to right. The effect, therefore, is to reverse the sequence.
name="ravi"
print(name[::-1]) #ivar
easiest way is:
first_key = my_dict.keys()[0]
but some times you should be more careful and assure that your entity is a valuable list so:
first_key = list(my_dict.keys())[0]
I just would like to add how it may happen that a reference breaks.
On my system (Windows 7 64-bit), when a BSOD happens, some of the stored reference files (most likely currently opened/being written into when BSOD happened) are overwritten with NULL
characters (ASCII 0).
As others mentioned, to fix it, it's enough to just delete those invalid reference files and re-fetch or re-pull the repository.
Error: cannot lock ref 'refs/remotes/origin/some/branch': unable to resolve reference 'refs/remotes/origin/some/branch': reference broken
Solution: delete the file %repo_root%/.git/refs/remotes/origin/some/branch
Replace back slashes \ with forward slashes / when running windows machine
Use:
$.ajax({
url: 'feed/4', type: 'POST', data: "_METHOD=PUT&accessToken=63ce0fde", success: function(data) {
console.log(data);
}
});
Always remember to use _METHOD=PUT
.
If you're using PhpMyAdmin, you can now:
I had over 250 tables to convert. It took a little over 5 minutes.
My recommendation is to checkout the code on a deployment machine, install dependencies as needed (this includes NOT installing dev dependencies if the code goes to production), and then move all the files to the target machine.
Why?
composer install
Long story short: Use Composer in an environment you can control. Your development machine does qualify because you already have all the things that are needed to operate Composer.
What's the correct way to deploy this without installing the -dev dependencies?
The command to use is
composer install --no-dev
This will work in any environment, be it the production server itself, or a deployment machine, or the development machine that is supposed to do a last check to find whether any dev requirement is incorrectly used for the real software.
The command will not install, or actively uninstall, the dev requirements declared in the composer.lock file.
If you don't mind deploying development software components on a production server, running composer install
would do the same job, but simply increase the amount of bytes moved around, and also create a bigger autoloader declaration.
what about using a hash table for the job, like this?
first, creating a "hash map" generic function, extending the Sequence protocol.
extension Sequence where Element: Hashable {
func hashMap() -> [Element: Int] {
var dict: [Element: Int] = [:]
for (i, value) in self.enumerated() {
dict[value] = i
}
return dict
}
}
This extension will work as long as the items in the array conform to Hashable, like integers or strings, here is the usage...
let numbers = Array(0...50)
let hashMappedNumbers = numbers.hashMap()
let numToDetect = 35
let indexOfnumToDetect = hashMappedNumbers[numToDetect] // returns the index of the item and if all the elements in the array are different, it will work to get the index of the object!
print(indexOfnumToDetect) // prints 35
But for now, let's just focus in check if the element is in the array.
let numExists = indexOfnumToDetect != nil // if the key does not exist
means the number is not contained in the collection.
print(numExists) // prints true
I'm posting my solution for the other sleep-deprived souls out there:
If you're using RVM, double-check that you're in the correct folder, using the correct ruby version and gemset. I had an array of terminal tabs open, and one of them was in a different directory. typing "rails console" produced the error because my default rails distro is 2.3.x.
I noticed the error on my part, cd'd to the correct directory, and my .rvmrc file did the rest.
RVM is not like Git. In git, changing branches in one shell changes it everywhere. It's literally rewriting the files in question. RVM, on the other hand, is just setting shell variables, and must be set for each new shell you open.
In case you're not familiar with .rvmrc, you can put a file with that name in any directory, and rvm will pick it up and use the version/gemset specified therein, whenever you change to that directory. Here's a sample .rvmrc file:
rvm use 1.9.2@turtles
This will switch to the latest version of ruby 1.9.2 in your RVM collection, using the gemset "turtles". Now you can open up a hundred tabs in Terminal (as I end up doing) and never worry about the ruby version it's pointing to.
If you are using PHP7.1 ( try php -version
to find your PHP version)
sudo apt-get install php7.1-curl
then restart apache
sudo service apache2 restart
I tried:
rm -rf .git
and also
Git keeps all of its files in the .git directory. Just remove that one and init again.
Neither worked for me. Here's what did:
.git
Then create / restore the project from backup:
in your action performed method, call:
label1.setText(nameField.getText());
This way, when the button is clicked, label will be updated to the nameField text.
I think you can also execute the pwd() function on the particular node:
node {
def PWD = pwd();
...
}
You should include <string.h>
(or its C++ equivalent, <cstring>
).
You'll see this in all the directives:
When you use brackets, it means you're passing a bindable property (a variable).
<a [routerLink]="routerLinkVariable"></a>
So this variable (routerLinkVariable) could be defined inside your class and it should have a value like below:
export class myComponent {
public routerLinkVariable = "/home"; // the value of the variable is string!
But with variables, you have the opportunity to make it dynamic right?
export class myComponent {
public routerLinkVariable = "/home"; // the value of the variable is string!
updateRouterLinkVariable(){
this.routerLinkVariable = '/about';
}
Where as without brackets you're passing string only and you can't change it, it's hard coded and it'll be like that throughout your app.
<a routerLink="/home"></a>
UPDATE :
The other speciality about using brackets specifically for routerLink is that you can pass dynamic parameters to the link you're navigating to:
So adding a new variable
export class myComponent {
private dynamicParameter = '129';
public routerLinkVariable = "/home";
Updating the [routerLink]
<a [routerLink]="[routerLinkVariable,dynamicParameter]"></a>
When you want to click on this link, it would become:
<a href="/home/129"></a>
Errors are stored in the nginx log file. You can specify it in the root of the nginx configuration file:
error_log /var/log/nginx/nginx_error.log warn;
On Mac OS X with Homebrew, the log file was found by default at the following location:
/usr/local/var/log/nginx
Use PATINDEX
DECLARE @input VARCHAR(10)='102030.40'
SELECT PATINDEX('%[^0-9]%',RTRIM(LTRIM(@input))) AS IsNumber
reference http://www.intellectsql.com/post-how-to-check-if-the-input-is-numeric/
Just use dt.Clear()
Also you can set your TableAdapter/DataAdapter to clear before it fills with data.
Write the function inline, and the interpreter is smart enough to know you're writing a function. Do it like this, and it assumes it's just a string (which it technically is).
If you open the references folder and locate system.data.entity, click the item, then check the runtime version number in the Properties explorer, you will see the sub version as well. Mine for instance shows v4.0.30319 with the Version property showing 4.0.0.0.
You can try this to avoid indicating custom date and if there is need to display start and end dates of current month:
LocalDate start = LocalDate.now().minusDays(LocalDate.now().getDayOfMonth()-1);
LocalDate end = LocalDate.now().minusDays(LocalDate.now().getDayOfMonth()).plusMonths(1);
System.out.println("Start of month: " + start);
System.out.println("End of month: " + end);
Result:
> Start of month: 2019-12-01
> End of month: 2019-12-30
Friend, don't worry, if you have any application installed built in codeigniter and you wanna add some language pack just follow these steps:
1. Add language files in folder application/language/arabic (i add arabic lang in sma2 built in ci)
2. Go to the file named setting.php
in application/modules/settings/views/setting.php. Here you find the array
<?php /*
$lang = array (
'english' => 'English',
'arabic' => 'Arabic', // i add this here
'spanish' => 'Español'
Now save and run the application. It's worked fine.
To convert $date
from dd-mm-yyyy hh:mm:ss
to a proper MySQL datetime
I go like this:
$date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s');
You can do the check at first and then use the switch as you like.
For example:
string str = "parameter"; // test1..test2..test3....
if (!message.Contains(str)) return ;
Then
switch(str)
{
case "test1" : {} break;
case "test2" : {} break;
default : {} break;
}
If you want a list of lists:
>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]
If a list of tuples is OK:
>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]
function scroll_to_anchor(anchor_id){
var tag = $("#"+anchor_id+"");
$('html,body').animate({scrollTop: tag.offset().top},'slow');
}
SELECT t1.ColumnID,
CASE
WHEN NOT EXISTS( SELECT t2.FieldText
FROM Table t2
WHERE t2.ColumnID = t1.ColumnID)
THEN t1.FieldText
ELSE t2.FieldText
END FieldText
FROM Table1 t1, Table2 t2
http://thiamteck.blogspot.com/2008/04/spring-propertyplaceholderconfigurer.html points out that "local properties" defined on the bean itself will be considered defaults to be overridden by values read from files:
<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>my_config.properties</value></property>
<property name="properties">
<props>
<prop key="entry.1">123</prop>
</props>
</property>
</bean>
git apply --reverse --reject example.patch
When you created a patch file with the branch names reversed:
ie. git diff feature_branch..master
instead of git diff master..feature_branch
NOT a solution, rather a TEMPORARY solution which only works only for the current editor and current session:
Simply right click on the place where the line-numbers should be, and there you'll see a small menu.
then, mark the "Show Line Numbers" option.
Please note that this only works on a per-file basis, however. Enjoy.
In my case i had to load images on radio button click,
I just uses the regular onclick
event and it worked for me.
<input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion" onclick="return get_images(this, {{color.id}})">
<script>
function get_images(obj, color){
console.log($("input[type='radio'][name='colors']:checked").val());
}
</script>
I've been using ClockPick.
onclick
propertySuppose you added your click event inline, like this :
<button id="myButton" onclick="alert('test')">Married</button>
Then, you can remove the event like this :
$("#myButton").prop('onclick', null); // Removes 'onclick' property if found
click
event listenersSuppose you added your click event by defining an event listener, like this :
$("button").on("click", function() { alert("clicked!"); });
... or like this:
$("button").click(function() { alert("clicked!"); });
Then, you can remove the event like this :
$("#myButton").off('click'); // Removes other events if found
If you're uncertain how your event has been added, you can combine both, like this :
$("#myButton").prop('onclick', null) // Removes 'onclick' property if found
.off('click'); // Removes other events if found
Good question - I think the only way to achieve this is to filter the items in the select.
You can do this through a jquery plugin. Check the following link, it describes how to achieve something similar to what you need. Thanks
jQuery disable SELECT options based on Radio selected (Need support for all browsers)
For me the solution was one of the methods had to be void, I had it as Boolean.
Code posted by you is correct and should have worked. But check exactly what you have in the char*
. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL
. Check what you have in the char*
against maximum values that float
and double
can represent on your computer.
Check this page for strtod
reference and this page for atof
reference.
I have tried the example you provided in both Windows and Linux and it worked fine.
I built on sabithpocker's idea and made a more generalized version that lets you control more than one selectbox from a given trigger.
I assigned the selectboxes I wanted to be controlled the classname "switchable," and cloned them all like this:
$j(this).data('options',$j('select.switchable option').clone());
and used a specific naming convention for the switchable selects, which could also translate into classes. In my case, "category" and "issuer" were the select names, and "category_2" and "issuer_1" the class names.
Then I ran an $.each on the select.switchable groups, after making a copy of $(this) for use inside the function:
var that = this;
$j("select.switchable").each(function() {
var thisname = $j(this).attr('name');
var theseoptions = $j(that).data('options').filter( '.' + thisname + '_' + id );
$j(this).html(theseoptions);
});
By using a classname on the ones you want to control, the function will safely ignore other selects elsewhere on the page (such as the last one in the example on Fiddle).
Here's a Fiddle with the complete code:
this would probably call for a many-to-many relation ship as follows
public class Person{
private Long personId;
@manytomany
private Set skills;
//Getters and setters
}
public class Skill{
private Long skillId;
private String skillName;
@manyToMany(MappedBy="skills,targetClass="Person")
private Set persons; // (people would not be a good convenion)
//Getters and setters
}
you may need to define a joinTable + JoinColumn but it will possible work also without...
You can use b
character in front of a string literal:
import hashlib
print(hashlib.md5(b"Hello MD5").hexdigest())
print(hashlib.md5("Hello MD5".encode('utf-8')).hexdigest())
Out:
e5dadf6524624f79c3127e247f04b548
e5dadf6524624f79c3127e247f04b548
i have same problem what i did i just downloaded 32-bit dll and added it to my bin folder this is solved my problem
As one would expect, WebKit's support of tel:
extends to the Android mobile browser as well - FYI
Similar to Andrews which is #1:
Something that worked for me is:
name = "Blue Jeans"
Product.find_by("lower(name) = ?", name.downcase)
This eliminates the need to do a #where
and #first
in the same query. Hope this helps!
In python 3, to get text output:
import io
import urllib.request
response = urllib.request.urlopen("http://google.com")
text = io.TextIOWrapper(response)
I have updated the controller to:
.controller('BusinessCtrl',
function ($scope, $http, $location, Business, BusinessService, UserService, Photo) {
$scope.$watch('createBusinessForm.$valid', function(newVal) {
//$scope.valid = newVal;
$scope.informationStatus = true;
});
...
Neither of them worked for me for some reason.
I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.
And finally this worked for me.
cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
connect.commit()
Looking under the hood, the two statements will be transformed into different query representations. Depending on the QueryProvider
of Collection
, this might be optimized away or not.
When this is a linq-to-object call, multiple where clauses will lead to a chain of IEnumerables that read from each other. Using the single-clause form will help performance here.
When the underlying provider translates it into a SQL statement, the chances are good that both variants will create the same statement.
Check the MySQL Datetime Functions:
Try this:
SELECT *
FROM tableA
WHERE YEAR(columnName) = YEAR(CURRENT_DATE()) AND
MONTH(columnName) = MONTH(CURRENT_DATE());
Item #1. Putting a break
within the foreach
loop does exit the loop, but it does not stop the pipeline. It sounds like you want something like this:
$todo=$project.PropertyGroup
foreach ($thing in $todo){
if ($thing -eq 'some_condition'){
break
}
}
Item #2. PowerShell lets you modify an array within a foreach
loop over that array, but those changes do not take effect until you exit the loop. Try running the code below for an example.
$a=1,2,3
foreach ($value in $a){
Write-Host $value
}
Write-Host $a
I can't comment on why the authors of PowerShell allowed this, but most other scripting languages (Perl, Python and shell) allow similar constructs.
This is how I was able to solve the problem when I faced it
Conda itself provides a quite detailed guidance about installing non-conda packages. Details can be found here: https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-pkgs.html
The basic idea is to use conda-forge. If it doesn't work, activate the environment and use pip.
192.30.252.128 is the current IP of github.com which can be set in your local DNS (/etc/hosts in Linux and C:\Windows\System32\drivers\etc\hosts)
Classes in the default package cannot be imported by classes in packages. This is why you should not use the default package.
There is a section in the MySQL manual on how to reset the root password which will solve your problem.
Here is more functional example with some ES6 features:
'use strict';
const React = require('react');
function renderArticles(articles) {
if (articles.length > 0) {
return articles.map((article, index) => (
<Article key={index} article={article} />
));
}
else return [];
}
const Article = ({article}) => {
return (
<article key={article.id}>
<a href={article.link}>{article.title}</a>
<p>{article.description}</p>
</article>
);
};
const Articles = React.createClass({
render() {
const articles = renderArticles(this.props.articles);
return (
<section>
{ articles }
</section>
);
}
});
module.exports = Articles;
I am heavily tempted to close this as a duplicate; this question appears to be answered in many different ways all over the site:
I did that in the following way for an image, you should be able to do it for text using similar steps.
// folder & name of image on PC
File fileObj = new File("C:\\Displayable\\imgcopy.jpg");
Boolean testB = fileObj.createNewFile();
System.out.println("Test this file eeeeeeeeeeeeeeeeeeee "+testB);
// image on server
URL url = new URL("http://localhost:8181/POPTEST2/imgone.jpg");
InputStream webIS = url.openStream();
FileOutputStream fo = new FileOutputStream(fileObj);
int c = 0;
do {
c = webIS.read();
System.out.println("==============> " + c);
if (c !=-1) {
fo.write((byte) c);
}
} while(c != -1);
webIS.close();
fo.close();
select *
from emp
where rownum <= &upperlimit
minus
select *
from emp
where rownum <= &lower limit ;
UPDATE TABLE
SET EndDate = CAST('2017-12-31' AS DATE)
WHERE Id = '123'
StringBuffer sb = new SringBuffer();
// do something wiht it
sb = new StringBuffer();
i think this code is faster.
Use DataSet(C#) with JavaScript. A simple function for creating a JSON stream with DataSet input. Create JSON content like (multi table dataset):
[[{a:1,b:2,c:3},{a:3,b:5,c:6}],[{a:23,b:45,c:35},{a:58,b:59,c:45}]]
Just client side, use eval. For example,
var d = eval('[[{a:1,b:2,c:3},{a:3,b:5,c:6}],[{a:23,b:45,c:35},{a:58,b:59,c:45}]]')
Then use:
d[0][0].a // out 1 from table 0 row 0
d[1][1].b // out 59 from table 1 row 1
// Created by Behnam Mohammadi And Saeed Ahmadian
public string jsonMini(DataSet ds)
{
int t = 0, r = 0, c = 0;
string stream = "[";
for (t = 0; t < ds.Tables.Count; t++)
{
stream += "[";
for (r = 0; r < ds.Tables[t].Rows.Count; r++)
{
stream += "{";
for (c = 0; c < ds.Tables[t].Columns.Count; c++)
{
stream += ds.Tables[t].Columns[c].ToString() + ":'" +
ds.Tables[t].Rows[r][c].ToString() + "',";
}
if (c>0)
stream = stream.Substring(0, stream.Length - 1);
stream += "},";
}
if (r>0)
stream = stream.Substring(0, stream.Length - 1);
stream += "],";
}
if (t>0)
stream = stream.Substring(0, stream.Length - 1);
stream += "];";
return stream;
}
This may sound Evil™ and I haven't tested it, but how about initializing all values in an array at allocation to '\0'
and then using strlen()
? This would give you your so-called real value since it would stop counting at the first '\0'
it encounters.
Well, now that I think about it though, please don't Ever™ do this. Unless, you want to land in a pile of dirty memory.
Also, for the allocated memory or the total memory you may use the following functions if your environment provides them:
You have to export
it from your NgModule
:
@NgModule({
declarations: [TaskCardComponent],
exports: [TaskCardComponent],
imports: [MdCardModule],
providers: []
})
export class TaskModule{}
As per my understanding data structure is any data residing in memory of any electronic system that can be efficiently managed. Many times it is a game of memory or faster accessibility of data. In terms of memory again, there are tradeoffs done with the management of data based on cost to the company of that end product. Efficiently managed tells us how best the data can be accessed based on the primary requirement of the end product. This is a very high level explanation but data structures is a vast subjects. Most of the interviewers dive into data structures that they can afford to discuss in the interviews depending on the time they have, which are linked lists and related subjects.
Now, these data types can be divided into primitive, abstract, composite, based on the way they are logically constructed and accessed.
I hope this helps you dive in.
You have to use a Class
instance because of the generic type erasure during compilation.
public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
try {
return clazz.cast(o);
} catch(ClassCastException e) {
return null;
}
}
The declaration of that method is:
public T cast(Object o)
This can also be used for array types. It would look like this:
final Class<int[]> intArrayType = int[].class;
final Object someObject = new int[]{1,2,3};
final int[] instance = convertInstanceOfObject(someObject, intArrayType);
Note that when someObject
is passed to convertToInstanceOfObject
it has the compile time type Object
.
I tried :
^(1[ \-\+]{0,3}|\+1[ -\+]{0,3}|\+1|\+)?((\(\+?1-[2-9][0-9]{1,2}\))|(\(\+?[2-8][0-9][0-9]\))|(\(\+?[1-9][0-9]\))|(\(\+?[17]\))|(\([2-9][2-9]\))|([ \-\.]{0,3}[0-9]{2,4}))?([ \-\.][0-9])?([ \-\.]{0,3}[0-9]{2,4}){2,3}$
I took care of special country codes like 1-97... as well. Here are the numbers I tested against (from Puneet Lamba and MCattle):
***** PASS *****
18005551234
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1.800.555.1234
+1.800.555.1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
(+230) 5 911 4450
123345678
(1) 345 654 67
+1 245436
1-976 33567
(1-734) 5465654
+(230) 2 345 6568
***** CORRECTLY FAILING *****
(003) 555-1212
(103) 555-1212
(911) 555-1212
1-800-555-1234p
800x555x1234
+1 800 555x1234
***** FALSE POSITIVES *****
180055512345
1 800 5555 1234
+867 800 555 1234
1 (800) 555-1234
86 800 555 1212
Originally posted here: Regular expression to match standard 10 digit phone number
Convert both completed
and total
to double
or at least cast them to double
when doing the devision. I.e. cast the varaibles to double not just the result.
Fair warning, there is a floating point precision problem when working with float
and double
.
It is a duplicate of this question, with an answer that contains a time measurement of the different methods.
Conclusion: Use [void]
or > $null
.
By using Reflector, you can see, that Contains is implemented using IndexOf. Here's the implementation.
public bool Contains(string value)
{
return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}
So Contains is likely a wee bit slower than calling IndexOf directly, but I doubt that it will have any significance for the actual performance.
One way to get some clues is to create a PDF file consisting of a blank page. I have CutePDF Writer on my computer, and made a blank Wordpad document of one page. Printed to a .pdf file, and then opened the .pdf file using Notepad.
Next, use a copy of this file and eliminate lines or blocks of text that might be of interest, then reload in Acrobat Reader. You'd be surprised at how little information is needed to make a working one-page PDF document.
I'm trying to make up a spreadsheet to create a PDF form from code.
Another way
@Html.TextAreaFor(model => model.Comments[0].Comment)
And in your css do this
textarea
{
font-family: inherit;
width: 650px;
height: 65px;
}
That DataType dealie allows carriage returns in the data, not everybody likes those.
I have to destroy the modal right after it is closed through a button click, and so I came up with the following.
$("#closeModal").click(function() {
$("#modal").modal('hide').on('hidden.bs.modal', function () {
$("#modal").remove();
});
});
Note that this works with Bootstrap 3.
There had been a similar question here: When should a class be Comparable and/or Comparator?
I would say the following: Implement Comparable for something like a natural ordering, e.g. based on an internal ID
Implement a Comparator if you have a more complex comparing algorithm, e.g. multiple fields and so on.
You want a simple for
loop:
total_count=0
for file in $(find . -name *.php -print)
do
count=$(wc -l $file)
let total_count+=count
done
echo "$total_count"
You can use format keyword as well for this.Format method will replace {} placeholder to the variable which you passed to the format method as an argument.
if re.search(r"\b(?=\w)**{}**\b(?!\w)".**format(TEXTO)**, subject, re.IGNORECASE):
# Successful match**strong text**
else:
# Match attempt failed
For me, I needed to do the following:
1- Comment out bind 127.0.0.1
2- Change protected-mode
to no
3- Protect my server with iptables
(https://www.digitalocean.com/community/tutorials/how-to-implement-a-basic-firewall-template-with-iptables-on-ubuntu-14-04)
The official postgres docker image will run .sql
scripts found in the /docker-entrypoint-initdb.d/
folder.
So all you need is to create the following sql script:
init.sql
CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
and add it in your Dockerfile:
Dockerfile
FROM library/postgres
COPY init.sql /docker-entrypoint-initdb.d/
But since July 8th, 2015, if all you need is to create a user and database, it is easier to just make use to the POSTGRES_USER
, POSTGRES_PASSWORD
and POSTGRES_DB
environment variables:
docker run -e POSTGRES_USER=docker -e POSTGRES_PASSWORD=docker -e POSTGRES_DB=docker library/postgres
or with a Dockerfile:
FROM library/postgres
ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB docker
From the documentation of the postgres Docker image, it is said that
[...] it will source any *.sh script found in that directory [
/docker-entrypoint-initdb.d
] to do further initialization before starting the service
What's important here is "before starting the service". This means your script make_db.sh will be executed before the postgres service would be started, hence the error message "could not connect to database postgres".
After that there is another useful piece of information:
If you need to execute SQL commands as part of your initialization, the use of Postgres single user mode is highly recommended.
Agreed this can be a bit mysterious at the first look. What it says is that your initialization script should start the postgres service in single mode before doing its actions. So you could change your make_db.ksh script as follows and it should get you closer to what you want:
NOTE, this has changed recently in the following commit. This will work with the latest change:
export PGUSER=postgres
psql <<- EOSQL
CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL
Previously, the use of --single
mode was required:
gosu postgres postgres --single <<- EOSQL
CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL
To see the contents of array you can use.
1) print_r($array);
or if you want nicely formatted array then:
echo '<pre>'; print_r($array); echo '</pre>';
2) use var_dump($array)
to get more information of the content in the array like datatype and length.
3) you can loop the array using php's foreach();
and get the desired output. more info on foreach in php's documentation website:
http://in3.php.net/manual/en/control-structures.foreach.php
import subprocess,os,threading,time
from queue import Queue
lock=threading.Lock()
_start=time.time()
def check(n):
with open(os.devnull, "wb") as limbo:
ip="192.168.21.{0}".format(n)
result=subprocess.Popen(["ping", "-n", "1", "-w", "300", ip],stdout=limbo, stderr=limbo).wait()
with lock:
if not result:
print (ip, "active")
else:
pass
def threader():
while True:
worker=q.get()
check(worker)
q.task_done()
q=Queue()
for x in range(255):
t=threading.Thread(target=threader)
t.daemon=True
t.start()
for worker in range(1,255):
q.put(worker)
q.join()
print("Process completed in: ",time.time()-_start)
I think this will be better one.
Use a process group so as to enable sending a signal to all the process in the groups. For that, you should attach a session id to the parent process of the spawned/child processes, which is a shell in your case. This will make it the group leader of the processes. So now, when a signal is sent to the process group leader, it's transmitted to all of the child processes of this group.
Here's the code:
import os
import signal
import subprocess
# The os.setsid() is passed in the argument preexec_fn so
# it's run after the fork() and before exec() to run the shell.
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE,
shell=True, preexec_fn=os.setsid)
os.killpg(os.getpgid(pro.pid), signal.SIGTERM) # Send the signal to all the process groups
It feels like all of the array_combine()
answers are all copying the same "mistake" (the unnecessary call of array_values()
).
array_combine()
ignores the keys of both parameters that it receives.
Code: (Demo)
$array = [
2 => (object)['title' => 'Section', 'linked' => 1],
1 => (object)['title' => 'Sub-Section', 'linked' => 1],
0 => (object)['title' => 'Sub-Sub-Section', 'linked' => null]
];
var_export(array_combine(range(1, count($array)), $array));
Output:
array (
1 =>
(object) array(
'title' => 'Section',
'linked' => 1,
),
2 =>
(object) array(
'title' => 'Sub-Section',
'linked' => 1,
),
3 =>
(object) array(
'title' => 'Sub-Sub-Section',
'linked' => NULL,
),
)
How much shorter do you want it to be? It is only an extra 2 lines AND it is clear and concise logic.
I think the more important thing you need to decide is if null
is a valid value or not. If they are not valid, you should write you code to prevent it from happening. Then you would not need this kind of check. If you go get an exception while doing a foreach
loop, that is a sign that there is a bug somewhere else in your code.
val jsonString =
"""
|{
| "languages": [{
| "name": "English",
| "is_active": true,
| "completeness": 2.5
| }, {
| "name": "Latin",
| "is_active": false,
| "completeness": 0.9
| }]
|}
""".stripMargin
val result = JSON.parseFull(jsonString).map {
case json: Map[String, List[Map[String, Any]]] =>
json("languages").map(l => (l("name"), l("is_active"), l("completeness")))
}.get
println(result)
assert( result == List(("English", true, 2.5), ("Latin", false, 0.9)) )
Use this code for API 21 or above. This works and gives better result compared to the other answers, it detects perfectly the foreground process.
if (Build.VERSION.SDK_INT >= 21) {
String currentApp = null;
UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> applist = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
if (applist != null && applist.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : applist) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:
{1, "one"}
{2, "two"}
{30, "thirty"}
You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.
After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.
In most scenarios, column name is fit for them. But maybe you write the code like follows:
class UserModel(BaseModel):
user_id = Column("user_id", INT, primary_key=True)
email = Column("user_email", STRING)
the column.name "user_email" while the field name is "email", the column.name could not work well as before.
To run one project at a time in same solution
Open Solution explorer window -> Open Solution for Project -> Right click on it -> Select Properties from drop down list (Alt+Enter)-> Common Properties -> select Startup Project you will see "current selection,single selection and multiple selection from that select "Current Selection" this will help you to run one project at a time in same solution workspace having different coding.
Working example. Notes below.
class Animal {
constructor(public name) {
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
alert(this.name + " is Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
alert(this.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You don't need to manually assign the name to a public variable. Using public name
in the constructor definition does this for you.
You don't need to call super(name)
from the specialised classes.
Using this.name
works.
Notes on use of super
.
This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from Animal
is not dissimilar to the behaviour in other languages. You need to specify the super
keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move()
or this.move()
you would be dealing with the specialised Snake
or Horse
function, so using super.move()
explicitly calls the base class function.
There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name
and this.name
- there is simply this.name
. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.
Here is my answer:
services.msc
, Enter"D:/Program Files/MySQL/MySQL Server 5.6/bin\mysqld" --defaults-file="D:\ProgramData\MySQL\MySQL Server 5.6\my.ini" MySQL56
Full answer here: https://stackoverflow.com/a/20136523/1316649
short answer, specific to OAuth2,
I like the simple solution using windows functions:
select t.*
from (select student.*, su.subname, max(mark) over (partition by subid) as maxmark
from marks m join
students st
on m.stid = st.stid join
subject su
on m.subid = su.subid
) t
where t.mark = maxmark
Or, alternatively:
select t.*
from (select student.*, su.subname, rank(mark) over (partition by subid order by mark desc) as markseqnum
from marks m join
students st
on m.stid = st.stid join
subject su
on m.subid = su.subid
) t
where markseqnum = 1
You've obviously considered lots of ways to write the SQL such that it prints out okay, but how about changing the 'print' statement you use for debug logging, rather than writing your SQL in ways you don't like? Using your favourite option above, how about a logging function such as this:
def debugLogSQL(sql):
print ' '.join([line.strip() for line in sql.splitlines()]).strip()
sql = """
select field1, field2, field3, field4
from table"""
if debug:
debugLogSQL(sql)
This would also make it trivial to add additional logic to split the logged string across multiple lines if the line is longer than your desired length.
I just had the exact same problem and it turned out to be caused by the fact that 2 projects in the same solution were referencing a different version of the 3rd party library.
Once I corrected all the references everything worked perfectly.
If you only want to add Datapoints above the bars, you could easily do it with:
for i in range(len(frequencies)): # your number of bars
plt.text(x = x_values[i]-0.25, #takes your x values as horizontal positioning argument
y = y_values[i]+1, #takes your y values as vertical positioning argument
s = data_labels[i], # the labels you want to add to the data
size = 9) # font size of datalabels
input location.bat
@echo off
cls
set /p "location"="bob"
echo We're working with %location%
pause
output
We're working with bob
(mistakes u done : space
and " "
)
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
This jQuery function captures all errors in svg images and replaces the file extension with an alternate extension
Please open the console to see the error loading image svg
(function($){_x000D_
$('img').on('error', function(){_x000D_
var image = $(this).attr('src');_x000D_
if ( /(\.svg)$/i.test( image )) {_x000D_
$(this).attr('src', image.replace('.svg', '.png'));_x000D_
}_x000D_
}) _x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<img src="https://jsfiddle.net/img/logo.svg">
_x000D_
Use the DATEDIFF
function with a datepart of day
.
SELECT ...
FROM ...
WHERE DATEDIFF(day, date1, date2) >= 0
Note that if you want to test that date1
<= date2
then you need to test that DATEDIFF(day, date1, date2) >= 0
, or alternatively you could test DATEDIFF(day, date2, date1) <= 0
.
Solution for Windows:
.box
filevagrant box add --name name_of_my_box 'name_of_my_box.box'
vagrant box list
should show the new box in the listSolution for MAC:
.box
filevagrant box add --name name_of_my_box "./name_of_my_box.box"
vagrant box list
should show the new box in the listHere's an alternative way to do the same call. And your type should always be in CAPS, eg. type:"GET" / type:"POST".
$.ajax({
url:/ControllerName/ActionName,
data: "id=" + Id + "¶m2=" + param2,
type: "GET",
success: function(data){
// code here
},
error: function(passParams){
// code here
}
});
Another alternative will be to use the data-ajax on a link.
<a href="/ControllerName/ActionName/" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#_content">Click Me!</a>
Assuming u had a div with the I'd _content, this will call the action and replace the content inside that div with the data returned from that action.
<div id="_content"></div>
Not really a direct answer to ur question but its some info u should be aware of ;).
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.You can use this code
$(document).keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert('You pressed a ENTER key.');
}
});
If you use Django, it has a built in @classproperty
decorator.
from django.utils.decorators import classproperty
You need the following functions to do this in PHP:
strpos
Find the position of the first occurrence of a substring in a string
strrpos
Find the position of the last occurrence of a substring in a string
substr
Return part of a string
Here's the signature of the substr
function:
string substr ( string $string , int $start [, int $length ] )
The signature of the substring
function (Java) looks a bit different:
string substring( int beginIndex, int endIndex )
substring
(Java) expects the end-index as the last parameter, but substr
(PHP) expects a length.
It's not hard, to get the desired length by the end-index in PHP:
$sub = substr($str, $start, $end - $start);
Here is the working code
$start = strpos($message, '-') + 1;
if ($req_type === 'RMT') {
$pt_password = substr($message, $start);
}
else {
$end = strrpos($message, '-');
$pt_password = substr($message, $start, $end - $start);
}
As in Laravel >= 5.3, if someone is still curious how to do so in easy way. Its possible by using : updateOrCreate()
.
For example for asked question you can use something like:
$matchThese = ['shopId'=>$theID,'metadataKey'=>2001];
ShopMeta::updateOrCreate($matchThese,['shopOwner'=>'New One']);
Above code will check the table represented by ShopMeta, which will be most likely shop_metas
unless not defined otherwise in model itself
and it will try to find entry with
column shopId = $theID
and
column metadateKey = 2001
and if it finds then it will update column shopOwner
of found row to New One
.
If it finds more than one matching rows then it will update the very first row that means which has lowest primary id
.
If not found at all then it will insert a new row with :
shopId = $theID
,metadateKey = 2001
and shopOwner = New One
Notice
Check your model for $fillable
and make sue that you have every column name defined there which you want to insert or update and rest columns have either default value or its id
column auto incremented one.
Otherwise it will throw error when executing above example:
Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field '...' doesn't have a default value (SQL: insert into `...` (`...`,.., `updated_at`, `created_at`) values (...,.., xxxx-xx-xx xx:xx:xx, xxxx-xx-xx xx:xx:xx))'
As there would be some field which will need value while inserting new row and it will not be possible as either its not defined in $fillable
or it doesnt have default value.
For more reference please see Laravel Documentation at : https://laravel.com/docs/5.3/eloquent
One example from there is:
// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
which pretty much clears everything.
Someone has asked if it is possible using Query Builder in Laravel. Here is reference for Query Builder from Laravel docs.
Query Builder works exactly the same as Eloquent so anything which is true for Eloquent is true for Query Builder as well. So for this specific case, just use the same function with your query builder like so:
$matchThese = array('shopId'=>$theID,'metadataKey'=>2001);
DB::table('shop_metas')::updateOrCreate($matchThese,['shopOwner'=>'New One']);
Of course, don't forget to add DB facade:
use Illuminate\Support\Facades\DB;
OR
use DB;
I hope it helps
Cygwin emulates entire POSIX environment, while MinGW is minimal tool set for compilation only (compiles native Win application.) So if you want to make your project cross-platform the choice between the two is obvious, MinGW.
Although you might consider using VS on Windows, GCC on Linux/Unices. Most open source projects do that (e.g. Firefox or Python).
As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).
On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.
You can check awesome material design components for AngularJS:
https://material.angularjs.org
I just fixed this problem by adding the following code in header:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
It's safer to use *arguments.callee.caller
since arguments.caller
is deprecated...
The file name should have .properties extension and the base directory should be in classpath. Otherwise it can also be in a jar which is in classpath Relative to the directory in classpath the resource bundle can be specified with / or . separator. "." is preferred.
This is the correct way:
To execute code that will only be available to the index page, we could use this syntax:
$(document).on('pageinit', "#index", function() {
...
});
The answer given by Fabian Perez worked for me, with a little change
Edited html is here:
<div ng-repeat="file in files" ng-class="!$last ? 'other' : 'class-for-last'">
{{file.name}}
</div>
Many way to Json Parse but i have found most effective way to
@model List<string[]>
<script>
function DataParse() {
var model = '@Html.Raw(Json.Encode(Model))';
var data = JSON.parse(model);
for (i = 0; i < data.length; i++) {
......
}
</script>
I think if I understand correctly this is what you are doing.
ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
ImageView imageView = (ImageView) view;
assert(R.id.someImage == imageView.getId());
switch(getDrawableId(imageView)) {
case R.drawable.foo:
imageView.setDrawableResource(R.drawable.bar);
break;
case R.drawable.bar:
default:
imageView.setDrawableResource(R.drawable.foo);
break;
}
});
Right? So that function getDrawableId()
doesn't exist. You can't get a the id that a drawable was instantiated from because the id is just a reference to the location of data on the device on how to construct a drawable. Once the drawable is constructed it doesn't have a way to get back the resourceId that was used to create it. But you could make it work something like this using tags
ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
ImageView imageView = (ImageView) view;
assert(R.id.someImage == imageView.getId());
// See here
Integer integer = (Integer) imageView.getTag();
integer = integer == null ? 0 : integer;
switch(integer) {
case R.drawable.foo:
imageView.setDrawableResource(R.drawable.bar);
imageView.setTag(R.drawable.bar);
break;
case R.drawable.bar:
default:
imageView.setDrawableResource(R.drawable.foo);
imageView.setTag(R.drawable.foo);
break;
}
});
Time to go back in time for a lesson. While we don't think about these things much in our fancy managed languages today, they are built on the same foundation, so let's look at how memory is managed in C.
Before I dive in, a quick explanation of what the term "pointer" means. A pointer is simply a variable that "points" to a location in memory. It doesn't contain the actual value at this area of memory, it contains the memory address to it. Think of a block of memory as a mailbox. The pointer would be the address to that mailbox.
In C, an array is simply a pointer with an offset, the offset specifies how far in memory to look. This provides O(1) access time.
MyArray [5]
^ ^
Pointer Offset
All other data structures either build upon this, or do not use adjacent memory for storage, resulting in poor random access look up time (Though there are other benefits to not using sequential memory).
For example, let's say we have an array with 6 numbers (6,4,2,3,1,5) in it, in memory it would look like this:
=====================================
| 6 | 4 | 2 | 3 | 1 | 5 |
=====================================
In an array, we know that each element is next to each other in memory. A C array (Called MyArray
here) is simply a pointer to the first element:
=====================================
| 6 | 4 | 2 | 3 | 1 | 5 |
=====================================
^
MyArray
If we wanted to look up MyArray[4]
, internally it would be accessed like this:
0 1 2 3 4
=====================================
| 6 | 4 | 2 | 3 | 1 | 5 |
=====================================
^
MyArray + 4 ---------------/
(Pointer + Offset)
Because we can directly access any element in the array by adding the offset to the pointer, we can look up any element in the same amount of time, regardless of the size of the array. This means that getting MyArray[1000]
would take the same amount of time as getting MyArray[5]
.
An alternative data structure is a linked list. This is a linear list of pointers, each pointing to the next node
======== ======== ======== ======== ========
| Data | | Data | | Data | | Data | | Data |
| | -> | | -> | | -> | | -> | |
| P1 | | P2 | | P3 | | P4 | | P5 |
======== ======== ======== ======== ========
P(X) stands for Pointer to next node.
Note that I made each "node" into its own block. This is because they are not guaranteed to be (and most likely won't be) adjacent in memory.
If I want to access P3, I can't directly access it, because I don't know where it is in memory. All I know is where the root (P1) is, so instead I have to start at P1, and follow each pointer to the desired node.
This is a O(N) look up time (The look up cost increases as each element is added). It is much more expensive to get to P1000 compared to getting to P4.
Higher level data structures, such as hashtables, stacks and queues, all may use an array (or multiple arrays) internally, while Linked Lists and Binary Trees usually use nodes and pointers.
You might wonder why anyone would use a data structure that requires linear traversal to look up a value instead of just using an array, but they have their uses.
Take our array again. This time, I want to find the array element that holds the value '5'.
=====================================
| 6 | 4 | 2 | 3 | 1 | 5 |
=====================================
^ ^ ^ ^ ^ FOUND!
In this situation, I don't know what offset to add to the pointer to find it, so I have to start at 0, and work my way up until I find it. This means I have to perform 6 checks.
Because of this, searching for a value in an array is considered O(N). The cost of searching increases as the array gets larger.
Remember up above where I said that sometimes using a non sequential data structure can have advantages? Searching for data is one of these advantages and one of the best examples is the Binary Tree.
A Binary Tree is a data structure similar to a linked list, however instead of linking to a single node, each node can link to two children nodes.
==========
| Root |
==========
/ \
========= =========
| Child | | Child |
========= =========
/ \
========= =========
| Child | | Child |
========= =========
Assume that each connector is really a Pointer
When data is inserted into a binary tree, it uses several rules to decide where to place the new node. The basic concept is that if the new value is greater than the parents, it inserts it to the left, if it is lower, it inserts it to the right.
This means that the values in a binary tree could look like this:
==========
| 100 |
==========
/ \
========= =========
| 200 | | 50 |
========= =========
/ \
========= =========
| 75 | | 25 |
========= =========
When searching a binary tree for the value of 75, we only need to visit 3 nodes ( O(log N) ) because of this structure:
Even though there are 5 nodes in our tree, we did not need to look at the remaining two, because we knew that they (and their children) could not possibly contain the value we were looking for. This gives us a search time that at worst case means we have to visit every node, but in the best case we only have to visit a small portion of the nodes.
That is where arrays get beat, they provide a linear O(N) search time, despite O(1) access time.
This is an incredibly high level overview on data structures in memory, skipping over a lot of details, but hopefully it illustrates an array's strength and weakness compared to other data structures.
On Java 14 you can do this
List<String> strings = Arrays.asList("one", "two", "three");
Forget about using success
and error
method.
Both methods have been deprecated in angular 1.4. Basically, the reason behind the deprecation is that they are not chainable-friendly, so to speak.
With the following example, I'll try to demonstrate what I mean about success
and error
being not chainable-friendly. Suppose we call an API that returns a user object with an address:
User object:
{name: 'Igor', address: 'San Francisco'}
Call to the API:
$http.get('/user')
.success(function (user) {
return user.address; <---
}) | // you might expect that 'obj' is equal to the
.then(function (obj) { ------ // address of the user, but it is NOT
console.log(obj); // -> {name: 'Igor', address: 'San Francisco'}
});
};
What happened?
Because success
and error
return the original promise, i.e. the one returned by $http.get
, the object passed to the callback of the then
is the whole user object, that is to say the same input to the preceding success
callback.
If we had chained two then
, this would have been less confusing:
$http.get('/user')
.then(function (user) {
return user.address;
})
.then(function (obj) {
console.log(obj); // -> 'San Francisco'
});
};
Create your Datafile like this:
# X Y
10000.0 0.01
100000.0 0.05
1000000.0 0.45
And plot it with
$ gnuplot -p -e "plot 'filename.dat'"
There is a good tutorial: http://www.gnuplotting.org/introduction/plotting-data/
I agree with this comment that using a table driven approach is often better.
In C# 1.0 this was not possible because it didn't have generics and anonymous delegates. New versions of C# have the scaffolding to make this work. Having a notation for object literals is also helps.
I have gone through the same problem when I was using
myApp.controller('mainController', ['$scope', function($scope,) {
//$http was not working in this
}]);
I have changed the above code to given below. Remember to include $http(2 times) as given below.
myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
//$http is working in this
}]);
and It has worked well.
Swift 3.0
With Swift 3, the name of NSJSONSerialization
and its methods have changed, according to the Swift API Design Guidelines.
let dic = ["2": "B", "1": "A", "3": "C"]
do {
let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}
Swift 2.x
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
// here "decoded" is of type `AnyObject`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch let error as NSError {
print(error)
}
Swift 1
var error: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
if error != nil {
println(error)
} else {
// here "jsonData" is the dictionary encoded in JSON data
}
}
if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
if error != nil {
println(error)
} else {
// here "decoded" is the dictionary decoded from JSON data
}
}
in Windows, you can use the runas command. For linux users, there are some alternatives for sudo in windows, you can check this out
http://helpdeskgeek.com/free-tools-review/5-windows-alternatives-linux-sudo-command/
hg rollback
is what you want.
In TortoiseHg, the hg rollback
is accomplished in the commit dialog. Open the commit dialog and select "Undo".
In my case convertor must return string value. I don't why, but it works.
*.xaml (common style file, which is included in another xaml files)
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
</Style>
*.cs
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Color color = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
return "#" + color.Name;
}
Use the .css()
jQuery manipulators, or better yet just call .show()
/.hide()
on the image once you've obtained a handle to it (e.g. $('#img' + id)
).
BTW, you should not write javascript handlers with the "javascript:" prefix.
I mostly use lstlistings in papers, but for coloured output (for slides) I use pygments instead.
The missing getParameterMap override ended up being a real problem for me. So this is what I ended up with:
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/***
* Request wrapper enabling the update of a request-parameter.
*
* @author E.K. de Lang
*
*/
final class HttpServletRequestReplaceParameterWrapper
extends HttpServletRequestWrapper
{
private final Map<String, String[]> keyValues;
@SuppressWarnings("unchecked")
HttpServletRequestReplaceParameterWrapper(HttpServletRequest request, String key, String value)
{
super(request);
keyValues = new HashMap<String, String[]>();
keyValues.putAll(request.getParameterMap());
// Can override the values in the request
keyValues.put(key, new String[] { value });
}
@SuppressWarnings("unchecked")
HttpServletRequestReplaceParameterWrapper(HttpServletRequest request, Map<String, String> additionalRequestParameters)
{
super(request);
keyValues = new HashMap<String, String[]>();
keyValues.putAll(request.getParameterMap());
for (Map.Entry<String, String> entry : additionalRequestParameters.entrySet()) {
keyValues.put(entry.getKey(), new String[] { entry.getValue() });
}
}
@Override
public String getParameter(String name)
{
if (keyValues.containsKey(name)) {
String[] strings = keyValues.get(name);
if (strings == null || strings.length == 0) {
return null;
}
else {
return strings[0];
}
}
else {
// Just in case the request has some tricks of it's own.
return super.getParameter(name);
}
}
@Override
public String[] getParameterValues(String name)
{
String[] value = this.keyValues.get(name);
if (value == null) {
// Just in case the request has some tricks of it's own.
return super.getParameterValues(name);
}
else {
return value;
}
}
@Override
public Map<String, String[]> getParameterMap()
{
return this.keyValues;
}
}
You will need to put a quote at the beginning of your first text and the end of your last.
Quick answer: change int testlib()
to int testlib(void)
to specify that the function takes no arguments.
A prototype is by definition a function declaration that specifies the type(s) of the function's argument(s).
A non-prototype function declaration like
int foo();
is an old-style declaration that does not specify the number or types of arguments. (Prior to the 1989 ANSI C standard, this was the only kind of function declaration available in the language.) You can call such a function with any arbitrary number of arguments, and the compiler isn't required to complain -- but if the call is inconsistent with the definition, your program has undefined behavior.
For a function that takes one or more arguments, you can specify the type of each argument in the declaration:
int bar(int x, double y);
Functions with no arguments are a special case. Logically, empty parentheses would have been a good way to specify that an argument but that syntax was already in use for old-style function declarations, so the ANSI C committee invented a new syntax using the void
keyword:
int foo(void); /* foo takes no arguments */
A function definition (which includes code for what the function actually does) also provides a declaration. In your case, you have something similar to:
int testlib()
{
/* code that implements testlib */
}
This provides a non-prototype declaration for testlib
. As a definition, this tells the compiler that testlib
has no parameters, but as a declaration, it only tells the compiler that testlib
takes some unspecified but fixed number and type(s) of arguments.
If you change ()
to (void)
the declaration becomes a prototype.
The advantage of a prototype is that if you accidentally call testlib
with one or more arguments, the compiler will diagnose the error.
(C++ has slightly different rules. C++ doesn't have old-style function declarations, and empty parentheses specifically mean that a function takes no arguments. C++ supports the (void)
syntax for consistency with C. But unless you specifically need your code to compile both as C and as C++, you should probably use the ()
in C++ and the (void)
syntax in C.)
This topic is well covered but I still would like to propose another approach in a slightly different philosophy.
It is a bit more complex to set-up but it allow (in my opinion) a bit more flexibility. For example, one can play with the respective ratios of each subplots / colorbar:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
# Define number of rows and columns you want in your figure
nrow = 2
ncol = 3
# Make a new figure
fig = plt.figure(constrained_layout=True)
# Design your figure properties
widths = [3,4,5,1]
gs = GridSpec(nrow, ncol + 1, figure=fig, width_ratios=widths)
# Fill your figure with desired plots
axes = []
for i in range(nrow):
for j in range(ncol):
axes.append(fig.add_subplot(gs[i, j]))
im = axes[-1].pcolormesh(np.random.random((10,10)))
# Shared colorbar
axes.append(fig.add_subplot(gs[:, ncol]))
fig.colorbar(im, cax=axes[-1])
plt.show()
Quick solution without downloading anything is to use online editors that has "Magic Wand Tool".
This is my way of doing it. It may be useful to others :
private void updateType(){
// Log.i(TAG,"updateType");
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// running on main thread-------
try {
JSONObject res = new JSONObject(response);
res.getString("result");
System.out.println("Response:" + res.getString("result"));
}else{
CustomTast ct=new CustomTast(context);
ct.showCustomAlert("Network/Server Disconnected",R.drawable.disconnect);
}
} catch (Exception e) {
e.printStackTrace();
//Log.e("Response", "==> " + e.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
// running on main thread-------
VolleyLog.d(TAG, "Error: " + volleyError.getMessage());
}
}) {
protected Map<String, String> getParams() {
HashMap<String, String> hashMapParams = new HashMap<String, String>();
hashMapParams.put("key", "value");
hashMapParams.put("key", "value");
hashMapParams.put("key", "value"));
hashMapParams.put("key", "value");
System.out.println("Hashmap:" + hashMapParams);
return hashMapParams;
}
};
AppController.getInstance().addToRequestQueue(request);
}
To get a full-screen dialog with animation, write the following ...
Styles:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="actionModeBackground">?attr/colorPrimary</item>
<item name="windowActionModeOverlay">true</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.NoActionBar.FullScreenDialog">
<item name="android:windowAnimationStyle">@style/Animation.WindowSlideUpDown</item>
</style>
<style name="Animation.WindowSlideUpDown" parent="@android:style/Animation.Activity">
<item name="android:windowEnterAnimation">@anim/slide_up</item>
<item name="android:windowExitAnimation">@anim/slide_down</item>
</style>
res/anim/slide_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="@android:interpolator/accelerate_quad">
<translate
android:duration="@android:integer/config_shortAnimTime"
android:fromYDelta="100%"
android:toYDelta="0%"/>
</set>
res/anim/slide_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="@android:interpolator/accelerate_quad">
<translate
android:duration="@android:integer/config_shortAnimTime"
android:fromYDelta="0%"
android:toYDelta="100%"/>
</set>
Java code:
public class MyDialog extends DialogFragment {
@Override
public int getTheme() {
return R.style.AppTheme_NoActionBar_FullScreenDialog;
}
}
private void showDialog() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment previous = getSupportFragmentManager().findFragmentByTag(MyDialog.class.getName());
if (previous != null) {
fragmentTransaction.remove(previous);
}
fragmentTransaction.addToBackStack(null);
MyDialog dialog = new MyDialog();
dialog.show(fragmentTransaction, MyDialog.class.getName());
}
Also note that the Hangouts application will currently block my BroadcastReceiver from receiving SMS messages. I had to disable SMS functionality in the Hangouts application (Settings->SMS->Turn on SMS), before my SMS BroadcastReceived started getting fired.
Edit: It appears as though some applications will abortBroadcast() on the intent which will prevent other applications from receiving the intent. The solution is to increase the android:priority
attribute in the intent-filter
tag:
<receiver android:name="com.company.application.SMSBroadcastReceiver" >
<intent-filter android:priority="500">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
See more details here: Enabling SMS support in Hangouts 2.0 breaks the BroadcastReceiver of SMS_RECEIVED in my app
Most of the answers here are obsolete, there is no more jQuery.browser
, and why would anyone even use jQuery or would sniff the User Agent
is beyond me.
Instead of detecting a browser, you should rather detect a feature
(whether it's supported or not).
The following is false
in Mozilla Firefox, Microsoft Edge; it is true
in Google Chrome.
"webkitLineBreak" in document.documentElement.style
Note this is not future-proof. A browser could implement the -webkit-line-break
property at any time in the future, thus resulting in false detection.
Then you can just look at the document object in Chrome and pick anything with webkit
prefix and check for that to be missing in other browsers.
I wrote all about tabs in vim, which gives a few interesting things you didn't ask about. To automatically indent braces, use:
:set cindent
To indent two spaces (instead of one tab of eight spaces, the vim default):
:set shiftwidth=2
To keep vim from converting eight spaces into tabs:
:set expandtab
If you ever want to change the indentation of a block of text, use < and >. I usually use this in conjunction with block-select mode (v, select a block of text, < or >).
(I'd try to talk you out of using two-space indentation, since I (and most other people) find it hard to read, but that's another discussion.)
I found this thread looking for information about dealing with parameters; this easy guide was so cool:
import argparse
parser = argparse.ArgumentParser(description='Script so useful.')
parser.add_argument("--opt1", type=int, default=1)
parser.add_argument("--opt2")
args = parser.parse_args()
opt1_value = args.opt1
opt2_value = args.opt2
run like:
python myScript.py --opt2 = 'hi'
Click on Wamp icon and open Apache/httpd.conf and search "#LoadModule rewrite_module modules/mod_rewrite.so". Remove # as below and save it
LoadModule rewrite_module modules/mod_rewrite.so
and restart all service.
Here you can find the direct download link for Curl.exe
I was looking for the download process of Curl and every where they said copy curl.exe file in System32 but they haven't provided the direct link but after digging little more I Got it. so here it is enjoy, find curl.exe easily in bin folder just
unzip it and then go to bin folder there you get exe file
In almost any language this should work instead:
a = true && 5 || 10
a = false && 5 || 10
LocalStorage:
Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. Available size is 5MB which considerably more space to work with than a typical 4KB cookie.
The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
It works on same-origin policy. So, data stored will only be available on the same origin.
Cookies:
We can set the expiration time for each cookie
The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.
sessionStorage:
Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted The data is available only inside the window/tab in which it was set.
The data is not persistent i.e. it will be lost once the window/tab is closed. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.
While this question has already been answered. Here is what exact steps you need to do when you are setting up for development. In general anything related to Java Development.
Setting Up Java
Make sure you are using latest jdk url
curl -L -O -H "Cookie: oraclelicense=accept-securebackup-cookie" -k "http://download.oracle.com/otn-pub/java/jdk/8u60-b27/jdk-8u60-linux-x64.tar.gz"
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/local/jdk1.7.0_67/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/local/jdk1.7.0_67/bin/javac" 1
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/local/jdk1.7.0_67/bin/javaws" 1
sudo update-alternatives --config java
sudo update-alternatives --config javac
sudo update-alternatives --config javaws
Setting up your system in this case ubuntu/mac
export ANDROID_HOME=/home/ashish/android-sdks
export ANDROID_SDK=/home/ashish/android-sdks
export JAVA_HOME=/usr/local/jdk1.8.0_45
export JDK_HOME=/usr/local/jdk1.8.0_45/
export JRE_HOME=/usr/local/jdk1.8.0_45/jre
export PATH=$PATH:$ANT_HOME/bin:$JAVA_HOME/bin:$JRE_HOME/bin:$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools
this contents needs to appear in .profile in ubuntu or .bash_profile in mac in home folder we can go there using cd ~
Let's, just as example:
public class Test { public Test() { System.out.println("NO ARGS"); } public Test(String s) { this(); System.out.println("1 ARG"); } public static void main(String args[]) { Test t = new Test("s"); } }
It will print
>>> NO ARGS >>> 1 ARG
The correct way to call the constructor is by:
this();
In Windows Command Line (cmd
), you can mount the current directory like so:
docker run --rm -it -v %cd%:/usr/src/project gcc:4.9
In PowerShell, you use ${PWD}
, which gives you the current directory:
docker run --rm -it -v ${PWD}:/usr/src/project gcc:4.9
On Linux:
docker run --rm -it -v $(pwd):/usr/src/project gcc:4.9
Cross Platform
The following options will work on both PowerShell and on Linux (at least Ubuntu):
docker run --rm -it -v ${PWD}:/usr/src/project gcc:4.9
docker run --rm -it -v $(pwd):/usr/src/project gcc:4.9
The code downloaded may require you to install dependencies first. Try commands(in app.js directory): npm install
then node app.js
. This should install dependencies and then start the app.
Not exactly that, but std::string
has many replace
overloaded functions.
Go through this link to see explanation of each, with examples as to how they're used.
Also, there are several versions of string::find
functions (listed below) which you can use in conjunction with string::replace
.
Also, note that there are several versions of replace
functions available from <algorithm>
which you can also use (instead of string::replace
):
Its very simple. Call one function inside another function with parameters.
function fun1()
{
var a=10;
var b=20;
fun2(a,b); //calling function fun2() and passing 2 parameters
}
function fun2(num1,num2)
{
var sum;
sum = num1+num2;
return sum;
}
fun1(); //trigger function fun1
Html::activeDropDownList($model, 'id', ArrayHelper::map(AttendanceLabel::find()->all(), 'id', 'label_name'), ['prompt'=>'Attendance Status'] );
The following commands rename the branch locally, delete the old branch on the remote location and push the new branch, setting the local branch to track the new remote:
git branch -m old_branch new_branch
git push origin :old_branch
git push --set-upstream origin new_branch
If you are still using .NET 2.0, then [IO.Path]::Combine
won't have the params string[]
overload which you need to join more than two parts, and you'll see the error Cannot find an overload for "Combine" and the argument count: "3".
Slightly less elegant, but a pure PowerShell solution is to manually aggregate path parts:
Join-Path C: (Join-Path "Program Files" "Microsoft Office")
or
Join-Path (Join-Path C: "Program Files") "Microsoft Office"
I don't think you can use "exists" on an integer in Perl, only on collections. Can you give an example of what you mean in Perl which matches your example in Java.
Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.
This indicates it only applies to hash or array elements!
The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).
# now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')
Also restarting your PC is not needed. Instead restart explorer.exe:
explorer
Windows Explorer has restarted and the TortoiseSVN icons reappear.
I want some code to run in the background continuously. I don't want to do it in a service. Is there any other way possible?
Most likely mechanizm that you are looking for is AsyncTask
. It directly designated for performing background process on background Thread. Also its main benefit is that offers a few methods which run on Main(UI) Thread and make possible to update your UI if you want to annouce user about some progress in task or update UI with data retrieved from background process.
If you don't know how to start here is nice tutorial:
Note: Also there is possibility to use IntentService
with ResultReceiver
that works as well.
you can try this indside findall for loop:
item_price = item.find('span', attrs={'class':'s-item__price'}).text
it extracts only text and assigs it to "item_pice"
I had this issue on resx files in my solution. I'm using Onedrive. However none of the above solutions fixed it.
The problem was the icon I used was in the MyWindow.resx files for the windows.
I removed that then grabbed the icon from the App Local Resources resource folder.
private ResourceManager rm = App_LocalResources.LocalResources.ResourceManager;
..
InitializeComponent();
this.Icon = (Icon)rm.GetObject("IconName");
This happened after an update to VS2019.
System like Ubuntu prefers to use auth_socket plugin. It will try to authenticate by comparing your username in DB and process which makes mysql request; it is described in here
The socket plugin checks whether the socket user name (the operating system user name) matches the MySQL user name specified by the client program to the server, and permits the connection only if the names match.
Instead you may want to back with the mysql_native_password, which will require user/password to authenticate.
About the method to achieve that, I recommend this instead.
It is mainly due to unregistered activity in manifest file as "NextActivity" Firstly register NextActivity in Manifest like
<activity android:name=".NextActivity">
then use the code in the where you want
Intent intent=new Intent(MainActivity.this,NextActivity.class);
startActivity(intent);
where you have to call the NextActivity..
Omit the parenthesis:
ALTER TABLE User
ADD CONSTRAINT userProperties
FOREIGN KEY(properties)
REFERENCES Properties(ID)
Just update of @bfncs answer
I think around Chrome 43 the behavior was changed a little. You still need to enable Preserve log to see, but now redirect shown under Other tab, when loaded document is shown under Doc.
This always confuse me, because I have a lot of networks requests and filter it by type XHR, Doc, JS etc. But in case of redirect the Doc tab is empty, so I have to guess.
You don't need jQuery. Just use JavaScript's Modulo operator.
Yes, it is visible in the same package. Anything outside that package will not be allowed to access it.
Why complicate things?
testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
The sequence being iterated in a foreach loop might not support indexing or know such a concept it just needs to implement a method called GetEnumerator that returns an object that as a minimum has the interface of IEnumerator though implmenting it is not required. If you know that what you iterate does support indexing and you need the index then I suggest to use a for
loop instead.
An example class that can be used in foreach
:
class Foo {
public iterator GetEnumerator() {
return new iterator();
}
public class iterator {
public Bar Current {
get{magic}
}
public bool MoveNext() {
incantation
}
}
}
On unixoid systems (and in php 7+ on Windows as well), you can use getrusage, like:
// Script start
$rustart = getrusage();
// Code ...
// Script end
function rutime($ru, $rus, $index) {
return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
- ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}
$ru = getrusage();
echo "This process used " . rutime($ru, $rustart, "utime") .
" ms for its computations\n";
echo "It spent " . rutime($ru, $rustart, "stime") .
" ms in system calls\n";
Note that you don't need to calculate a difference if you are spawning a php instance for every test.
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
Another option is to create a exclude list, this is particulary usefull when you have a long list of things to exclude.
vi /root/scripts/exclude_list.txt
Now add what you would like to exclude
Nopaging the limit is
keyword to remove is
Now use grep to remove lines from your file log file and view information not excluded.
grep -v -f /root/scripts/exclude_list.txt /var/log/admin.log
In my case I was using the prototype name as the object name. For e.g.
function proto1()
{}
var proto1 = new proto1();
It was a silly mistake but might be of help to someone like me ;)
char* result = strcpy((char*)malloc(str.length()+1), str.c_str());
let firstname = "paresh"
let lastname = "hirpara"
let itsme = "\(firstname) \(lastname)"