You can also add hash when page is loading:
location.hash = "noBack";
Then just handle location hash change to add another hash:
$(window).on('hashchange', function() {
location.hash = "noBack";
});
That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.
You can add "download" attribute inside your tag to download files.
<a href="/project/download" download> Download Document </a>
I really like the philosophy of the ezSQL database library, which wraps the native SQL methods in an easier-to-use interface.
Fetching a single value from the database is trivial:
$id = $db->get_var("SELECT id FROM games WHERE ...");
It also makes it easy to fetch a single row, column, or set of rows.
You need to specify the column in both expressions.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
I had the same problem. I had created a file named .env, but in reality the file ended up being .env.txt.
I created a new file, saved it in form of 'No Extension' and boom, the file was real .env and worked perfectly.
form.reset()
is a DOM element method (not one on the jQuery object), so you need:
$("#client.frm")[0].reset();
//faster version:
$("#client")[0].reset();
Or without jQuery:
document.getElementById("client").reset();
Convert hex string to int in Python
I may have it as
"0xffff"
or just"ffff"
.
To convert a string to an int, pass the string to int
along with the base you are converting from.
Both strings will suffice for conversion in this way:
>>> string_1 = "0xffff"
>>> string_2 = "ffff"
>>> int(string_1, 16)
65535
>>> int(string_2, 16)
65535
int
inferIf you pass 0 as the base, int
will infer the base from the prefix in the string.
>>> int(string_1, 0)
65535
Without the hexadecimal prefix, 0x
, int
does not have enough information with which to guess:
>>> int(string_2, 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: 'ffff'
If you're typing into source code or an interpreter, Python will make the conversion for you:
>>> integer = 0xffff
>>> integer
65535
This won't work with ffff
because Python will think you're trying to write a legitimate Python name instead:
>>> integer = ffff
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ffff' is not defined
Python numbers start with a numeric character, while Python names cannot start with a numeric character.
You can have a look at this library: https://github.com/mozilla/pdf.js it renders PDF document in a Web/HTML page
Also you can use Flash to embed the document into any HTML page like that:
<object data="your_file.pdf#view=Fit" type="application/pdf" width="100%" height="850">
<p>
It appears your Web browser is not configured to display PDF files. No worries, just <a href="your_file.pdf">click here to download the PDF file.</a>
</p>
</object>
I just had this problem, so I finally wrote a 1 line bash dirty solution by reading and parsing the list of aviable tools :
tools/android update sdk -u -t $(android list sdk | grep 'Android SDK Build-tools' | sed 's/ *\([0-9]\+\)\-.*/\1/')
I got the resources on C# (Desktop WPF W/ .NET Framework 4.8) using the code below
{DefaultNamespace}.Properties.Resources.{ResourceName}
In my case, the issue was not resolved by updating butterknife
from: "com.jakewharton:butterknife:8.4.0" to: "com.jakewharton:butterknife:8.8.1"
I've tried to @BindView inside Adapter class and no success. As soon I used .findViewById(R.id.message_time), compilation had been completed successfully.
The key is the margin: 0 auto; on the inner div. A proof-of-concept example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<body>
<div style="background-color: blue; width: 100%;">
<div style="background-color: yellow; width: 940px; margin: 0 auto;">
Test
</div>
</div>
</body>
</html>
System.out.print("\"Hello\"");
The double quote character has to be escaped with a backslash in a Java string literal. Other characters that need special treatment include:
"\r"
and "\n"
"\\\\"
"\'"
"\t"
and "\f"
The complete list of Java string and character literal escapes may be found in the section 3.10.6 of the JLS.
It is also worth noting that you can include arbitrary Unicode characters in your source code using Unicode escape sequences of the form "\uxxxx" where the "x"s are hexadecimal digits. However, these are different from ordinary string and character escapes in that you can use them anywhere in a Java program ... not just in string and character literals; see JLS sections 3.1, 3.2 and 3.3 for a details on the use of Unicode in Java source code.
See also:
The Oracle Java Tutorial: Numbers and Strings - Characters
This works for me:
Just checkout the master branch:
git checkout -b master
git add .
git push origin master
Or use --force
for forcing a change.
git push origin master --force
OpenCV has support for getting data from a webcam, and it comes with Python wrappers by default, you also need to install numpy
for the OpenCV Python extension (called cv2
) to work.
As of 2019, you can install both of these libraries with pip:
pip install numpy
pip install opencv-python
More information on using OpenCV with Python.
An example copied from Displaying webcam feed using opencv and python:
import cv2
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
if vc.isOpened(): # try to get the first frame
rval, frame = vc.read()
else:
rval = False
while rval:
cv2.imshow("preview", frame)
rval, frame = vc.read()
key = cv2.waitKey(20)
if key == 27: # exit on ESC
break
cv2.destroyWindow("preview")
function blinkTab() {
const browserTitle = document.title;
let timeoutId;
let message = 'My New Title';
const stopBlinking = () => {
document.title = browserTitle;
clearInterval(timeoutId);
};
const startBlinking = () => {
document.title = document.title === message ? browserTitle : message;
};
function registerEvents() {
window.addEventListener("focus", function(event) {
stopBlinking();
});
window.addEventListener("blur", function(event) {
const timeoutId = setInterval(startBlinking, 500);
});
};
registerEvents();
};
blinkTab();
If you want to keep it simple, cut out the middleman and just call wc
with all the filenames:
wc -l `find . -name "*.php"`
Or in the modern syntax:
wc -l $(find . -name "*.php")
This works as long as there are no spaces in any of the directory names or filenames. And as long as you don't have tens of thousands of files (modern shells support really long command lines). Your project has 74 files, so you've got plenty of room to grow.
Just write simple template:
template<typename T>
const char* getClassName(T) {
return typeid(T).name();
}
struct A {} a;
void main() {
std::cout << getClassName(a);
}
public class ProductList
{
public string product{get;set;}
public List<ProductList> objList{get;set;}
}
ProductList obj=new ProductList();
obj.objList=new List<ProductList>();
obj.objList.add(new ProductList{product="Football"});
now assign obj to session
Session["Product"]=obj;
for retrieval of session.
ProductList objLst = (ProductList)Session["Product"];
You could have a pseudo dynamic array where the size is set by the user at runtime, but then is fixed after that.
int size;
cin >> size;
int dynamicArray[size];
For those who are still trying, this link helped me out, too; it just puts it all together:
http://dotnetslackers.com/VB_NET/re-36138_How_To_Get_Selected_Date_from_MonthCalendar_control.aspx
private void MonthCalendar1_DateChanged(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
//Display the dates for selected range
Label1.Text = "Dates Selected from :" + (MonthCalendar1.SelectionRange.Start() + " to " + MonthCalendar1.SelectionRange.End);
//To display single selected of date
//MonthCalendar1.MaxSelectionCount = 1;
//To display single selected of date use MonthCalendar1.SelectionRange.Start/ MonthCalendarSelectionRange.End
Label2.Text = "Date Selected :" + MonthCalendar1.SelectionRange.Start;
}
A bit late but I used jQuery ajax method. But I did not want to send a request every second if I haven't got the response back from the last request, so I did this.
function request(){
if(response == true){
// This makes it unable to send a new request
// unless you get response from last request
response = false;
var req = $.ajax({
type:"post",
url:"request-handler.php",
data:{data:"Hello World"}
});
req.done(function(){
console.log("Request successful!");
// This makes it able to send new request on the next interval
response = true;
});
}
setTimeout(request(),1000);
}
request();
It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.
The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:
You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:
Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:
#toolbar=0&navpanes=0
So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.
string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);
You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
var mySelect = document.getElementById('mySelect'),
newOption = document.createElement('option');
newOption.value = 'bmw';
// Not all browsers support textContent (W3C-compliant)
// When available, textContent is faster (see http://stackoverflow.com/a/1359822/139010)
if (typeof newOption.textContent === 'undefined')
{
newOption.innerText = 'BMW';
}
else
{
newOption.textContent = 'BMW';
}
mySelect.appendChild(newOption);
This is a two-step process:
you need to create a login to SQL Server for that user, based on its Windows account
CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
you need to grant this login permission to access a database:
USE (your database)
CREATE USER (username) FOR LOGIN (your login name)
Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader
database role to read all tables.
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'
You can use triple-quoted strings. When they're not a docstring (the first thing in a class/function/module), they are ignored.
'''
This is a multiline
comment.
'''
(Make sure to indent the leading '''
appropriately to avoid an IndentationError
.)
Guido van Rossum (creator of Python) tweeted this as a "pro tip".
However, Python's style guide, PEP8, favors using consecutive single-line comments, like this:
# This is a multiline
# comment.
...and this is also what you'll find in many projects. Text editors usually have a shortcut to do this easily.
There is one more similarity measure which I once implemented in our system and was giving satisfactory results :-
Use Case
There is a user query which needs to be matched against a set of documents.
Algorithm
For every keyword extracted from user query :-
In essence, if first keyword appears 4 times in the document, the score will be calculated as :-
Total similarity score = 1 + 1/2 + 1/3 + 1/4 = 2.083
Similarly, we calculate it for other keywords in user query.
Finally, the total score will represent the extent of similarity between user query and given document.
As Tim Potter pointed out, setting proxy in dockerfile is horrible. When building the image, you add proxy for your corporate network but you may be deploying in cloud or a DMZ where there is no need for proxy or the proxy server is different.
Also, you cannot share your image with others outside your corporate n/w.
You can log the stack trace without an exception.
https://docs.python.org/3/library/logging.html#logging.Logger.debug
The second optional keyword argument is stack_info, which defaults to False. If true, stack information is added to the logging message, including the actual logging call. Note that this is not the same stack information as that displayed through specifying exc_info: The former is stack frames from the bottom of the stack up to the logging call in the current thread, whereas the latter is information about stack frames which have been unwound, following an exception, while searching for exception handlers.
Example:
>>> import logging
>>> logging.basicConfig(level=logging.DEBUG)
>>> logging.getLogger().info('This prints the stack', stack_info=True)
INFO:root:This prints the stack
Stack (most recent call last):
File "<stdin>", line 1, in <module>
>>>
You can also look at the following if you use WPF or reference System.Windows.Input
if (Keyboard.Modifiers == ModifierKeys.Shift)
The Keyboard namespace can also be used to check the pressed state of other keys with Keyboard.IsKeyDown(Key), or if you are subscribing to a KeyDownEvent or similar event, the event arguments carry a list of currently pressed keys.
(I presume that you've concluded that it's an iptables problem by dropping the firewall completely (iptables -P INPUT ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F) and confirmed that you can connect to the MySQL server from your Windows box?)
Some previous rule in the INPUT table is probably rejecting or dropping the packet. You can get around that by inserting the new rule at the top, although you might want to review your existing rules to see whether that's sensible:
iptables -I INPUT 1 -p tcp --dport 3306 -j ACCEPT
Note that iptables-save won't save the new rule persistently (i.e. across reboots) - you'll need to figure out something else for that. My usual route is to store the iptables-save output in a file (/etc/network/iptables.rules or similar) and then load then with a pre-up statement in /etc/network/interfaces).
Ok, I have another solution for one specific case: if you use WINDOWS 10, and you updated it recently (with Anniversary Update package) you need to follow the steps below:
Windows Event Viewer
- press Win+R and type: eventvwr
, then press ENTER.Windows Event Viewer
click on Windows Logs
-> Application
.IIS-W3SVC-WP
in middle window.The Module DLL >>path-to-DLL<< failed to load. The data is the error.
Control Panel
-> Program and Features
and depending on which dll cannot be load you need to repair another module:
rewrite.dll
- find IIS URL Rewrite Module 2 and click Change
->Repair
aspnetcore.dll
- find Microsoft .NET Core 1.0.0 - VS 2015 Tooling ... and click Change
->Repair
.This is a nice 5-part tutorial that covers a lot of useful material: http://mobile.tutsplus.com/tutorials/phonegap/phonegap-from-scratch/
(Anyone else noticing a trend forming here??? hehehee )
And this will definitely be of use to all developers:
http://blip.tv/mobiletuts/weinre-demonstration-5922038
=)
Todd
Edit I just finished a nice four part tutorial building an app to write, save, edit, & delete notes using jQuery mobile (only), it was very practical & useful, but it was also only for jQM. So, I looked to see what else they had on DZone.
I'm now going to start sorting through these search results. At a glance, it looks really promising. I remembered this post; so I thought I'd steer people to it. ?
This worked for me:
mysql -u root -p
mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
You might need sudo for the first step:
sudo mysql -u root -p
In general it is safer to work on copies than on original data frames, except when you know that you won't be needing the original anymore and want to proceed with the manipulated version. Normally, you would still have some use for the original data frame to compare with the manipulated version, etc. Therefore, most people work on copies and merge at the end.
Try bellow code with jquery :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){
$('#myForm').on('change', "input#MyFile", function (e) {
e.preventDefault();
$("#myForm").submit();
});
});
</script>
<body>
<div id="content">
<form id="myForm" action="action.php" method="POST" enctype="multipart/form-data">
<input type="file" id="MyFile" value="Upload" />
</form>
</div>
</body>
</html>
This is common issue, another way is to use DataTable object
DataTable dt = new DataTable();
dt.Columns.Add("column name");
dt.Rows.Add(new object[] { "Item 1" });
dt.Rows.Add(new object[] { "Item 2" });
dt.Rows.Add(new object[] { "Item 3" });
This problem is described in detail here: http://www.psworld.pl/Programming/BindingListOfString
this works too.
df = NULL
for (k in 1:10)
{
x = 1
y = 2
z = 3
df = rbind(df, data.frame(x,y,z))
}
output will look like this
df #enter
x y z #col names
1 2 3
I saw that two people put that question to their favorites so I will try to answer the solution which works for me: Instead of using find modules I'm writing configuration files for all libraries which are installed. Those files are extremly simple and can also be used to set non-standard variables. CMake will (at least on windows) search for those configuration files in
CMAKE_PREFIX_PATH/<<package_name>>-<<version>>/<<package_name>>-config.cmake
(which can be set through an environment variable). So for example the boost configuration is in the path
CMAKE_PREFIX_PATH/boost-1_50/boost-config.cmake
In that configuration you can set variables. My config file for boost looks like that:
set(boost_INCLUDE_DIRS ${boost_DIR}/include)
set(boost_LIBRARY_DIR ${boost_DIR}/lib)
foreach(component ${boost_FIND_COMPONENTS})
set(boost_LIBRARIES ${boost_LIBRARIES} debug ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-gd-1_50.lib)
set(boost_LIBRARIES ${boost_LIBRARIES} optimized ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-1_50.lib)
endforeach()
add_definitions( -D_WIN32_WINNT=0x0501 )
Pretty straight forward + it's possible to shrink the size of the config files even more when you write some helper functions. The only issue I have with this setup is that I havn't found a way to give config files a priority over find modules - so you need to remove the find modules.
Hope this this is helpful for other people.
Best way to copy file from local to vagrant, No need to write any code or any thing or any configuration changes. 1- First up the vagrant (vagrant up) 2- open cygwin 3- cygwin : go to your folder where is vagrantfile or from where you launch the vagrant 4- ssh vagrant 5- now it will work like a normal system.
I too faced a similar issue and my resolution was different. I went to the line of code mentioned and traversed to the character (For SpanishTest.java[31, 81], go to 31st line and 81th character including spaces). I observed an apostrophe in comment which was causing the issue. Though not a mistake, the maven compiler reports issue and in my case it was possible to remove maven's 'illegal' character.. lol.
simply go to D:/project/androidgc/.git/ this directory and delete index.lock this worked for me.
All the validation from model are skipped when we use validate: false
user = User.new(....)
user.save(validate: false)
I think the following is a good exhibit of Echo vs. Write-Host. Notice how test() actually returns an array of ints, not a single int as one could easily be led to believe.
function test {
Write-Host 123
echo 456 # AKA 'Write-Output'
return 789
}
$x = test
Write-Host "x of type '$($x.GetType().name)' = $x"
Write-Host "`$x[0] = $($x[0])"
Write-Host "`$x[1] = $($x[1])"
Terminal output of the above:
123
x of type 'Object[]' = 456 789
$x[0] = 456
$x[1] = 789
item = objects.Find(obj => obj.property==myValue);
Maybe
if (inventory.contains("bread") && !inventory.contains("water"))
Or
if (inventory.contains("bread")) {
if (!inventory.contains("water")) {
// do something here
}
}
Did you choose the customized version of Bootstrap? There is an issue that the font files included in the customized package are broken (see https://github.com/twbs/bootstrap/issues/9925). If you do not want to use the CDN, you have to download them manually and replace your own fonts with the downloaded ones:
https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot
After that try a strong reload (CTRL + F5), hope it helps.
Use empty()
:
std::string s;
if (s.empty())
// nothing in s
From Spring In Action
As you can see, this class is annotated with @Controller. On its own, @Controller doesn’t do much. Its primary purpose is to identify this class as a component for component scanning. Because HomeController is annotated with @Controller, Spring’s component scanning automatically discovers it and creates an instance of HomeController as a bean in the Spring application context.
In fact, a handful of other annotations (including @Component, @Service, and @Repository) serve a purpose similar to @Controller. You could have just as effectively annotated HomeController with any of those other annotations, and it would have still worked the same. The choice of @Controller is, however, more descriptive of this component’s role in the application.
You can use the static
from()
method from the LayoutInflater
class:
LayoutInflater li = LayoutInflater.from(context);
Try this in angular 8.0:
@ViewChild('result',{static: false}) resultElement: ElementRef;
This discussion is missing out on the important point: The question is not if the "non-key-columns" are better to include as index-columns or as included-columns.
The question is how expensive it is to use the include-mechanism to include columns that are not really needed in index? (typically not part of where-clauses, but often included in selects). So your dilemma is always:
Where: id1, id2 ... idN are columns often used in restrictions and col1, col2 ... colN are columns often selected, but typically not used in restrictions
(The option to include all of these columns as part of the index-key is just always silly (unless they are also used in restrictions) - cause it would always be more expensive to maintain since the index must be updated and sorted even when the "keys" have not changed).
So use option 1 or 2?
Answer: If your table is rarely updated - mostly inserted into/deleted from - then it is relatively inexpensive to use the include-mechanism to include some "hot columns" (that are often used in selects - but not often used on restrictions) since inserts/deletes require the index to be updated/sorted anyway and thus little extra overhead is associated with storing off a few extra columns while already updating the index. The overhead is the extra memory and CPU used to store redundant info on the index.
If the columns you consider to add as included-columns are often updated (without the index-key-columns being updated) - or - if it is so many of them that the index becomes close to a copy of your table - use option 1 I'd suggest! Also if adding certain include-column(s) turns out to make no performance-difference - you might want to skip the idea of adding them:) Verify that they are useful!
The average number of rows per same values in keys (id1, id2 ... idN) can be of some importance as well.
Notice that if a column - that is added as an included-column of index - is used in the restriction: As long as the index as such can be used (based on restriction against index-key-columns) - then SQL Server is matching the column-restriction against the index (leaf-node-values) instead of going the expensive way around the table itself.
Just put the full directory location in the File object.
File file = new File("z:\\results.txt");
As I know view can be something just like select command. You also can add parameters to this select for example in where statements like this:
WHERE (exam_id = @var)
If you are unable to install with either of these:
sudo apt-get install python-distutils
sudo apt-get install python3-distutils
Try this instead:
sudo apt-get install python-distutils-extra
Ref: https://groups.google.com/forum/#!topic/beagleboard/RDlTq8sMxro
Update my_table set my_field = CEILING((RAND(CAST(NEWID() AS varbinary)) * 10))
Number between 1 and 10.
Check it Out-->
For getting text
$("#selme").change(function(){
$(this[this.selectedIndex]).text();
});
For getting value
$("#selme").change(function(){
$(this[this.selectedIndex]).val();
});
Usually I create Fowler's Range implementation for such things.
public interface IRange<T>
{
T Start { get; }
T End { get; }
bool Includes(T value);
bool Includes(IRange<T> range);
}
public class DateRange : IRange<DateTime>
{
public DateRange(DateTime start, DateTime end)
{
Start = start;
End = end;
}
public DateTime Start { get; private set; }
public DateTime End { get; private set; }
public bool Includes(DateTime value)
{
return (Start <= value) && (value <= End);
}
public bool Includes(IRange<DateTime> range)
{
return (Start <= range.Start) && (range.End <= End);
}
}
Usage is pretty simple:
DateRange range = new DateRange(startDate, endDate);
range.Includes(date)
By Using map
var values = $("input[name='pname[]']")
.map(function(){return $(this).val();}).get();
The parameters of isset()
should be separated by a comma sign (,
) and not a dot sign (.
). Your current code concatenates the variables into a single parameter, instead of passing them as separate parameters.
So the original code evaluates the variables as a unified string
value:
isset($_POST['search_term'] . $_POST['postcode']) // Incorrect
While the correct form evaluates them separately as variables:
isset($_POST['search_term'], $_POST['postcode']) // Correct
string directoryPath = Path.GetDirectoryName(destinationFileName);
// If directory doesn't exist create one
if (!Directory.Exists(directoryPath))
{
DirectoryInfo di = Directory.CreateDirectory(directoryPath);
}
File.Copy(sourceFileName, destinationFileName);
You might want to remove the accents and diacritic signs first, then on each character position check if the "simplified" string is an ascii letter - if it is, the original position shall contain word characters, if not, it can be removed.
I came to this post while researching for a similar need, but i felt cloning solution that is so popular, to be too raw and takes my focus away from the functionality.
I found an article in react documents Higher Order Components
Here is my sample:
import React from 'react';
const withForm = (ViewComponent) => {
return (props) => {
const myParam = "Custom param";
return (
<>
<div style={{border:"2px solid black", margin:"10px"}}>
<div>this is poc form</div>
<div>
<ViewComponent myParam={myParam} {...props}></ViewComponent>
</div>
</div>
</>
)
}
}
export default withForm;
const pocQuickView = (props) => {
return (
<div style={{border:"1px solid grey"}}>
<div>this is poc quick view and it is meant to show when mouse hovers over a link</div>
</div>
)
}
export default withForm(pocQuickView);
For me i found a flexible solution in implementing the pattern of Higher Order Components.
Of course it depends on the functionality, but it is good if someone else is looking for a similar requirement, it is much better than being dependent on raw level react code like cloning.
Other pattern that i actively use is the container pattern. do read about it, there are many articles out there.
Thanks to Ali Tokmen answer. I managed to force delete the specific local dependency with the following command:
mvn dependency:purge-local-repository -DmanualInclude=com.skyfish:utils
With this, it removes utils
from my .m2/repository and it always re-download the utils
JAR dependency when I run mvn clean install
.
I use RStudio or Emacs and always use the editor shortcuts available to comment regions. If this is not a possibility then you could use Paul's answer but this only works if your code is syntactically correct.
Here is another dirty way I came up with, wrap it in scan()
and remove the result. It does store the comment in memory for a short while so it will probably not work with very large comments. Best still is to just put #
signs in front of every line (possibly with editor shortcuts).
foo <- scan(what="character")
These are comments
These are still comments
Can also be code:
x <- 1:10
One line must be blank
rm(foo)
GroupBy using in Hibernate
This is the resulting code
public Map getStateCounts(final Collection ids) {
HibernateSession hibernateSession = new HibernateSession();
Session session = hibernateSession.getSession();
Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
.add(Restrictions.in("id", ids));
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("state"));
projectionList.add(Projections.rowCount());
criteria.setProjection(projectionList);
List results = criteria.list();
Map stateMap = new HashMap();
for (Object[] obj : results) {
DownloadState downloadState = (DownloadState) obj[0];
stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
}
hibernateSession.closeSession();
return stateMap;
}
When executed in the browser, webpack needs to know where you'll host the generated bundle. Thus it is able to request additional chunks (when using code splitting) or referenced files loaded via the file-loader or url-loader respectively.
For example: If you configure your http server to host the generated bundle under /assets/
you should write: publicPath: "/assets/"
Let's see how to get and print day,month,year in python from current time:
import datetime
now = datetime.datetime.now()
year = '{:02d}'.format(now.year)
month = '{:02d}'.format(now.month)
day = '{:02d}'.format(now.day)
hour = '{:02d}'.format(now.hour)
minute = '{:02d}'.format(now.minute)
day_month_year = '{}-{}-{}'.format(year, month, day)
print('day_month_year: ' + day_month_year)
result:
day_month_year: 2019-03-26
Through discourse it's clear that the problem lies in using VS2010 to write the query, as it uses the canonical CONCAT()
function which is limited to 2 parameters. There's probably a way to change that, but I'm not aware of it.
An alternative:
SELECT '1'+'2'+'3'
This approach requires non-string values to be cast/converted to strings, as well as NULL
handling via ISNULL()
or COALESCE()
:
SELECT ISNULL(CAST(Col1 AS VARCHAR(50)),'')
+ COALESCE(CONVERT(VARCHAR(50),Col2),'')
get-aduser -Server "servername" -Identity %username% -Properties *
get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *
These work when you have the username. Also less to type than using the -filter
property.
EDIT: Formatting.
You can use with reduce
:
let randomNumbers = [4, 7, 1, 9, 6, 5, 6, 9]
let maxNumber = randomNumbers.reduce(randomNumbers[0]) { $0 > $1 ? $0 : $1 } //result is 9
It's pretty simple :
public function myAction()
{
$url = $this->generateUrl('blog_show', array('slug' => 'my-blog-post'));
}
Inside an action, $this->generateUrl is an alias that will use the router to get the wanted route, also you could do this that is the same :
$this->get('router')->generate('blog_show', array('slug' => 'my-blog-post'));
From managed code you have access to instances of the Thread
type for each managed thread. Thread
encapsulates the concept of an OS thread and as of the current CLR there's a one-to-one correspondance with managed threads and OS threads. However, this is an implementation detail, that may change in the future.
The ID displayed by Visual Studio is actually the OS thread ID. This is not the same as the managed thread ID as suggested by several replies.
The Thread
type does include a private IntPtr member field called DONT_USE_InternalThread
, which points to the underlying OS structure. However, as this is really an implementation detail it is not advisable to pursue this IMO. And the name sort of indicates that you shouldn't rely on this.
Please see my comment here: Make a link in the Android browser start up my app?
We strongly discourage people from using their own schemes, unless they are defining a new world-wide internet scheme.
Try this small example, to get a feel for ThreadLocal variable:
public class Book implements Runnable {
private static final ThreadLocal<List<String>> WORDS = ThreadLocal.withInitial(ArrayList::new);
private final String bookName; // It is also the thread's name
private final List<String> words;
public Book(String bookName, List<String> words) {
this.bookName = bookName;
this.words = Collections.unmodifiableList(words);
}
public void run() {
WORDS.get().addAll(words);
System.out.printf("Result %s: '%s'.%n", bookName, String.join(", ", WORDS.get()));
}
public static void main(String[] args) {
Thread t1 = new Thread(new Book("BookA", Arrays.asList("wordA1", "wordA2", "wordA3")));
Thread t2 = new Thread(new Book("BookB", Arrays.asList("wordB1", "wordB2")));
t1.start();
t2.start();
}
}
Console output, if thread BookA is done first:
Result BookA: 'wordA1, wordA2, wordA3'.
Result BookB: 'wordB1, wordB2'.
Console output, if thread BookB is done first:
Result BookB: 'wordB1, wordB2'.
Result BookA: 'wordA1, wordA2, wordA3'.
I've used that notation before as well, with no ill side effects and no misunderstandings. It makes sense -- a string is just an array of characters, after all.
we can do like this:
in application.yml:
spring:
profiles:
active: test //modify here to switch between environments
include: application-${spring.profiles.active}.yml
in application-test.yml:
server:
port: 5000
and in application-local.yml:
server:
address: 0.0.0.0
port: 8080
then spring boot will start our app as we wish to.
I have Alter this function to auto uncheck previous
var limit = 3;_x000D_
$('.compare_items').on('click', function(evt) {_x000D_
index = $(this).parent('td').parent('tr').index();_x000D_
if ($('.compare_items:checked').length >= limit) {_x000D_
$('.compare_items').eq(localStorage.getItem('last-checked-item')).removeAttr('checked');_x000D_
//this.checked = false;_x000D_
}_x000D_
localStorage.setItem('last-checked-item', index);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="checkbox" class="compare_items">1_x000D_
<input type="checkbox" class="compare_items">2_x000D_
<input type="checkbox" class="compare_items">3_x000D_
<input type="checkbox" class="compare_items">4_x000D_
<input type="checkbox" class="compare_items">5_x000D_
<input type="checkbox" class="compare_items">6_x000D_
<input type="checkbox" class="compare_items">7_x000D_
<input type="checkbox" class="compare_items">8_x000D_
<input type="checkbox" class="compare_items">9_x000D_
<input type="checkbox" class="compare_items">10
_x000D_
According to the api docs, doing:
dataFrame1.except(dataFrame2)
will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.
Expanding on betabandido's answer, you could write a function to inject the attributes as constants into the module:
def module_register_class_constants(klass, attr_prefix):
globals().update(
(name, getattr(klass, name)) for name in dir(klass) if name.startswith(attr_prefix)
)
class Animal(object):
SIZE_HUGE = "Huge"
SIZE_BIG = "Big"
module_register_class_constants(Animal, "SIZE_")
class Horse(Animal):
def printSize(self):
print SIZE_BIG
I am surprised that there's no concise answer yet, although such an expand/collapse animation is very easy to achieve with just 2 lines of code:
(recycler.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false // called once
together with
notifyItemChanged(position) // in adapter, whenever a child view in item's recycler gets hidden/shown
So for me, the explanations in the link below were really useful: https://medium.com/@nikola.jakshic/how-to-expand-collapse-items-in-recyclerview-49a648a403a6
Hi we can use default method "first" in jQuery
Here some examples:
When you want to add class for first div
$('.alldivs div').first().addClass('active');
When you want to change the remove the "onediv" class and add only to first child
$('.alldivs div').removeClass('onediv').first().addClass('onediv');
What Jeremiah said, plus the compiler issues the warning because the production:
*src ="anotherstring";
says: take the address of "anotherstring" -- "anotherstring" IS a char pointer -- and store that pointer indirect through src (*src = ... ) into the first char of the string "abcdef..." The warning might be baffling because there is nowhere in your code any mention of any integer: the warning seems nonsensical. But, out of sight behind the curtain, is the rule that "int" and "char" are synonymous in terms of storage: both occupy the same number of bits. The compiler doesn't differentiate when it issues the warning that you are storing into an integer. Which, BTW, is perfectly OK and legal but probably not exactly what you want in this code.
-- pete
import os
os.system('pip install requests')
I tried above for temporary solution instead of changing docker file. Hope these might be useful to some
By pooling the answer by Louis St-Amour and the NSUserDefaults+UnRegisterDefaults
category from this question/answer, you can use the following methods to start and stop user-agent spoofing at any time while your app is running:
#define kUserAgentKey @"UserAgent"
- (void)startSpoofingUserAgent:(NSString *)userAgent {
[[NSUserDefaults standardUserDefaults] registerDefaults:@{ kUserAgentKey : userAgent }];
}
- (void)stopSpoofingUserAgent {
[[NSUserDefaults standardUserDefaults] unregisterDefaultForKey:kUserAgentKey];
}
Just as string.gmatch
will find patterns in a string, this function will find the things between patterns:
function string:split(pat)
pat = pat or '%s+'
local st, g = 1, self:gmatch("()("..pat..")")
local function getter(segs, seps, sep, cap1, ...)
st = sep and seps + #sep
return self:sub(segs, (seps or 0) - 1), cap1 or sep, ...
end
return function() if st then return getter(st, g()) end end
end
By default it returns whatever is separated by whitespace.
wmic bios get serialnumber
if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)
I had to do exactly that.:):)
- How do I find Android SDK on my machine? Or prove to myself it's not there?
When you install Android studio, it allows you to choose if you want to download SDK or not
- If it's not there how do I install it?
you can get SDK from here http://developer.android.com/sdk/index.html
- How do I change PATH to include Android SDK?
Using String#gsub
with regular expression:
"((String1))".gsub(/^\(+|\)+$/, '')
# => "String1"
"(((((( parentheses )))".gsub(/^\(+|\)+$/, '')
# => " parentheses "
This will remove surrounding parentheses only.
"(((((( This (is) string )))".gsub(/^\(+|\)+$/, '')
# => " This (is) string "
A lot of dancing around the answer. You can add the UDF context help, but you have to export the Module and edit the contents in a text editor, then re-import it to VBA. Here's the example from Chip Pearson: Adding Code Attributes
string founded = FindStringTakeX("UID: 994zxfa6q", "UID:", 9);
string FindStringTakeX(string strValue,string findKey,int take,bool ignoreWhiteSpace = true)
{
int index = strValue.IndexOf(findKey) + findKey.Length;
if (index >= 0)
{
if (ignoreWhiteSpace)
{
while (strValue[index].ToString() == " ")
{
index++;
}
}
if(strValue.Length >= index + take)
{
string result = strValue.Substring(index, take);
return result;
}
}
return string.Empty;
}
You might be after something that the scrollTo plugin from Ariel Flesler does really well.
One line of code using jQuery which hides the 2nd column:
$('td:nth-child(2)').hide();
If your table has header(th), use this:
$('td:nth-child(2),th:nth-child(2)').hide();
Source: Hide a Table Column with a Single line of jQuery code
jsFiddle to test the code: http://jsfiddle.net/mgMem/1/
If you want to see a good use case, take a look at my blog post:
Hide a table column and colorize rows based on value with jQuery.
I've done something like this;
var certificationClass = _db.INDIVIDUALLICENSEs
.Join(_db.INDLICENSECLAsses,
IL => IL.LICENSE_CLASS,
ILC => ILC.NAME,
(IL, ILC) => new { INDIVIDUALLICENSE = IL, INDLICENSECLAsse = ILC })
.Where(o =>
o.INDIVIDUALLICENSE.GLOBALENTITYID == "ABC" &&
o.INDIVIDUALLICENSE.LICENSE_TYPE == "ABC")
.Select(t => new
{
value = t.PSP_INDLICENSECLAsse.ID,
name = t.PSP_INDIVIDUALLICENSE.LICENSE_CLASS,
})
.OrderBy(x => x.name);
The following code will load an image from a file image.png
and will display it as grayscale.
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
fname = 'image.png'
image = Image.open(fname).convert("L")
arr = np.asarray(image)
plt.imshow(arr, cmap='gray', vmin=0, vmax=255)
plt.show()
If you want to display the inverse grayscale, switch the cmap to cmap='gray_r'
.
If you've got git-bash
installed (which comes with Git, Github for Windows, or Visual Studio 2015), then that includes a Windows version of ssh-keygen
.
https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/
I know this thread is old, but still answering it so that no-one else should spend sleepless nights.
I was refactoring an old project, whose layout files all contained hardcoded
attributes such as android:maxLength = 500
. So I decided to register it in my
res/dimen
file as <dimen name="max_length">500</dimen>
.
Finished refactoring almost 30 layout files with my res-value. Guess what? the next time I ran my project it started throwing the same InflateException
.
As a solution, needed to redo my all changes and keep all-those values as same as before.
TLDR;
step 1: All running good.
step 2: To boost my maintenance I replaced android:maxLength = 500
with <dimen name="max_length">500</dimen>
and android:maxLength = @dimen/max_length
, that's where it all went wrong(crashing with InflateException
).
step 3: All running bad
step 4: Re-do all my work by again replacing android:maxLength = @dimen/max_length
with android:maxLength = 500
.Everything got fixed.
step 5: All running good.
Javascript doesn't have it, as you point out.
A quick search came up with:
function strcmp ( str1, str2 ) {
// http://kevin.vanzonneveld.net
// + original by: Waldo Malqui Silva
// + input by: Steve Hilder
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + revised by: gorthaur
// * example 1: strcmp( 'waldo', 'owald' );
// * returns 1: 1
// * example 2: strcmp( 'owald', 'waldo' );
// * returns 2: -1
return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}
from http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strcmp/
Of course, you could just add localeCompare if needed:
if (typeof(String.prototype.localeCompare) === 'undefined') {
String.prototype.localeCompare = function(str, locale, options) {
return ((this == str) ? 0 : ((this > str) ? 1 : -1));
};
}
And use str1.localeCompare(str2)
everywhere, without having to worry wether the local browser has shipped with it. The only problem is that you would have to add support for locales
and options
if you care about that.
Update image field to add full URL, ignoring null fields:
UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;
Try this one.
#/bin/bash
testpid="abc,def,ghij"
count=`echo $testpid | grep -o ',' | wc -l` # this is not a good way
count=`expr $count + 1`
while [ $count -gt 0 ] ; do
echo $testpid | cut -d ',' -f $i
count=`expr $count - 1 `
done
you can also use this command :
wget --mirror -pc --convert-links -P ./your-local-dir/ http://www.your-website.com
so that you get the exact mirror of the website you want to download
Select all code that you intend to indent, then hit Ctrl + ] in Sublime text to indent.
For macOS users, use command + ] to indent, and command + [ to un-indent.
I had the same issue. Seems like when starting the service the main thread shouldnt be the main worker thread. By simply creating a new thread and handing the main work to that thread solved my issue.
At the very core, the file extension you use makes no difference as to how perl
interprets those files.
However, putting modules in .pm
files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD
and you put it in a directory Example/Plot/FourD.pm
in a path in your @INC
, then use
and require
will do the right thing when given the package name as in use Example::Plot::FourD
.
The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with
1;
unless you're sure it'll return true otherwise. But it's better just to put the1;
, in case you add more statements.If
EXPR
is a bareword, therequire
assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.
All use
does is to figure out the filename from the package name provided, require
it in a BEGIN
block and invoke import
on the package. There is nothing preventing you from not using use
but taking those steps manually.
For example, below I put the Example::Plot::FourD
package in a file called t.pl
, loaded it in a script in file s.pl
.
C:\Temp> cat t.pl
package Example::Plot::FourD;
use strict; use warnings;
sub new { bless {} => shift }
sub something { print "something\n" }
"Example::Plot::FourD"
C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;
BEGIN {
require 't.pl';
}
my $p = Example::Plot::FourD->new;
$p->something;
C:\Temp> s
something
This example shows that module files do not have to end in 1
, any true value will do.
A more simple solution is as follows. Just check True/False with pandas .duplicated()
method and then take sum. Please also see pandas.Series.duplicated — pandas 0.24.1 documentation
import pandas as pd
def has_duplicated(l):
return pd.Series(l).duplicated().sum() > 0
print(has_duplicated(['one', 'two', 'one']))
# True
print(has_duplicated(['one', 'two', 'three']))
# False
this step works on me : 1. Remove your project on eclipse 2. Re import project 3. Delete target folder on your project 4. mvn or mvnw install
in the DBAdaper i.e Data Base helper class declare the table like this
private static final String USERDETAILS=
"create table userdetails(usersno integer primary key autoincrement,userid text not null ,username text not null,password text not null,photo BLOB,visibility text not null);";
insert the values like this,
first convert the images as byte[]
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.common)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] photo = baos.toByteArray();
db.insertUserDetails(value1,value2, value3, photo,value2);
in DEAdaper class
public long insertUserDetails(String uname,String userid, String pass, byte[] photo,String visibility)
{
ContentValues initialValues = new ContentValues();
initialValues.put("username", uname);
initialValues.put("userid",userid);
initialValues.put("password", pass);
initialValues.put("photo",photo);
initialValues.put("visibility",visibility);
return db.insert("userdetails", null, initialValues);
}
retrieve the image as follows
Cursor cur=your query;
while(cur.moveToNext())
{
byte[] photo=cur.getBlob(index of blob cloumn);
}
convert the byte[] into image
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);
I think this content may solve your problem
unicode('foo,bar').translate(dict([[ord(char), u''] for char in u',']))
One method is to do it without JavaScript and this is something like this:
<textarea style="overflow: visible" />
UPDATE 17/03/2017
Original solution won't work anymore. The spinners are part of shadow dom. For now just to hide in chrome use:
input[type=number]::-webkit-inner-spin-button {_x000D_
-webkit-appearance: none;_x000D_
}
_x000D_
<input type="number" />
_x000D_
or to always show:
input[type=number]::-webkit-inner-spin-button {_x000D_
opacity: 1;_x000D_
}
_x000D_
<input type="number" />
_x000D_
You can try the following but keep in mind that works only for Chrome:
input[type=number]::-webkit-inner-spin-button { _x000D_
-webkit-appearance: none;_x000D_
cursor:pointer;_x000D_
display:block;_x000D_
width:8px;_x000D_
color: #333;_x000D_
text-align:center;_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button:before,_x000D_
input[type=number]::-webkit-inner-spin-button:after {_x000D_
content: "^";_x000D_
position:absolute;_x000D_
right: 0;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button:before {_x000D_
top:0px;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button:after {_x000D_
bottom:0px;_x000D_
-webkit-transform: rotate(180deg);_x000D_
}
_x000D_
<input type="number" />
_x000D_
No use of any pre defined function as well as efficient: --- >>
public static void Delete(int d , int[] array )
{
Scanner in = new Scanner (System.in);
int i , size = array.length;
System.out.println("ENTER THE VALUE TO DELETE? ");
d = in.nextInt();
for ( i=0;i< size;i++)
{
if (array[i] == d)
{
int[] arr3 =new int[size-1];
int[] arr4 = new int[i];
int[] arr5 = new int[size-i-1];
for (int a =0 ;a<i;a++)
{
arr4[a]=array[a];
arr3[a] = arr4[a];
}
for (int a =i ;a<size-1;a++)
{
arr5[a-i] = array[a+1];
arr3[a] = arr5[a-i];
}
System.out.println(Arrays.toString(arr3));
}
else System.out.println("************");
}
}
That's because itoa
isn't a standard function. Try snprintf
instead.
char str[LEN];
snprintf(str, LEN, "%d", 42);
i want to mention some important point to bare in mind while implementing class binding.
[ngClass] = "{
'badge-secondary': somevariable === value1,
'badge-danger': somevariable === value1,
'badge-warning': somevariable === value1,
'badge-warning': somevariable === value1,
'badge-success': somevariable === value1 }"
class here is not binding correctly because one condition is to be met, whereas you have two identical classes 'badge-warning' that may have two different condition. To correct this
[ngClass] = "{
'badge-secondary': somevariable === value1,
'badge-danger': somevariable === value1,
'badge-warning': somevariable === value1 || somevariable === value1,
'badge-success': somevariable === value1 }"
Or, as inspired by @MatheusAraujo:
df[nrow(df) + 1,] = list("v1","v2")
This would allow for mixed data types.
if you want to set value than you can do the same in some function on click or on some event fire.
also you can get value using ViewChild
using local variable like this
<input type='text' id='loginInput' #abc/>
and get value like this
this.abc.nativeElement.value
okay got it , you have to use ngAfterViewInit
method of angualr2 for the same like this
ngAfterViewInit(){
document.getElementById('loginInput').value = '123344565';
}
ngAfterViewInit
will not throw any error because it will render after template loading
I tried everything for hours but the following finally fixed it (I'm on OS X 10.9.4):
m - sets margin
p - sets padding
t - sets margin-top or padding-top
b - sets margin-bottom or padding-bottom
l - sets margin-left or padding-left
r - sets margin-right or padding-right
x - sets both padding-left and padding-right or margin-left and margin-right
y - sets both padding-top and padding-bottom or margin-top and margin-bottom
blank - sets a margin or padding on all 4 sides of the element
0 - sets margin or padding to 0
1 - sets margin or padding to .25rem (4px if font-size is 16px)
2 - sets margin or padding to .5rem (8px if font-size is 16px)
3 - sets margin or padding to 1rem (16px if font-size is 16px)
4 - sets margin or padding to 1.5rem (24px if font-size is 16px)
5 - sets margin or padding to 3rem (48px if font-size is 16px)
auto - sets margin to auto
I ran into the same problem and found that I have to request the permissions at run time, even if I have declared it in the manifest. Just as stated as Justin Fiedler's answer.
The official documentation about this are here: https://developer.android.com/training/permissions/requesting.html
My implementation is slightly different from Justin Fiedler's answer that it also implement v4 fragment's onRequestPermissionsResult method to handle the permissions request response.
public static final int REQUEST_EXTERNAL_PERMISSION_CODE = 666;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public static final String[] PERMISSIONS_EXTERNAL_STORAGE = {
READ_EXTERNAL_STORAGE,
WRITE_EXTERNAL_STORAGE
};
public boolean checkExternalStoragePermission(Activity activity) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
return true;
}
int readStoragePermissionState = ContextCompat.checkSelfPermission(activity, READ_EXTERNAL_STORAGE);
int writeStoragePermissionState = ContextCompat.checkSelfPermission(activity, WRITE_EXTERNAL_STORAGE);
boolean externalStoragePermissionGranted = readStoragePermissionState == PackageManager.PERMISSION_GRANTED &&
writeStoragePermissionState == PackageManager.PERMISSION_GRANTED;
if (!externalStoragePermissionGranted) {
requestPermissions(PERMISSIONS_EXTERNAL_STORAGE, REQUEST_EXTERNAL_PERMISSION_CODE);
}
return externalStoragePermissionGranted;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (requestCode == REQUEST_EXTERNAL_PERMISSION_CODE) {
if (checkExternalStoragePermission(getActivity())) {
// Continue with your action after permission request succeed
}
}
}
}
#include <string.h>
...
char otherString[6]; // note 6, not 5, there's one there for the null terminator
...
strncpy(otherString, someString, 5);
otherString[5] = '\0'; // place the null terminator
Open a new worksheet on the related instance (Alt-F10)
and run the following query
SELECT view_name, owner
FROM sys.all_views
ORDER BY owner, view_name
I had a similar problem, I tried to clear all the caches possible (tried almost all the solutions above) and the only thing that worked for me was to kill the expo app and to restart it.
I assume you're looking for "1.4 MB" instead of "1468006 bytes"?
I don't think there is a built-in way to do that in .NET. You'll need to just figure out which unit is appropriate, and format it.
Edit: Here's some sample code to do just that:
$('select#id').val($('#id option')[index].value)
Replace the id with particular select tag id and index with particular element you want to select.
i.e.
<select class="input-field" multiple="multiple" id="ddlState" name="ddlState">
<option value="AB">AB</option>
<option value="AK">AK</option>
<option value="AL">AL</option>
</select>
So here for first element selection I will use following code :
$('select#ddlState').val($('#ddlState option')[0].value)
Copied from the author's post:
Use the -t
option to git remote add
, e.g.:
git remote add -t remote-branch remote-name remote-url
You can use multiple -t branch
options to grab multiple branches.
USE IT
$info = random_bytes(16);
$info[6] = chr(ord($info[6]) & 0x0f | 0x40);
$info[8] = chr(ord($info[8]) & 0x3f | 0x80);
$result =vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($info), 4));
return $result;
static String toCamelCase(String s){
String[] parts = s.split(" ");
String camelCaseString = "";
for (String part : parts){
if(part!=null && part.trim().length()>0)
camelCaseString = camelCaseString + toProperCase(part);
else
camelCaseString=camelCaseString+part+" ";
}
return camelCaseString;
}
static String toProperCase(String s) {
String temp=s.trim();
String spaces="";
if(temp.length()!=s.length())
{
int startCharIndex=s.charAt(temp.indexOf(0));
spaces=s.substring(0,startCharIndex);
}
temp=temp.substring(0, 1).toUpperCase() +
spaces+temp.substring(1).toLowerCase()+" ";
return temp;
}
public static void main(String[] args) {
String string="HI tHiS is SomE Statement";
System.out.println(toCamelCase(string));
}
There are potential problems with using document.activeElement. Consider:
<div contentEditable="true">
<div>Some text</div>
<div>Some text</div>
<div>Some text</div>
</div>
If the user focuses on an inner-div, then document.activeElement still references the outer div. You cannot use document.activeElement to determine which of the inner div's has focus.
The following function gets around this, and returns the focused node:
function active_node(){
return window.getSelection().anchorNode;
}
If you would rather get the focused element, use:
function active_element(){
var anchor = window.getSelection().anchorNode;
if(anchor.nodeType == 3){
return anchor.parentNode;
}else if(anchor.nodeType == 1){
return anchor;
}
}
See this JSFiddle
input[type="text"]_x000D_
{_x000D_
border: 0;_x000D_
border-bottom: 1px solid red;_x000D_
outline: 0;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
</form>
_x000D_
you can use
style="display:none"
Ex:
<asp:TextBox ID="txbProv" runat="server" style="display:none"></asp:TextBox>
void foo<TOne, TTwo>()
where TOne : BaseOne
where TTwo : BaseTwo
More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx
If you want data validation too
<!-- form -->
<form name="loginForm">
...
<input type="email" ng-keyup="$loginForm.$valid && $event.keyCode == 13 && signIn()" ng-model="email"... />
<input type="password" ng-keyup="$loginForm.$valid && $event.keyCode == 13 && signIn()" ng-model="password"... />
</form>
The important addition here is $loginForm.$valid
which will validate the form before executing function. You will have to add other attributes for validation which is beyond the scope of this question.
Good Luck.
Try This Code.
.card {_x000D_
_x000D_
width: 200px;_x000D_
_x000D_
height: 195px;_x000D_
_x000D_
position: relative;_x000D_
_x000D_
display: inline-block;_x000D_
_x000D_
}_x000D_
_x000D_
.card .img-top {_x000D_
_x000D_
display: none;_x000D_
_x000D_
position: absolute;_x000D_
_x000D_
top: 0;_x000D_
_x000D_
left: 0;_x000D_
_x000D_
z-index: 99;_x000D_
width:200px;_x000D_
}_x000D_
_x000D_
.card:hover .img-top {_x000D_
_x000D_
display: inline;_x000D_
_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
<title>Image Change on Hover with CSS</title>_x000D_
_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<div class="card">_x000D_
_x000D_
<img src="http://www.dhresource.com/200x200s/f2-albu-g5-M00-EC-97-rBVaJFkAobCAHD9XAADvz9DDocA266.jpg/diy-wall-stickers-home-decor-nature-colorful.jpg" alt="Card Back" style="width:200px">_x000D_
_x000D_
<img src="https://s-media-cache-ak0.pinimg.com/236x/31/17/98/3117987a0be0a7d8976869aabf54d2d7.jpg" class="img-top" alt="Card Front">_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy
It seems that ssh is not installed on your computer.
You can install openssh from here : http://openssh.en.softonic.com/download
Than you will have to geneate your ssh-key. There's a good tutorial about this here:
https://help.github.com/articles/generating-ssh-keys#platform-windows
To deploy, you just have to push your code over git. Something like this:
git push fort master
If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.
The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication
Taken from this link:
Build means compile and link only the source files that have changed since the last build, while Rebuild means compile and link all source files regardless of whether they changed or not. Build is the normal thing to do and is faster. Sometimes the versions of project target components can get out of sync and rebuild is necessary to make the build successful. In practice, you never need to Clean.
git-pull - Fetch from and integrate with another repository or a local branch
git pull [options] [<repository> [<refspec>...]]
You can refer official git doc https://git-scm.com/docs/git-pull
Ex :
git pull origin dev
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
Try this
$('document').ready(function(){
window.setTimeout('test()',time in milliseconds);
});
function test(){
$('#divid').hide();
}
On my system (IntelliJ Idea 2017.2.5), it was not sufficient to enable "Make Project Automatically". I also had to use the menu item "View, Tool Windows, Problems" to see the problems tool window at the bottom of the screen.
Whenever you want to redirect, send the headers:
header("Location: http://www.example.com/");
Remember you cant send data to the client before that, though.
To view file (txt for example):
return File("~/TextFileInRootDir.txt", MediaTypeNames.Text.Plain);
To download file (txt for example):
return File("~/TextFileInRootDir.txt", MediaTypeNames.Text.Plain, "TextFile.txt");
note: to download file we should pass fileDownloadName argument
I've got the same error on a fully updated Windows Vista Family 64bit with a .NET application that I've compiled to 32 bit only - the program is installed in the programx86 folder on 64 bit machines. It fails with this error message even with 2007 access database provider installed, with/wiothout the SP2 of the same installed, IIS installed and app pool set for 32bit app support... yes I've tried every solution everywhere and still no success.
I switched my app to ACE OLE DB.12.0 because JET4.0 was failing on 64bit machines - and it's no better :-/ The most promising thread I've found was this:
http://ellisweb.net/2010/01/connecting-to-excel-and-access-files-using-net-on-a-64-bit-server/
but when you try to install the 64 bit "2010 Office System Driver Beta: Data Connectivity Components" it tells you that you can't install the 64 bit version without uninstalling all 32bit office applications... and installing the 32 bit version of 2010 Office System Driver Beta: Data Connectivity Components doesn't solve the initial problem, even with "Microsoft.ACE.OLEDB.12.0" as provider instead of "Microsoft.ACE.OLEDB.14.0" which that page (and others) recommend.
My next attempt will be to follow this post:
The issue is due to the wrong flavor of OLEDB32.DLL and OLEDB32r.DLL being registered on the server. If the 64 bit versions are registered, they need to be unregistered, and then the 32 bit versions registered instead. To fix this, unregister the versions located in %Program Files%/Common Files/System/OLE DB. Then register the versions at the same path but in the %Program Files (x86)% directory.
Has anyone else had so much trouble with both JET4.0 and OLEDB ACE providers on 64 bit machines? Has anyone found a solution if none of the others work?
Seems like the python executable is not found in your PATH, which defines where it is looking for executables. See the official instructions for instructions on how to get the python executables in your PATH.
To install it, just run the command
npm install jquery
or
yarn add jquery
then you can import it in your file like
import $ from 'jquery';
Try :
adb shell
recovery --wipe_data
And here is the list of arguments :
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
The class Date/Timestamp
represents a specific instant in time, with millisecond precision, since January 1, 1970, 00:00:00 GMT. So this time difference (from epoch to current time) will be same in all computers across the world with irrespective of Timezone.
Date/Timestamp
doesn't know about the given time is on which timezone.
If we want the time based on timezone we should go for the Calendar or SimpleDateFormat classes in java.
If you try to print a Date/Timestamp object using toString()
, it will convert and print the time with the default timezone of your machine.
So we can say (Date/Timestamp).getTime() object will always have UTC (time in milliseconds)
To conclude Date.getTime()
will give UTC time, but toString()
is on locale specific timezone, not UTC.
The below code gives you a date (time in milliseconds) with specified timezones. The only problem here is you have to give date in string format.
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
dateFormatLocal.setTimeZone(timeZone);
java.util.Date parsedDate = dateFormatLocal.parse(date);
Use dateFormat.format
for taking input Date (which is always UTC), timezone and return date as String.
If you print the parsedDate
object, the time will be in default timezone.
But you can store the UTC time in DB like below.
Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Timestamp tsSchedStartTime = new Timestamp (parsedDate.getTime());
if (tsSchedStartTime != null) {
stmt.setTimestamp(11, tsSchedStartTime, calGMT );
} else {
stmt.setNull(11, java.sql.Types.DATE);
}
You can find/debug XPath/CSS locators in the IE as well as in different browsers with the tool called SWD Page Recorder
The only restrictions/limitations:
IEDriverServer.exe
- should be downloaded separately and placed near SwdPageRecorder.exe
This works fine with hostname, reverse IP (for internal networks) and IP.
function pingAddress($ip) {
$ping = exec("ping -n 2 $ip", $output, $status);
if (strpos($output[2], 'unreachable') !== FALSE) {
return '<span style="color:#f00;">OFFLINE</span>';
} else {
return '<span style="color:green;">ONLINE</span>';
}
}
echo pingAddress($ip);
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);
Yes we can have an abstract class without Abstract Methods as both are independent concepts. Declaring a class abstract means that it can not be instantiated on its own and can only be sub classed. Declaring a method abstract means that Method will be defined in the subclass.
I suggest much better solution. Task in my case: add http://google.com/ path before each record and import multiple fields.
CSV single field value (all images just have filenames, separate by |):
"123.jpg|345.jpg|567.jpg"
Tamper 1st plugin: find and replace by REGEXP: pattern: /([a-zA-Z0-9]*)./ replacement: http://google.com/$1
Tamper 2nd plugin: explode setting: explode by |
In this case you don't need any additinal fields mappings and can use 1 field in CSV
The problem for us was that duplicate submodule entries had been added into .gitmodules (probably from a merge). We searched for the path git complained about in .gitmodules and found the two identical sections. Deleting one of the sections solved the problem for us.
For what it is worth, git 1.7.1 gave the "no submodule mapping" error but git 2.13.0 didn't seem to care.
Use StringSubstitutor
from Apache Commons Text.
https://commons.apache.org/proper/commons-text/
It will do it for you (and its open source...)
Map<String, String> valuesMap = new HashMap<String, String>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
StringSubstitutor sub = new StringSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
def count_letters(word):
return len(word) - word.count(' ')
Alternatively, if you have multiple letters to ignore, you could filter the string:
def count_letters(word):
BAD_LETTERS = " "
return len([letter for letter in word if letter not in BAD_LETTERS])
What I do usually after new installation is to modify the main css file where all visual styles are stored. I use Miniconda but location is similar with others C:\Miniconda3\Lib\site-packages\notebook\static\style\style.min.css
With some screens these resolutions are different and more than 1. To be on the safe side I change all to 98% so if I disconnect from my external screens on my laptop I still have 98% screen width.
Then just replace 1140px with 98% of the screen width.
@media (min-width: 1200px) {
.container {
width: 1140px;
}
}
After editing
@media (min-width: 1200px) {
.container {
width: 98%;
}
}
Save and restart your notebook
Update
Recently had to wider Jupyter cells on an environment it is installed, which led me to come back here and remind myself.
If you need to do it in virtual env you installed jupyter on. You can find the css file in this subdir
env/lib/python3.6/site-packages/notebook/static/style/stye.min.css
I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
This fixed the problem, although changing the server name to localhost still gives the error.
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
But it connects successfully when the IP address is entered for the server name.
Another reason this can happen is if you send the wrong appId. This can happen in early development if you have a development app and a production app. If you hard-code the appId for dev and push to prod, this will show up.
if you want a simple dropdown &/or flyout menu with no transition effects just use CSS... you can force IE6 to support :hover on all element using an .htc file (css3hover?) with behavior (IE6 only property) defined in the conditionally attached CSS file.
You are experiencing two separate problems here:
hduser@ubuntu:/usr/local/hadoop$ hadoop fs -put /usr/local/input-data/ /input put: /usr/local/input-data (Permission denied)
Here, the user hduser
does not have access to the local directory /usr/local/input-data
. That is, your local permissions are too restrictive. You should change it.
hduser@ubuntu:/usr/local/hadoop$ sudo bin/hadoop fs -put /usr/local/input-data/ /inwe put: org.apache.hadoop.security.AccessControlException: Permission denied: user=root, access=WRITE, inode="":hduser:supergroup:rwxr-xr-x
Here, the user root
(since you are using sudo) does not have access to the HDFS directory /input
. As you can see: hduser:supergroup:rwxr-xr-x
says only hduser
has write access. Hadoop doesn't really respect root
as a special user.
To fix this, I suggest you change the permissions on the local data:
sudo chmod -R og+rx /usr/local/input-data/
Then, try the put
command again as hduser.
The difference is quite simple:
OLTP (Online Transaction Processing)
OLTP is a class of information systems that facilitate and manage transaction-oriented applications. OLTP has also been used to refer to processing in which the system responds immediately to user requests. Online transaction processing applications are high throughput and insert or update-intensive in database management. Some examples of OLTP systems include order entry, retail sales, and financial transaction systems.
OLAP (Online Analytical Processing)
OLAP is part of the broader category of business intelligence, which also encompasses relational database, report writing and data mining. Typical applications of OLAP include business reporting for sales, marketing, management reporting, business process management (BPM), budgeting and forecasting, financial reporting and similar areas.
See more details OLTP and OLAP
If you add jars in tomcat's lib folder you can see this error
These are the options currently documented in the tests: ctrl, shift, enter and escape. These are some valid examples of key bindings:
keydown.control.shift.enter
keydown.control.esc
You can track this here while no official docs exist, but they should be out soon.
Use this, works for me and solve problems with small screen.
<div class="row">
<!-- (fixed content) JUST VISIBLE IN LG SCREEN -->
<div class="col-lg-3 device-lg visible-lg">
<div class="affix">
fixed position
</div>
</div>
<div class="col-lg-9">
<!-- (fixed content) JUST VISIBLE IN NO LG SCREEN -->
<div class="device-sm visible-sm device-xs visible-xs device-md visible-md ">
<div>
NO fixed position
</div>
</div>
Normal data enter code here
</div>
</div>
Step 1
Search
→ Find
→ (goto Tab) Mark
Find what
: ^Session.*$ Bookmark line
Regular expression
(under Search Mode
)Mark All
(this will find the regex and highlights all the lines and bookmark them) Step 2
Search
→ Bookmark
→ Remove Bookmarked Lines
Based on my experience, solution which is fine(the best) when keys are not important:
$cart = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
I was having the same problem but wanted to minimize 3rd party dependencies (because this one-off script was to be executed by many users). My solution was to wrap a curl
call and make sure that the exit code was 0
. Worked like a charm.
This code just works perfectly for bootstrap 4. The problem in other codes were how the modal-backdrop is selected. It'll be better if you used the jQuery next select on the actual modal after the modal has been shown.
$(document).on('show.bs.modal', '.modal', function () {
var zIndex = 1040 + (10 * $('.modal').length);
var model = $(this);
model.css('z-index', zIndex);
model.attr('data-z-index', zIndex);
});
$(document).on('shown.bs.modal', '.modal', function () {
var model = $(this);
var zIndex = model.attr('data-z-index');
model.next('.modal-backdrop.show').css('z-index', zIndex - 1);
});
_x000D_
Use merge()
:
$request->merge([
'user_id' => $modified_user_id_here,
]);
Simple! No need to transfer the entire $request->all()
to another variable.
I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0
, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes
import matplotlib.pyplot as plt
plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()
I upgraded from 2010 to 2013 and after changing all the projects' Platform Toolset, I need to right-click on the Solution and choose Retarget... to make it work.
Include this line on top of your test class
@PrepareForTest({ First.class })
In your code:
while(fscanf(fp,"%s %c",item,&status) == 1)
why 1 and not 2? The scanf functions return the number of objects read.
I ran into this same problem and ended up using a JQuery solution to make it seem like a class can inherit other classes.
<script>
$(function(){
$(".composite").addClass("something else");
});
</script>
This will find all elements with the class "composite" and add the classes "something" and "else" to the elements. So something like <div class="composite">...</div>
will end up like so:
<div class="composite something else">...</div>
If you are doing a presentation, and you don't care about anything lining up, Verdana is a good choice.
If you are going to distribute your presentation, use a font that you know is on everyone's machine, since using something else is going to cause the machine to fall back to one of the common fonts (like Arial or Times) anyway.
If you do care about things lining up, and are not distributing the presentation, consider Consolas:
It is highly legible, reminiscent of Verdana, and is monospaced. The color choices are, of course, a matter of taste.
Adding to the answers above -
To use in a script, use the following :-
result=`ps aux | grep -i "myscript.sh" | grep -v "grep" | wc -l`
if [ $result -ge 1 ]
then
echo "script is running"
else
echo "script is not running"
fi
You need to render it as block level;
img {
display: block;
width: auto;
margin: auto;
}
The problem appears to be internal bubbling within the <video>
element ... so when you click on the "Play" button the code triggers and then the play button itself get triggered :(
I couldn't find a simple (reliable) way to stop the click bubbling through (logic tells me there should be a way, but... it escapes me right now)
Anyway, the solution I found to this was to put a transparent <div>
over the video sized to fit down to where the controls appear... so if you click on the div then your script controls play/pause but if the user clicks on the controls themselves then the <video>
element handles that for you.
The sample below was sized for my video so you may need to juggle sizes of the relative <div>
s but it should get you started
<div id="vOverlay" style="position:relative; width:600px; height:300px; z-index:2;"></div>
<video style="position:relative; top:-300px; z-index:1;width:600px;height:340px;" width="600" height="409" id=videoPlayer controls="controls">
<source src="video.mp4" type="video/mp4">
</video>
<script>
var v = document.getElementById('videoPlayer');
var vv = document.getElementById('vOverlay');
<!-- Auto play, Half volume -->
v.play()
v.volume = 0.5;
v.firstChild.nodeValue = "Play";
<!-- Play, Pause -->
vv.addEventListener('click',function(e){
if (!v.paused) {
console.log("pause playback");
v.pause();
v.firstChild.nodeValue = 'Pause';
} else {
console.log("start playback")
v.play();
v.firstChild.nodeValue = 'Play';
}
});
</script>
pause
command is what you looking for.
If you looking ONLY the case when enter is hit you can abuse the runas
command:
runas /user:# "" >nul 2>&1
the screen will be frozen until enter is hit.What I like more than set/p=
is that if you press other buttons than enter they will be not displayed.
verse = "If you can keep your head when all about you\n Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to hating,\n And yet don’t look too good, nor talk too wise:"
enter code here
print(verse)
#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))
Some browsers repeat the thead
element on each page, as they are supposed to. Others need some help: Add this to your CSS:
thead {display: table-header-group;}
tfoot {display: table-header-group;}
Opera 7.5 and IE 5 won't repeat headers no matter what you try.
(source)
The simplest answer, assuming you don't mind the vagaries and variations in format between different platforms, is the standard %p
notation.
The C99 standard (ISO/IEC 9899:1999) says in §7.19.6.1 ¶8:
p
The argument shall be a pointer tovoid
. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.
(In C11 — ISO/IEC 9899:2011 — the information is in §7.21.6.1 ¶8.)
On some platforms, that will include a leading 0x
and on others it won't, and the letters could be in lower-case or upper-case, and the C standard doesn't even define that it shall be hexadecimal output though I know of no implementation where it is not.
It is somewhat open to debate whether you should explicitly convert the pointers with a (void *)
cast. It is being explicit, which is usually good (so it is what I do), and the standard says 'the argument shall be a pointer to void
'. On most machines, you would get away with omitting an explicit cast. However, it would matter on a machine where the bit representation of a char *
address for a given memory location is different from the 'anything else pointer' address for the same memory location. This would be a word-addressed, instead of byte-addressed, machine. Such machines are not common (probably not available) these days, but the first machine I worked on after university was one such (ICL Perq).
If you aren't happy with the implementation-defined behaviour of %p
, then use C99 <inttypes.h>
and uintptr_t
instead:
printf("0x%" PRIXPTR "\n", (uintptr_t)your_pointer);
This allows you to fine-tune the representation to suit yourself. I chose to have the hex digits in upper-case so that the number is uniformly the same height and the characteristic dip at the start of 0xA1B2CDEF
appears thus, not like 0xa1b2cdef
which dips up and down along the number too. Your choice though, within very broad limits. The (uintptr_t)
cast is unambiguously recommended by GCC when it can read the format string at compile time. I think it is correct to request the cast, though I'm sure there are some who would ignore the warning and get away with it most of the time.
Kerrek asks in the comments:
I'm a bit confused about standard promotions and variadic arguments. Do all pointers get standard-promoted to void*? Otherwise, if
int*
were, say, two bytes, andvoid*
were 4 bytes, then it'd clearly be an error to read four bytes from the argument, non?
I was under the illusion that the C standard says that all object pointers must be the same size, so void *
and int *
cannot be different sizes. However, what I think is the relevant section of the C99 standard is not so emphatic (though I don't know of an implementation where what I suggested is true is actually false):
§6.2.5 Types
¶26 A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.39) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.
39) The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.
(C11 says exactly the same in the section §6.2.5, ¶28, and footnote 48.)
So, all pointers to structures must be the same size as each other, and must share the same alignment requirements, even though the structures the pointers point at may have different alignment requirements. Similarly for unions. Character pointers and void pointers must have the same size and alignment requirements. Pointers to variations on int
(meaning unsigned int
and signed int
) must have the same size and alignment requirements as each other; similarly for other types. But the C standard doesn't formally say that sizeof(int *) == sizeof(void *)
. Oh well, SO is good for making you inspect your assumptions.
The C standard definitively does not require function pointers to be the same size as object pointers. That was necessary not to break the different memory models on DOS-like systems. There you could have 16-bit data pointers but 32-bit function pointers, or vice versa. This is why the C standard does not mandate that function pointers can be converted to object pointers and vice versa.
Fortunately (for programmers targetting POSIX), POSIX steps into the breach and does mandate that function pointers and data pointers are the same size:
§2.12.3 Pointer Types
All function pointer types shall have the same representation as the type pointer to void. Conversion of a function pointer to
void *
shall not alter the representation. Avoid *
value resulting from such a conversion can be converted back to the original function pointer type, using an explicit cast, without loss of information.Note: The ISO C standard does not require this, but it is required for POSIX conformance.
So, it does seem that explicit casts to void *
are strongly advisable for maximum reliability in the code when passing a pointer to a variadic function such as printf()
. On POSIX systems, it is safe to cast a function pointer to a void pointer for printing. On other systems, it is not necessarily safe to do that, nor is it necessarily safe to pass pointers other than void *
without a cast.
JAXB is a reliable choice as it does xml to java classes mapping smoothely. But there are other frameworks available, here is one such:
Image Magick has been mentioned. There is a JNI front end project called JMagick. It's not a particularly stable project (and Image Magick itself has been known to change a lot and even break compatibility). That said, we've had good experience using JMagick and a compatible version of Image Magick in a production environment to perform scaling at a high throughput, low latency rate. Speed was substantially better then with an all Java graphics library that we previously tried.
you cannot set target attribute to div, becacuse div does not know how to handle http requests. instead of you set target attribute for link tag.
$(this).find("a").target = "_blank";
window.location= $(this).find("a").attr("href")
Had the same problem here. Usually Clean and Build solves much of the problem. It happened to be caused by a wrongly installed plugin.
This works for me, with Mac OS Sierra using Python,
options = webdriver.ChromeOptions()
options.add_argument("--kiosk")
driver = webdriver.Chrome(chrome_options=options)
You need to download this from Microsoft: http://www.microsoft.com/en-us/download/details.aspx?id=7435.
The tool is called "Microsoft URL Rewrite Module 2.0 for IIS 7" and is described as follows by Microsoft: "URL Rewrite Module 2.0 provides a rule-based rewriting mechanism for changing requested URL’s before they get processed by web server and for modifying response content before it gets served to HTTP clients"
Again, don't need the comparator for Arrays.binarySearch(Object[] a, Object key)
so long as the types of objects are comparable, but with lambda expressions this is now way easier.
Simply replace the comparator with the method reference: String::compareTo
E.g.:
Arrays.binarySearch(someStringArray, "The String to find.", String::compareTo);
You could also use
Arrays.binarySearch(someStringArray, "The String to find.", (a,b) -> a.compareTo(b));
but even before lambdas, there were always anonymous classes:
Arrays.binarySearch(
someStringArray,
"The String to find.",
new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
The C standard (actually C99, I'm not up to date) says:
Alphabetic escape sequences representing nongraphic characters in the execution character set are intended to produce actions on display devices as follows:
\b
(backspace) Moves the active position to the previous position on the current line. [...]
\t
(horizontal tab) Moves the active position to the next horizontal tabulation position on the current line. [...]
Both just move the active position, neither are supposed to write any character on or over another character. To overwrite with a space you could try: puts("foo\b \tbar");
but note that on some display devices - say a daisy wheel printer - the o
will show the transparent space.
Add
actionBar.setHomeButtonEnabled(true);
and then add the following
@Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
As suggested by naXa I've added a check on the itemId
, to have it work correctly in case there are multiple buttons on the action bar.
You need to change source to viewmodel object:
myBinding.Source = viewModelObject;
There is another way to make subclasses in python dynamically with a function type()
:
SubClass = type('SubClass', (BaseClass,), {'set_x': set_x}) # Methods can be set, including __init__()
You usually want to use this method when working with metaclasses. When you want to do some lower level automations, that alters way how python creates class. Most likely you will not ever need to do it in this way, but when you do, than you already will know what you are doing.
Usually you can find a program under a subdirectory "../bin". System programs are under /usr/bin or /bin. To check where files of mysql package are placed, on RHEL 6 type like this :
rpm -ql mysql (which is the main part of the package)
and the result is a list of "exe" files such as "mysqladmin" tool. About to know the version of the server, run the command:
mysqladmin -u "valid-user" version
You cannot always make a branch or pull an existing branch and push back to it, because you are not registered as a collaborator for that specific project.
Forking is nothing more than a clone on the GitHub server side:
You keep a fork in sync with the original project by:
The rebase allows you to make sure your changes are straightforward (no merge conflict to handle), making your pulling request that more easy when you want the maintainer of the original project to include your patches in his project.
The goal is really to allow collaboration even though direct participation is not always possible.
The fact that you clone on the GitHub side means you have now two "central" repository ("central" as "visible from several collaborators).
If you can add them directly as collaborator for one project, you don't need to manage another one with a fork.
The merge experience would be about the same, but with an extra level of indirection (push first on the fork, then ask for a pull, with the risk of evolutions on the original repo making your fast-forward merges not fast-forward anymore).
That means the correct workflow is to git pull --rebase upstream
(rebase your work on top of new commits from upstream), and then git push --force origin
, in order to rewrite the history in such a way your own commits are always on top of the commits from the original (upstream) repo.
See also:
You can try this Circle Progress library
NB: please always use same width and height for progress views
DonutProgress:
<com.github.lzyzsd.circleprogress.DonutProgress
android:id="@+id/donut_progress"
android:layout_marginLeft="50dp"
android:layout_width="100dp"
android:layout_height="100dp"
custom:circle_progress="20"/>
CircleProgress:
<com.github.lzyzsd.circleprogress.CircleProgress
android:id="@+id/circle_progress"
android:layout_marginLeft="50dp"
android:layout_width="100dp"
android:layout_height="100dp"
custom:circle_progress="20"/>
ArcProgress:
<com.github.lzyzsd.circleprogress.ArcProgress
android:id="@+id/arc_progress"
android:background="#214193"
android:layout_marginLeft="50dp"
android:layout_width="100dp"
android:layout_height="100dp"
custom:arc_progress="55"
custom:arc_bottom_text="MEMORY"/>
Catching the user id as path variable (recommended):
curl -i -X POST -H "Content-Type: multipart/form-data"
-F "[email protected]" http://mysuperserver/media/1234/upload/
Catching the user id as part of the form:
curl -i -X POST -H "Content-Type: multipart/form-data"
-F "[email protected];userid=1234" http://mysuperserver/media/upload/
or:
curl -i -X POST -H "Content-Type: multipart/form-data"
-F "[email protected]" -F "userid=1234" http://mysuperserver/media/upload/
DAYS(start_date,end_date):
For example:
DAYS(A1,TODAY())
There is a new DecisionTreeClassifier
method, decision_path
, in the 0.18.0 release. The developers provide an extensive (well-documented) walkthrough.
The first section of code in the walkthrough that prints the tree structure seems to be OK. However, I modified the code in the second section to interrogate one sample. My changes denoted with # <--
Edit The changes marked by # <--
in the code below have since been updated in walkthrough link after the errors were pointed out in pull requests #8653 and #10951. It's much easier to follow along now.
sample_id = 0
node_index = node_indicator.indices[node_indicator.indptr[sample_id]:
node_indicator.indptr[sample_id + 1]]
print('Rules used to predict sample %s: ' % sample_id)
for node_id in node_index:
if leave_id[sample_id] == node_id: # <-- changed != to ==
#continue # <-- comment out
print("leaf node {} reached, no decision here".format(leave_id[sample_id])) # <--
else: # < -- added else to iterate through decision nodes
if (X_test[sample_id, feature[node_id]] <= threshold[node_id]):
threshold_sign = "<="
else:
threshold_sign = ">"
print("decision id node %s : (X[%s, %s] (= %s) %s %s)"
% (node_id,
sample_id,
feature[node_id],
X_test[sample_id, feature[node_id]], # <-- changed i to sample_id
threshold_sign,
threshold[node_id]))
Rules used to predict sample 0:
decision id node 0 : (X[0, 3] (= 2.4) > 0.800000011921)
decision id node 2 : (X[0, 2] (= 5.1) > 4.94999980927)
leaf node 4 reached, no decision here
Change the sample_id
to see the decision paths for other samples. I haven't asked the developers about these changes, just seemed more intuitive when working through the example.
Can a modulus be negative?
%
can be negative as it is the remainder operator, the remainder after division, not after Euclidean_division. Since C99 the result may be 0, negative or positive.
// a % b
7 % 3 --> 1
7 % -3 --> 1
-7 % 3 --> -1
-7 % -3 --> -1
The modulo OP wanted is a classic Euclidean modulo, not %
.
I was expecting a positive result every time.
To perform a Euclidean modulo that is well defined whenever a/b
is defined, a,b
are of any sign and the result is never negative:
int modulo_Euclidean(int a, int b) {
int m = a % b;
if (m < 0) {
// m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
m = (b < 0) ? m - b : m + b;
}
return m;
}
modulo_Euclidean( 7, 3) --> 1
modulo_Euclidean( 7, -3) --> 1
modulo_Euclidean(-7, 3) --> 2
modulo_Euclidean(-7, -3) --> 2
This should do exactly what the author wanted:
<StackPanel Orientation="Horizontal">
<Separator Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />
</StackPanel>
if you want a horizontal separator, change the Orientation
of the StackPanel
to Vertical
.
Return an Array Of Objects
private static Object[] f ()
{
double x =1.0;
int y= 2 ;
return new Object[]{Double.valueOf(x),Integer.valueOf(y)};
}