You can use std::getline
:
#include <fstream>
#include <string>
int main()
{
std::ifstream file("Read.txt");
std::string str;
while (std::getline(file, str))
{
// Process str
}
}
Also note that it's better you just construct the file stream with the file names in it's constructor rather than explicitly opening (same goes for closing, just let the destructor do the work).
Further documentation about std::string::getline()
can be read at CPP Reference.
Probably the easiest way to read a whole text file is just to concatenate those retrieved lines.
std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
file_contents += str;
file_contents.push_back('\n');
}
As far as I am aware, simply opening the file in write mode without append mode will erase the contents of the file.
ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append
The first one will place the position bit at the beginning erasing all contents while the second version will place the position bit at the end-of-file bit and write from there.
This will do:
#include <fstream>
#include <iostream>
using std::fstream;
int main(int argc, char *argv[]) {
fstream file;
file.open("test.txt",std::ios::out);
file << fflush;
file.close();
}
Just follow closely the chain of events.
Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop.
Try this:
while (true) {
int x;
iFile >> x;
if( iFile.eof() ) break;
cerr << x << endl;
}
By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.
This seems to be answered - #include <fstream>
.
The message means :-
incomplete type
- the class has not been defined with a full class. The compiler has seen statements such as class ifstream;
which allow it to understand that a class exists, but does not know how much memory the class takes up.
The forward declaration allows the compiler to make more sense of :-
void BindInput( ifstream & inputChannel );
It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.
The has initializer
seems a bit extraneous, but is saying that the incomplete object is being created.
Like this:
long begin, end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size: " << (end-begin) << " bytes." << endl;
An angular-only solution that works alongside ng-click
is possible by using compile to wrap the ng-click
expression.
Directive:
.directive('confirmClick', function ($window) {
var i = 0;
return {
restrict: 'A',
priority: 1,
compile: function (tElem, tAttrs) {
var fn = '$$confirmClick' + i++,
_ngClick = tAttrs.ngClick;
tAttrs.ngClick = fn + '($event)';
return function (scope, elem, attrs) {
var confirmMsg = attrs.confirmClick || 'Are you sure?';
scope[fn] = function (event) {
if($window.confirm(confirmMsg)) {
scope.$eval(_ngClick, {$event: event});
}
};
};
}
};
});
HTML:
<a ng-click="doSomething()" confirm-click="Are you sure you wish to proceed?"></a>
There is a JQuery plug-in that accomplishes pretty much what you're trying to do: https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js.
After including JQuery and the jquery.redirect.min.js plug-in, you can simply do something like this:
$().redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});
Use the following code on newer JQuery versions instead:
$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});
Hope this helps!
I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join
helper=1
for i in df1.index:
df1.loc[i,'helper']=helper
helper=helper+1
for i in df2.index:
df2.loc[i,'helper']=helper
helper=helper+1
df1.merge(df2,on='helper',how='outer')
@Ned Batchelder and @newacct provided the right answer, but ...
Just in case if you have comma(,) decimal(.) in your string:
import re
re.sub("[^\d\.]", "", "$1,999,888.77")
'1999888.77'
On Ubuntu, you'll need to install unixodbc-dev:
sudo apt-get install unixodbc-dev
Install pip by using this command:
sudo apt-get install python-pip
once that is installed, you should be able to install pyodbc successfully:
pip install pyodbc
git clean -fd
didn't help, new files remained. What I did is totally deleting all the working tree and then
git reset --hard
See "How do I clear my local working directory in git?" for advice to add the -x
option to clean:
git clean -fdx
Note -x
flag will remove all files ignored by Git so be careful (see discussion in the answer I refer to).
Try this coding:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
browser does scrolling automatically to an element that gets focus, so what you can also do it to wrap the element that you need to be scrolled to into <a>...</a>
and then when you need scroll just set the focus on that a
Git 2.23 introduces git switch
and git restore
to split the responsibilities of git checkout
Creating a new branch from an existing branch as of git 2.23:
git switch -c my-new-branch
Switched to a new branch 'my-new-branch'
Take a look at this Github blog post explaining the changes in greater detail:
Git 2.23 brings a new pair of experimental commands to the suite of existing ones: git switch and git restore. These two are meant to eventually provide a better interface for the well-known git checkout. The new commands intend to each have a clear separation, neatly divvying up what the many responsibilities of git checkout
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
function changes() {
$('#link').val('new value');
}
</script>
<button onclick="changes()">a</button>
<input type='text' value='http://www.link.com' id='link'>
git log --all -- path/to/file
should work
In case you have key value pairs in your input array, I used:
.filter(
this.multi_items[0] != null && store.state.isSearchBox === false
? item =>
_.map(this.multi_items, "value").includes(item["wijknaam"])
: item => item["wijknaam"].includes("")
);
where the input array is multi_items as: [{"text": "bla1", "value": "green"}, {"text": etc. etc.}]
_.map is a lodash function.
Like pretty much everyone has stated already:
A period (.
) indicates a class, and a hash (#
) indicates an ID.
The fundamental difference between is that you can reuse a class on your page over and over, whereas an ID can be used once. That is, of course, if you are sticking to WC3 standards.
A page will still render if you have multiple elements with the same ID, but you will run into problems if/when you try to dynamically update said elements by calling them with their ID, since they are not unique.
It is also useful to note that ID properties will supersede class properties.
getElementById will return false if the element was not found in the DOM.
var el = document.getElementById("customx");
if (el !== null && el.value === "")
{
//The element was found and the value is empty.
}
Found this example... Will test...
import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
public static void main(String [] args)
{
int x=1;
DecimalFormat df = new DecimalFormat("00");
System.out.println(df.format(x));
}
}
Tested this and:
String.format("%05d",number);
Both work, for my purposes I think String.Format is better and more succinct.
Using the =~
operator:
$ string="hello-world"
$ prefix="hell"
$ suffix="ld"
$ [[ "$string" =~ ^$prefix(.*)$suffix$ ]] && echo "${BASH_REMATCH[1]}"
o-wor
Check "Virtualization" status under performance option in your task manager. If you already have enabled it in your BIOS and still status is "Disabled", then go to bios, disable it and save & exit. Restart or shut down again. Enable it in BIOS again and save & exit. This time you'll see the status changed to "Enabled", It took me 3 attempts (don't know why it took that much time, but finally it worked).
You can use var_dump() function to display structured information about variables/expressions including its type and value, or you can use print_r() to display information about a variable in a way that's readable by humans.
Example: Say we have got the following array and we want to display its contents.
$arr = array ('xyz', false, true, 99, array('50'));
Array
(
[0] => xyz
[1] =>
[2] => 1
[3] => 99
[4] => Array
(
[0] => 50
)
)
array(5) {
[0]=>
string(3) "xyz"
[1]=>
bool(false)
[2]=>
bool(true)
[3]=>
int(100)
[4]=>
array(1) {
[0]=>
string(2) "50"
}
}
The functions used in this answer can be found on the PHP.net website var_dump(), print_r()
For more details:
» https://stackhowto.com/how-to-display-php-variable-values-with-echo-print_r-and-var_dump/
What is the difference between
git pull
andgit fetch
?
To understand this, you first need to understand that your local git maintains not only your local repository, but it also maintains a local copy of the remote repository.
git fetch
brings your local copy of the remote repository up to date. For example, if your remote repository is GitHub - you may want to fetch any changes made in the remote repository to your local copy of it the remote repository. This will allow you to perform operations such as compare or merge.
git pull
on the other hand will bring down the changes in the remote repository to where you keep your own code. Typically, git pull
will do a git fetch
first to bring the local copy of the remote repository up to date, and then it will merge the changes into your own code repository and possibly your working copy.
Try:
alter table <your table> modify <column name> null;
Tip: Try to remove dependencies of jQuery in your projects as much as you can - VanillaJS.
document.firstElementChild
returns <html>
tag then the classList
attribute returns all classes added to it.
if(document.firstElementChild.classList.contains("your-class")){
// <html> has 'your-class'
} else {
// <html> doesn't have 'your-class'
}
Although this is mostly the same with the answer by @nfmcclure, I prefer using stringr
package as it provdies a set of functions whose names are most consistent and descriptive than those in base R (in fact I always google for "how to get the number of characters in R" as I can't remember the name nchar()
).
library(stringr)
str_sub(iris$Species, end=-4)
#or
str_sub(iris$Species, 1, str_length(iris$Species)-3)
This removes the last 3 characters from each value at Species
column.
This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!
On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:
<?php
session_start();
$timezone = $_SESSION['time'];
?>
This will read the session variable "time", which we are now about to create.
On the same page, in the <head>
section, first of all you need to include jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Also in the <head>
section, paste this jQuery:
<script type="text/javascript">
$(document).ready(function() {
if("<?php echo $timezone; ?>".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
$.ajax({
type: "GET",
url: "http://example.com/timezone.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
You may or may not have noticed, but you need to change the url to your actual domain.
One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)
<?php
session_start();
$_SESSION['time'] = $_GET['time'];
?>
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.
You can read more about this on my blog
Simply get a count of the record(s) you're looking for. If count > 0 then record(s) exist.
DECLARE rec_count NUMBER := 0; BEGIN select count(*) into rec_count from EMPLOYEETABLE WHERE employee_id = inEMPLOYEE_ID AND department_nbr = inDEPARTMENT_NBR; if rec_count > 0 then {UPDATE EMPLOYEETABLE} else {INSERT INTO EMPLOYEETABLE} end if; END;
I had to merge some of those good answers here! This works for me:
git remote set-url origin 'https://bitbucket.org/teamName/repo.git'
In the end, it will always prompt anyone who wants to pull from it
To install the Jupyterthemes package directly with conda, use:
conda install -c conda-forge jupyterthemes
Then, as others have pointed out, change the theme with jt -t <theme-name>
In this Java best practices book by Joshua Bloch, you can find explained why you should enforce the Singleton property with a private constructor or an Enum type. The chapter is quite long, so keeping it summarized:
Making a class a Singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type. Recommended approach is implement Singletons by simply make an enum type with one element:
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks.
While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.
Here is one that works for plain-text with some server side processing:
public string RotateHtmltext(string innerHtml)
{
const string TRANSFORMTEXT = "transform: rotate(90deg);";
const string EXTRASTYLECSS = "<style type='text/css'>.r90 {"
+ "-webkit-" + TRANSFORMTEXT
+ "-moz-" + TRANSFORMTEXT
+ "-o-" + TRANSFORMTEXT
+ "-ms-" + TRANSFORMTEXT
+ "" + TRANSFORMTEXT
+ "width:1em;line-height:1ex}</style>";
const string WRAPPERDIV = "<div style='display: table-cell; vertical-align: middle;'>";
var newinnerHtml = string.Join("</div>"+WRAPPERDIV, Regex.Split(innerHtml, @"<br */?>").Reverse());
newinnerHtml = Regex.Replace(newinnerHtml, @"((?:<[^>]*>)|(?:[^<]+))",
match => match.Groups[1].Value.StartsWith("<")
? match.Groups[1].Value
: string.Join("", match.Groups[1].Value.ToCharArray().Select(x=>"<div class='r90'>"+x+"</div>")),
RegexOptions.Singleline);
return EXTRASTYLECSS + WRAPPERDIV + newinnerHtml + "</div>";
}
which gives something like:
<style type="text/css">.r90 {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
width: 1em;
line-height: 1ex;
}</style>
<div style="display: table-cell; vertical-align: middle;">
<div class="r90">p</div>
<div class="r90">o</div>
<div class="r90">s</div>
</div><div style="display: table-cell; vertical-align: middle;">
<div class="r90">(</div>
<div class="r90">A</div>
<div class="r90">b</div>
<div class="r90">s</div>
<div class="r90">)</div>
</div>
os.path
works in a funny way. It looks like os
should be a package with a submodule path
, but in reality os
is a normal module that does magic with sys.modules
to inject os.path
. Here's what happens:
When Python starts up, it loads a bunch of modules into sys.modules
. They aren't bound to any names in your script, but you can access the already-created modules when you import them in some way.
sys.modules
is a dict in which modules are cached. When you import a module, if it already has been imported somewhere, it gets the instance stored in sys.modules
.os
is among the modules that are loaded when Python starts up. It assigns its path
attribute to an os-specific path module.
It injects sys.modules['os.path'] = path
so that you're able to do "import os.path
" as though it was a submodule.
I tend to think of os.path
as a module I want to use rather than a thing in the os
module, so even though it's not really a submodule of a package called os
, I import it sort of like it is one and I always do import os.path
. This is consistent with how os.path
is documented.
Incidentally, this sort of structure leads to a lot of Python programmers' early confusion about modules and packages and code organization, I think. This is really for two reasons
If you think of os
as a package and know that you can do import os
and have access to the submodule os.path
, you may be surprised later when you can't do import twisted
and automatically access twisted.spread
without importing it.
It is confusing that os.name
is a normal thing, a string, and os.path
is a module. I always structure my packages with empty __init__.py
files so that at the same level I always have one type of thing: a module/package or other stuff. Several big Python projects take this approach, which tends to make more structured code.
The gradle daemon also creates a many large text files of every single build log. They are stored here:
~/.gradle/daemon/X.X/daemon-XXXX.out.log
"X.X" is the gradle version in use, like "4.4", and "XXXX" are just random numbers, like "1234".
The total size can grow to several hundred MB in just a few months. There is no way to disable the logging, and the files are not automatically deleted and they do not really need to be retained.
But you can create a small gradle task to automatically delete them, and free up lots of disk space:
Add this to your app/build.gradle
:
android {
buildTypes {
...
}
// Delete large build log files from ~/.gradle/daemon/X.X/daemon-XXX.out.log
// Source: https://discuss.gradle.org/t/gradle-daemon-produces-a-lot-of-logs/9905
def gradle = project.getGradle()
new File("${gradle.getGradleUserHomeDir().getAbsolutePath()}/daemon/${gradle.getGradleVersion()}").listFiles().each {
if (it.getName().endsWith('.out.log')) {
// println("Deleting gradle log file: $it") // Optional debug output
it.delete()
}
}
}
To see which files are being deleted, you can see the debug output in Android Studio -> View -> Tool Windows -> Build. Then press "Toggle View" button on that window to show the text output.
Note that a Gradle Sync or any Gradle Build will trigger the file deletions.
A better way would be to automatically move the files to the Trash/Recycle Bin, or at least copy them to a Trash folder first. But I don't know how to do that.
- First to me Iterating
and Looping
are 2 different things.
Eg: Increment a variable till 5 is Looping.
int count = 0;
for (int i=0 ; i<5 ; i++){
count = count + 1;
}
Eg: Iterate over the Array to print out its values, is about Iteration
int[] arr = {5,10,15,20,25};
for (int i=0 ; i<arr.length ; i++){
System.out.println(arr[i]);
}
Now about all the Loops:
- Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...
For Loop
:
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("The sum is " + sum);
The Difference between While and Do-While is as Follows :
- While
is a Entry Control Loop
, Condition is checked in the Beginning before entering the loop.
- Do-While
is a Exit Control Loop
, Atleast once the block is always executed then the Condition is checked.
While Loop
:
int sum = 0;
int i = 0; // i is 0 Here
while (i<100) {
sum += i;
i++;
}
System.out.println("The sum is " + sum);
do-While
:
int sum = 0;
int i = 0; // i is 0 Here
do{
sum += i;
i++
}while(i < 100; );
System.out.println("The sum is " + sum);
From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.
ArrayList<String> arr = new ArrayList<String>();
arr.add("Vivek");
arr.add("Is");
arr.add("Good");
arr.add("Boy");
for (String str : arr){ // str represents the value in each index of arr
System.out.println(str);
}
Here is a small jQuery plugin that (among other things) can empty an dropdown list.
Just write:
$('your-select-element').selectUtils('setEmpty');
All above answers are very relevant, but if someone still unable to reset the userdefaults for deleted app, then you can reset the content settings of you simulator, and it will work.
Update 2018
Bootstrap 4
Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col
class on the fluid column.
.sidebar {
width: 180px;
min-height: 100vh;
}
<div class="row">
<div class="sidebar p-2">Fixed width</div>
<div class="col bg-dark text-white pt-2">
Content
</div>
</div>
http://www.codeply.com/go/7LzXiPxo6a
Bootstrap 3..
One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...
@media (min-width:768px) {
#sidebar {
min-width: 300px;
max-width: 300px;
}
#main {
width:calc(100% - 300px);
}
}
Working Bootstrap 3 Fixed-Fluid Demo
Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?
rm -rf *
Would remove everything (folders & files) in the current directory.
But be careful! Only execute this command if you are absolutely sure, that you are in the right directory.
I found the answer :)
Use JsonPath or XmlPath (in case you have XML) to get data from the response body.
In my case:
JsonPath jsonPath = new JsonPath(responseBody);
int user_id = jsonPath.getInt("user_id");
Did you check your Project Properties -> Project Facets
panel? (From that post)
A WTP project is composed of multiple units of functionality (known as facets).
The Java facet version needs to always match the java compiler compliance level.
The best way to change java level is to use the Project Facets properties panel as that will update both places at the same time.
The "
Project->Preferences->Project Facets
" stores its configuration in this file, "org.eclipse.wst.common.project.facet.core.xml
", under the ".settings
" directory.The content might look like this
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<runtime name="WebSphere Application Server v6.1"/>
<fixed facet="jst.java"/>
<fixed facet="jst.web"/>
<installed facet="jst.java" version="5.0"/>
<installed facet="jst.web" version="2.4"/>
<installed facet="jsf.ibm" version="7.0"/>
<installed facet="jsf.base" version="7.0"/>
<installed facet="web.jstl" version="1.1"/>
</faceted-project>
Check also your Java compliance level:
Use Range("A1").Text
instead of .Value
post comment edit:
Why?
Because the .Text
property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92
then <- Text
will return exactly what it in the cell including any formatting.
The .Value
and .Value2
properties return what's stored in the cell under the hood excluding formatting. Specially .Value2
for date types, it will return the decimal representation.
If you want to dig deeper into the meaning and performance, I just found this article
which seems like a good guide
another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
now,
paste this code in a module
Sub main()
Dim ws As Worksheet, i&, j&
Set ws = Sheets(1)
For i = 3 To 7
For j = 1 To 4
Debug.Print _
"row " & i & vbTab & vbTab & _
Cells(i, j).Text & vbTab & _
Cells(i, j).Value & vbTab & _
Cells(i, j).Value2
Next j
Next i
End Sub
and Analyse
the output! Its really easy and there isn't much more i can do to help :)
.TEXT .VALUE .VALUE2
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 4 1 1 1
row 4 1 1 1
row 4 01/01/1900 31/12/1899 1
row 4 1.00% 0.01 0.01
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 6 63 63 63
row 6 =7*9 =7*9 =7*9
row 6 03/03/1900 03/03/1900 63
row 6 6300.00% 63 63
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013 29/05/2013 29/05/2013
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013% 29/05/2013% 29/05/2013%
Simply declare it as below if you want to us the STL queue container.
std::queue<myclass*> my_queue;
Quite similar approve as already posted above. However it's easier to read.
/**
* Remove all empty spaces from array a string array
* @param arr array
* @return array without ""
*/
public static String[] removeAllEmpty(String[] arr) {
if (arr == null)
return arr;
String[] result = new String[arr.length];
int amountOfValidStrings = 0;
for (int i = 0; i < arr.length; i++) {
if (!arr[i].equals(""))
result[amountOfValidStrings++] = arr[i];
}
result = Arrays.copyOf(result, amountOfValidStrings);
return result;
}
If You are using source control. vim temp files are quite useless.
So You might want to configure vim not to create them.
Just edit Your ~/.vimrc and add these lines:
set nobackup
set noswapfile
If you just have included a layout file at the beginning of onCreate()
inside setContentView
and want to get this layout to add new elements programmatically try this:
ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);
then you can create a new Button
for example and just add it:
Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);
When you create a repository in bitbucket.org, it gives you instructions on how to set up your local directory. Chances are, you just forgot to run the code:
git remote add origin https://[email protected]/username/reponame.git
If your branch is local only and hasn't been pushed to the server, use
git rebase master
Otherwise, use
git merge master
A bit offtopic but might help someone. If you need to pass password and port I suggest using sshpass
package. Command line command would look like this:
sshpass -p "password" rsync -avzh -e 'ssh -p PORT312' [email protected]:/dir_on_host/
Assuming you want the whole regex to ignore case, you should look for the i
flag. Nearly all regex engines support it:
/G[a-b].*/i
string.match("G[a-b].*", "i")
Check the documentation for your language/platform/tool to find how the matching modes are specified.
If you want only part of the regex to be case insensitive (as my original answer presumed), then you have two options:
Use the (?i)
and [optionally] (?-i)
mode modifiers:
(?i)G[a-b](?-i).*
Put all the variations (i.e. lowercase and uppercase) in the regex - useful if mode modifiers are not supported:
[gG][a-bA-B].*
One last note: if you're dealing with Unicode characters besides ASCII, check whether or not your regex engine properly supports them.
Here are the steps:
To verify if Path is set successfully open terminal again and type adb if adb version and other details are displayed that means path is set properly.
Add this code on values anim
<scale
android:duration="@android:integer/config_longAnimTime"
android:fromXScale="0.2"
android:fromYScale="0.2"
android:toXScale="1.0"
android:toYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"/>
<alpha
android:fromAlpha="0.1"
android:toAlpha="1.0"
android:duration="@android:integer/config_longAnimTime"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"/>
call on styles.xml
<style name="DialogScale">
<item name="android:windowEnterAnimation">@anim/scale_in</item>
<item name="android:windowExitAnimation">@anim/scale_out</item>
</style>
On java code: set Onclick
public void onClick(View v) {
fab_onclick(R.style.DialogScale, "Scale" ,(Activity) context,getWindow().getDecorView().getRootView());
// Dialogs.fab_onclick(R.style.DialogScale, "Scale");
}
setup on method:
alertDialog.getWindow().getAttributes().windowAnimations = type;
It seems strange that you would write arrays without commas (is that a MATLAB syntax?)
Have you tried going through NumPy's documentation on multi-dimensional arrays?
It seems NumPy has a "Python-like" append method to add items to a NumPy n-dimensional array:
>>> p = np.array([[1,2],[3,4]])
>>> p = np.append(p, [[5,6]], 0)
>>> p = np.append(p, [[7],[8],[9]],1)
>>> p
array([[1, 2, 7], [3, 4, 8], [5, 6, 9]])
It has also been answered already...
From the documentation for MATLAB users:
You could use a matrix constructor which takes a string in the form of a matrix MATLAB literal:
mat("1 2 3; 4 5 6")
or
matrix("[1 2 3; 4 5 6]")
Please give it a try and tell me how it goes.
You can test like this:
create table test1(
id number,
name varchar2(20)
);
insert into test1 values (1,'abc');
insert into test1 values (1,'abc');
select * from test1;
select count(*) from test1;
select count(1) from test1;
select count(ALL 1) from test1;
select count(DISTINCT 1) from test1;
Wrap code in
window.onload = function(){
// your code
};
As others have mentioned, myCoolDiv
is a child of markerDiv
not playerContainer
. If you want to remove myCoolDiv
but keep markerDiv
for some reason you can do the following
myCoolDiv.parentNode.removeChild(myCoolDiv);
The solution is the /Y
switch:
xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y
Yes, Hibernate can be configured by way of the hibernate.hbm2ddl.auto
property in the hibernate.cfg.xml
file to automatically create tables in your DB in order to store your entities in them if the table doesn't already exist.
This can be handy during development where a new, in-memory,
DB can be used and created a new on every run of the application or during testing.
Try the following:
if ((select VisitCount from PageImage where PID=@pid and PageNumber=5) is NULL)
begin
update PageImage
set VisitCount=1
where PID=@pid and PageNumber=@pageno
end
else
begin
update PageImage
set VisitCount=VisitCount+1
where PID=@pid and PageNumber=@pageno
end
Typically you would always put the hyphen first in the []
match section. EG, to match any alphanumeric character including hyphens (written the long way), you would use [-a-zA-Z0-9]
For generate Model , controller with resources and migration best command is:
php artisan make:model ModelName -m -cr
i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te
Either define a delimiter that will not be a potential value or learn to use XML.
If you still insist on using properties use one of the methods that will return a list of all keys. Your key appears to have three parts a group identifier (foo, bar) an index (1, 2) and then an element name (filename, expire). Get all the keys break them into their component parts. Create a List for each type of identifier, when processing the list use the identifier to determine which List to add to. Create you paired elements as you said and simply add to the list! If the index order is important either add that as a field to your paired elements or sort the keys before processing.
based on accepted answer
$output = some_function();
echo $output;
if it results array then use json_encode it will result json array which is supportable by javascript
$output = some_function();
echo json_encode($output);
If someone wants to stop execution after you echo some result use exit method of php. It will work like return keyword
$output = some_function();
echo $output;
exit;
This works for spanish operation system.
Script accepts two parameters:
script.bat listofurls.txt output.txt
@echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=%2
>nul copy nul %OUTPUT_FILE%
for /f %%i in (%1) do (
set SERVER_ADDRESS=No se pudo resolver el host
for /f "tokens=1,2,3,4,5" %%v in ('ping -a -n 1 %%i ^&^& echo SERVER_IS_UP')
do (
if %%v==Haciendo set SERVER_ADDRESS=%%z
if %%v==Respuesta set SERVER_ADDRESS=%%x
if %%v==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE!
)
You can find a sample code about sharpening image using "unsharp mask" algorithm at OpenCV Documentation.
Changing values of sigma
,threshold
,amount
will give different results.
// sharpen image using "unsharp mask" algorithm
Mat blurred; double sigma = 1, threshold = 5, amount = 1;
GaussianBlur(img, blurred, Size(), sigma, sigma);
Mat lowContrastMask = abs(img - blurred) < threshold;
Mat sharpened = img*(1+amount) + blurred*(-amount);
img.copyTo(sharpened, lowContrastMask);
The localStorage
can only store string content and you are trying to store a jQuery object since html(htmlString)
returns a jQuery object.
You need to set the string content instead of an object. And use the setItem
method to add data and getItem
to get data.
window.localStorage.setItem('content', 'Test');
$('#test').html(window.localStorage.getItem('content'));
public void scheduleAtFixedRate(TimerTask task,
long delay,
long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).
Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.
Parameters:
Throws:
I know there is already a good answer posted, but it won't allow leading zeros. And I don't have enough reputation to leave a comment, so... Here's my solution allowing leading zeros:
First I match the numbers 50 through 99 (with possible leading zeros):
0*[5-9]\d
Then match numbers of 100 and above (also with leading zeros):
0*[1-9]\d{2,}
Add them together with an "or" and wrap it up to match the whole sentence:
^0*([1-9]\d{2,}|[5-9]\d)$
That's it!
Combine the use of window.btoa
and window.atob
together with
JSON.stringify
and JSON.parse
.
- This works for strings containing single quotes
Encoding the data:
var encodedObject = window.btoa(JSON.stringify(dataObject));
Decoding the data:
var dataObject = JSON.parse(window.atob(encodedObject));
Here is an example of how the data is constructed and decoded later with the click event.
Construct the html and encode the data:
var encodedObject = window.btoa(JSON.stringify(dataObject));
"<td>" + "<a class='eventClass' href='#' data-topic='" + encodedObject + "'>"
+ "Edit</a></td>"
Decode the data in the click event handler:
$("#someElementID").on('click', 'eventClass', function(e) {
event.preventDefault();
var encodedObject = e.target.attributes["data-topic"].value;
var dataObject = JSON.parse(window.atob(encodedObject));
// use the dataObject["keyName"]
}
I also had the same error. I had not added the below dependency in my POM file.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
But My porject used to run even before I had added this dependency. But at one point it stopped and started giving the same above error.
If any one couldn't solve this error they can also solve by this link
This is one of the method to overcome this issue.
client.cpp
#ifndef SOCKET_CLIENT_CLASS
#define SOCKET_CLIENT_CLASS
#ifndef BOOST_ASIO_HPP
#include <boost/asio.hpp>
#endif
class SocketClient // Or whatever the name is... {
// ...
bool read(int, char*); // Or whatever the name is...
// ... };
#endif
client.h
bool SocketClient::read(int, char*)
{
// Implementation goes here...
}
main.cpp
#include <iostream>
#include <string>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include "client.h"
// ^^ Notice this!
main.h
int main()
Look at the image to be clear about gravity
Very near to TheEye answer, but I change a little thing to make it work:
var num = 192.16;_x000D_
_x000D_
console.log( Math.ceil(num * 10) / 10 );
_x000D_
Use the Index property in your DGV's SelectedRows collection:
int index = yourDGV.SelectedRows[0].Index;
Now that Java 8 supports lambdas, it's possible to create Java APIs that closely resemble LINQ.
Jinq is one of these new LINQ-style libraries for Java.
I am the developer of this library. It is based on five years of research on using bytecode analysis to translate Java to database queries. Similar to how C#'s D-LINQ is a query layer that sits on top of the Entity Framework, Jinq is able to act as a query layer sitting on top of JPA or jOOQ. It has support for aggregation, groups, and subqueries. Even Erik Meijer (the creator of LINQ) has acknowledged Jinq.
At least for MS VC++, the C Runtime library has several functions that I've found helpful in the past. Check the MSDN help for the _Crt*
functions.
function is_array_assoc($foo) {
if (is_array($foo)) {
return (count(array_filter(array_keys($foo), 'is_string')) > 0);
}
return false;
}
Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances.
patchValue
does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls. On the other hand, setValue
requires all Form Control values to be filled in, and it will return an error if any of your controls are not specified within the parameter.
In this scenario, we will want to use patchValue, since we are only updating user
and questioning
:
this.qService.editQue([params["id"]]).subscribe(res => {
this.question = res;
this.editqueForm.patchValue({
user: this.question.user,
questioning: this.question.questioning
});
});
EDIT: If you feel like doing some of ES6's Object Destructuring, you may be interested to do this instead
const { user, questioning } = this.question;
this.editqueForm.patchValue({
user,
questioning
});
Ta-dah!
You should use the resource folders such as
values-ldpi
values-mdpi
values-hdpi
And write the text size in 'dimensions.xml' file for each range.
And in the java code you can set the text size with
textView.setTextSize(getResources().getDimension(R.dimen.textsize));
Sample dimensions.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="textsize">15sp</dimen>
</resources>
After allocating DateFormatter
you need to give the formatted string
then you can convert as string like this way
var date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
let updatedString = formatter.string(from: yourDate!)
print(updatedString)
OutPut
01-Mar-2017
In cryptography there are two types of algorithms used:
Symmetric algorithms
A single key is used to encrypt data. When encrypted with the key, the data can be decrypted using the same key. If, for example, Mary encrypts a message using the key "my-secret" and sends it to John, he will be able to decrypt the message correctly with the same key "my-secret".
Asymmetric algorithms
Two keys are used to encrypt and decrypt messages. While one key(public) is used to encrypt the message, the other key(private) can only be used to decrypt it. So, John can generate both public and private keys, then send only the public key to Mary to encrypt her message. The message can only be decrypted using the private key.
HS256 and RS256 Scenario
These algorithms are NOT used to encrypt/decryt data. Rather they are used to verify the origin or the authenticity of the data. When Mary needs to send an open message to Jhon and he needs to verify that the message is surely from Mary, HS256 or RS256 can be used.
HS256 can create a signature for a given sample of data using a single key. When the message is transmitted along with the signature, the receiving party can use the same key to verify that the signature matches the message.
RS256 uses pair of keys to do the same. A signature can only be generated using the private key. And the public key has to be used to verify the signature. In this scenario, even if Jack finds the public key, he cannot create a spoof message with a signature to impersonate Mary.
Just make Alberto Gaona's answer into one line
token=$(cat ~/.emulator_console_auth_token); cat <(echo -e "auth $token \n geo fix 96.0290791 16.9041016 \n exit") - | nc localhost 5554
5554 is the emulator port number shown in adb devices
.
It would have been better if adb emu
work.
It is possible to enable/disable wifi on pre Android 10 devices using the following code:
WifiManager wifiManager =
(WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);
But note that it is not possible to do this anymore on Android 10 and probably going ahead as well.
https://issuetracker.google.com/issues/141011684
You could use echo $(/usr/libexec/java_home)
command in your terminal to know the path where Java being installed.
Is this what you are looking for? Otherwise, let me know and I will remove this post.
Try this jQuery plugin: http://archive.plugins.jquery.com/project/client-detect
Demo: http://www.stoimen.com/jquery.client.plugin/
This is based on quirksmode BrowserDetect a wrap for jQuery browser/os detection plugin.
For keen readers:
http://www.stoimen.com/blog/2009/07/16/jquery-browser-and-os-detection-plugin/
http://www.quirksmode.org/js/support.html
And more code around the plugin resides here: http://www.stoimen.com/jquery.client.plugin/jquery.client.js
i find best for do it fast and simple
find ur item in list
var d = Details.Where(x => x.ProductID == selectedProduct.ID).SingleOrDefault();
make clone from current
OrderDetail dd = d;
Update ur clone
dd.Quantity++;
find index in list
int idx = Details.IndexOf(d);
remove founded item in (1)
Details.Remove(d);
insert
if (idx > -1)
Details.Insert(idx, dd);
else
Details.Insert(Details.Count, dd);
Playing around with different project properties, I found that the project build order was the problem. The project that generated the files I wanted to copy was built second, but the project that was running the batch file as a post-build event was built first, so I simply attached the build event to the second project instead, and it works just fine. Thanks for your help, everyone, though.
Create Refresh control using Selector method.
var refreshCntrl : UIRefreshControl!
refreshCntrl = UIRefreshControl()
refreshCntrl.tintColor = UIColor.whiteColor()
refreshCntrl.attributedTitle = NSAttributedString(string: "Please Wait...")
refreshCntrl.addTarget(self, action:"refreshControlValueChanged", forControlEvents: UIControlEvents.ValueChanged)
atableView.addSubview(refreshCntrl)
//Refresh Control Method
func refreshControlValueChanged(){
atableView.reloadData()
refreshCntrl.endRefreshing()
}
This will only work in C++. Functions in structs are not a feature of C.
Same goes for your client.AddClient(); call ... this is a call for a member function, which is object oriented programming, i.e. C++.
Convert your source to a .cpp file and make sure you are compiling accordingly.
If you need to stick to C, the code below is (sort of) the equivalent:
typedef struct client_t client_t, *pno;
struct client_t
{
pid_t pid;
char password[TAM_MAX]; // -> 50 chars
pno next;
};
pno AddClient(pno *pclient)
{
/* code */
}
int main()
{
client_t client;
//code ..
AddClient(client);
}
I like to run a "bare-bones" version of Python 2 to verify scripts that I create for other people without an advanced python setup. But Anaconda and Python 3 have a lot of nice features. To enjoy both things on the same computer I do this on my Windows computer which allows me to easily switch.
C:\Users>python --version
Python 2.7.11
C:\Users>conda create --name p3 python=3
C:\Users>conda info --envs
Using Anaconda Cloud api site https://api.anaconda.org
# conda environments:
#
p3 C:\Anaconda3\envs\p3
root * C:\Anaconda3
C:\Users>activate p3
Deactivating environment "C:\Anaconda3"...
Activating environment "C:\Anaconda3\envs\p3"...
[p3] C:\Users>python --version
Python 3.5.1 :: Continuum Analytics, Inc.
For more info: http://conda.pydata.org/docs/test-drive.html
The usual error is one tries to put Content-Type: {multipart/form-data}
into the header of the post request. That will fail, it is best to let Postman do it for you. For example:
To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():
so, below code is to convert the local time to other time zone.
# Time conversion from local time
import datetime
import pytz
dt_today = datetime.datetime.today() # Local time
dt_India = dt_today.astimezone(pytz.timezone('Asia/Kolkata'))
dt_London = dt_today.astimezone(pytz.timezone('Europe/London'))
India = (dt_India.strftime('%m/%d/%Y %H:%M'))
London = (dt_London.strftime('%m/%d/%Y %H:%M'))
print("Indian standard time: "+India+" IST")
print("British Summer Time: "+London+" BST")
import pytz
for tz in pytz.all_timezones:
print(tz)
it may be very old post, but I would like to share my experience. I had the same issue when I used Pycharm and I installed the package from Project Interpreter page in the Project Settings/Preferences... That fixed the issue, please check below link: https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html?_ga=2.41088674.1813230270.1594526819-1842497340.1594080707
I am using ng2 with webpack, not system JS. Steps need for me were:
npm install underscore --save
typings install dt~underscore --global --save
and then in the file I wish to import underscore into:
import * as _ from 'underscore';
if you're after the catalina.out log and you are using eclispe with tomcat, this works for me:
I could not made your code to do the desired query, the AS is an alias only for the table abc
, not for the derived table.
Laravel Query Builder does not implicitly support derived table aliases, DB::raw is most likely needed for this.
The most straight solution I could came up with is almost identical to yours, however produces the query as you asked for:
$sql = Abc::groupBy('col1')->toSql();
$count = DB::table(DB::raw("($sql) AS a"))->count();
The produced query is
select count(*) as aggregate from (select * from `abc` group by `col1`) AS a;
This is an error message you see whenever you have a situation like the following:
char* pointer_to_nonconst = "string literal";
Why? Well, C and C++ differ in the type of the string literal. In C the type is array of char and in C++ it is constant array of char. In any case, you are not allowed to change the characters of the string literal, so the const in C++ is not really a restriction but more of a type safety thing. A conversion from const char*
to char*
is generally not possible without an explicit cast for safety reasons. But for backwards compatibility with C the language C++ still allows assigning a string literal to a char*
and gives you a warning about this conversion being deprecated.
So, somewhere you are missing one or more const
s in your program for const correctness. But the code you showed to us is not the problem as it does not do this kind of deprecated conversion. The warning must have come from some other place.
/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
int result = 0;
Iterator<Row> rowIterator = xssfSheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<Cell> cells = new ArrayList<>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cells.add(cellIterator.next());
}
for (int i = cells.size(); i >= 0; i--) {
Cell cell = cells.get(i-1);
if (cell.toString().trim().isEmpty()) {
cells.remove(i-1);
} else {
result = cells.size() > result ? cells.size() : result;
break;
}
}
}
return result;
}
In case of VSCode, follow the below steps:
That worked for me.
bool doesL1ContainsL2 = l1.Intersect(l2).Count() == l2.Count;
L1 and L2 are both List<T>
My favorite...
Url.Content(Request.Url.PathAndQuery)
or just...
Url.Action()
C:\Program Files\Android\Android Studio\jre\bin>java -version
openjdk version "1.8.0_76-release"
OpenJDK Runtime Environment (build 1.8.0_76-release-b03)
OpenJDK 64-Bit Server VM (build 25.76-b03, mixed mode)
Somehow the Studio installer would install another version under:
C:\Program Files\Android\Android Studio\jre\jre\bin>java -version
openjdk version "1.8.0_76-release"
OpenJDK Runtime Environment (build 1.8.0_76-release-b03)
OpenJDK 64-Bit Server VM (build 25.76-b03, mixed mode)
where the latest version was installed the Java DevKit installer in:
C:\Program Files\Java\jre1.8.0_121\bin>java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
Need to clean up the Android Studio so it would use the proper latest 1.8.0 versions.
According to How to set Java SDK path in AndroidStudio? one could override with a specific JDK but when I renamed
C:\Program Files\Android\Android Studio\jre\jre\
to:
C:\Program Files\Android\Android Studio\jre\oldjre\
And restarted Android Studio, it would complain that the jre was invalid.
When I tried to aecify an JDK to pick the one in C:\Program Files\Java\jre1.8.0_121\bin
or:
C:\Program Files\Java\jre1.8.0_121\
It said that these folders are invalid. So I guess that the embedded version must have some special purpose.
If you really want to create an array rather than a list use either
String[] names = ["lucas", "Fred", "Mary"]
or
def names = ["lucas", "Fred", "Mary"].toArray()
I recommend using a cache-buster in the wsdl url.
In our apps we use a SVN Revision id in the wsdl url so the client immediately knows of changing structures. This works on our app because, everytime we change the server-side, we also need to adjust the client accordingly.
$client = new SoapClient('http://somewhere.com/?wsdl&rev=$Revision$');
This requires svn to be configured properly. Not on all repositories this is enabled by default.
In case you are not responsible for both components (server,client) or you don't use SVN you may find another indicator which can be utilised as a cache-buster in your wsdl url.
For varchars, you may need to do something like this:
select convert(varchar(25), NULL) as abc_column into xyz_table
If you try
select '' as abc_column into xyz_table
you may get errors related to truncation, or an issue with null values, once you populate.
For older versions of jQuery
jQuery().jquery (or)
jQuery().fn.jquery
For newer versions of jQuery
$().jquery (or)
$().fn.jquery
When you specify position:absolute it positions itself to the next-highest element with position:relative. In this case, that's the .project div.
If you give the image's immediate parent div a style of position:relative, the overlay will key to that instead of the div which includes the text. For example: http://jsfiddle.net/7gYUU/1/
<div class="parent">
<img src="http://placehold.it/500x500" class="img-responsive"/>
<div class="fa fa-plus project-overlay"></div>
</div>
.parent {
position: relative;
}
I recently discovered q:
. It opens the "command window" and shows your most recent ex-mode (command-mode) commands. You can move as usual within the window, and pressing <CR>
executes the command. You can edit, etc. too. Priceless when you're messing around with some complex command or regex and you don't want to retype the whole thing, or if the complex thing you want to do was 3 commands back. It's almost like bash's set -o vi
, but for vim itself (heh!).
See :help q:
for more interesting bits for going back and forth.
Small correction for the Set-Content command. If the searched string is not found the Set-Content
command will blank (empty) the target file.
You can first verify if the string you are looking for exist or not. If not it will not replace anything.
If (select-string -path "c:\Windows\System32\drivers\etc\hosts" -pattern "String to look for") `
{(Get-Content c:\Windows\System32\drivers\etc\hosts).replace('String to look for', 'String to replace with') | Set-Content c:\Windows\System32\drivers\etc\hosts}
Else{"Nothing happened"}
use numpy
import numpy
zarray = numpy.zeros(100)
And then use the Histogram library function
I know I'm late to the party, but try this...
SELECT
`Train`,
`Dest`,
SUBSTRING_INDEX(GROUP_CONCAT(`Time` ORDER BY `Time` DESC), ",", 1) AS `Time`
FROM TrainTable
GROUP BY Train;
Src: Group Concat Documentation
Edit: fixed sql syntax
Some working Java code based on Sarp's answer:
public class permute {
static void permute(int level, String permuted,
boolean used[], String original) {
int length = original.length();
if (level == length) {
System.out.println(permuted);
} else {
for (int i = 0; i < length; i++) {
if (!used[i]) {
used[i] = true;
permute(level + 1, permuted + original.charAt(i),
used, original);
used[i] = false;
}
}
}
}
public static void main(String[] args) {
String s = "hello";
boolean used[] = {false, false, false, false, false};
permute(0, "", used, s);
}
}
You're missing semi-colons after your javascript lines. Also, window.location
should have .href
or .replace
etc to redirect - See this post for more information.
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location.href = "index.php";';
echo '</script>';
For clarity, try leaving PHP tags for this:
?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php
NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.
The only problem with JSON in Java is that if your XML has a single child, but is an array, it will convert it to an object instead of an array. This can cause problems if you dynamically always convert from XML to JSON, where if your example XML has only one element, you return an object, but if it has 2+, you return an array, which can cause parsing issues for people using the JSON.
Infoscoop's XML2JSON class has a way of tagging elements that are arrays before doing the conversion, so that arrays can be properly mapped, even if there is only one child in the XML.
Here is an example of using it (in a slightly different language, but you can also see how arrays is used from the nodelist2json() method of the XML2JSON link).
Nowadays you can use lodash:
var x = 1;
var y = 5;
var z = 3;
_.inRange(z,x,y);
//results true
To ensure success with a full path use recurse=yes
- name: ensure custom facts directory exists
file: >
path=/etc/ansible/facts.d
recurse=yes
state=directory
GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH
. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:
export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH
Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).
PDOStatement->execute()
returns true on success. There is also PDOStatement->errorCode()
which you can check for errors.
I had through the same situation. I solved using two Promise.All().
I think was really good solution, so I published it on npm: https://www.npmjs.com/package/promise-foreach
I think your code will be something like this
var promiseForeach = require('promise-foreach')
var jsonItems = [];
promiseForeach.each(jsonItems,
[function (jsonItems){
return new Promise(function(resolve, reject){
if(jsonItems.type === 'file'){
jsonItems.getFile().then(function(file){ //or promise.all?
resolve(file.getSize())
})
}
})
}],
function (result, current) {
return {
type: current.type,
size: jsonItems.result[0]
}
},
function (err, newList) {
if (err) {
console.error(err)
return;
}
console.log('new jsonItems : ', newList)
})
You need to use document.getElementById()
in line 3.
If you try this right now in the console:
var img = document.createElement("img");_x000D_
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";_x000D_
var src = document.getElementById("header");_x000D_
src.appendChild(img);
_x000D_
<div id="header"></div>
_x000D_
... you'd get this:
In case people are searching how to do it in BigQuery:
An underscore "_" matches a single character or byte.
You can escape "\", "_", or "%" using two backslashes. For example, "\%". If you are using raw strings, only a single backslash is required. For example, r"\%".
WHERE mycolumn LIKE '%\\_%'
Source: https://cloud.google.com/bigquery/docs/reference/standard-sql/operators
WebClient
doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:
Using client as new WebClient
result = client.UploadString(someurl, "param1=somevalue¶m2=othervalue")
End Using
Try:
<c:if test = "${ansokanInfo.PSystem == 'NAT'}">
JSP/Servlet 2.4 (I think that's the version number) doesn't support method calls in EL and only support properties. The latest servlet containers do support method calls (ie Tomcat 7).
Use JavaScript for this. You can do:
echo '
<script type="text/javascript">
parent.window.location.reload(true);
</script>
';
In PHP and it will refresh the parent's frame page.
// logout
if(isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header('location:login.php');
}
?>
You are making it complicated. string
is already nullable. You don't need to make it more nullable. Take out the ?
on the property type.
I agree with yossi's example, stretch the image to fit the div but in a slightly different way (without background-image as this is a little inflexible in css 2.1). Show full image:
<div id="yourdiv">
<img id="theimage" src="image.jpg" alt="" />
</div>
#yourdiv img {
width:100%;
/*height will be automatic to remain aspect ratio*/
}
Show part of the image using background-position:
#yourdiv
{
background-image: url(image.jpg);
background-repeat: no-repeat;
background-position: 10px 25px;
}
Same as the first part of (1) the image will scale to the div so bigger or smaller will both work
Same as yossi's.
Please make sure that you have added the dependency in pom.xml or gradle file
spring-boot-starter-data-jpa
After adding the JDK
repo, before Installing you might want to run an update first so the repo can be added
run
apt update
an then continue with your installation
sudo apt install adoptopenjdk-8-hotspot
Try to use TranslateAnimation class, which creates the animation for position changes. Try reading this for help - http://developer.android.com/reference/android/view/animation/TranslateAnimation.html
Update: Here's the example for this. If you have the height of your view as 50 and in the hide mode you want to show only 10 px. The sample code would be -
TranslateAnimation anim=new TranslateAnimation(0,0,-40,0);
anim.setFillAfter(true);
view.setAnimation(anim);
PS: There are lot's or other methods there to help you use the animation according to your need. Also have a look at the RelativeLayout.LayoutParams if you want to completely customize the code, however using the TranslateAnimation is easier to use.
EDIT:-Complex version using LayoutParams
RelativeLayout relParam=new RelativeLayout.LayoutParam(RelativeLayout.LayoutParam.FILL_PARENT,RelativeLayout.LayoutParam.WRAP_CONTENT); //you can give hard coded width and height here in (width,height) format.
relParam.topMargin=-50; //any number that work.Set it to 0, when you want to show it.
view.setLayoutParams(relparam);
This example code assumes you are putting your view in RelativeLayout, if not change the name of Layout, however other layout might not work. If you want to give an animation effect on them, reduce or increase the topMargin slowly. You can consider using Thread.sleep() there too.
For Mac OS, you may use the below command in order to remove files manually.
sudo rm -rf /usr/local/bin/jupyter
For SQL 2005 and up
SELECT ROW_NUMBER() OVER( ORDER BY SomeColumn ) AS 'rownumber',*
FROM YourTable
for 2000 you need to do something like this
SELECT IDENTITY(INT, 1,1) AS Rank ,VALUE
INTO #Ranks FROM YourTable WHERE 1=0
INSERT INTO #Ranks
SELECT SomeColumn FROM YourTable
ORDER BY SomeColumn
SELECT * FROM #Ranks
Order By Ranks
see also here Row Number
Looking at the posts above I would like to give a more clarified answer:
Suppose our main.c
file looks like this:
#include "header.h"
int main(void) {
FunctionInHeader();
}
Now consider three cases:
Case 1:
Our header.h
file looks like this:
#include <stdio.h>
static void FunctionInHeader();
void FunctionInHeader() {
printf("Calling function inside header\n");
}
Then the following command on linux:
gcc main.c -o main
will succeed! That's because after the main.c
file includes the header.h
, the static function definition will be in the same main.c
file (more precisely, in the same translation unit) to where it's called.
If one runs ./main
, the output will be Calling function inside header
, which is what that static function should print.
Case 2: Our header header.h
looks like this:
static void FunctionInHeader();
and we also have one more file header.c
, which looks like this:
#include <stdio.h>
#include "header.h"
void FunctionInHeader() {
printf("Calling function inside header\n");
}
Then the following command
gcc main.c header.c -o main
will give an error. In this case main.c
includes only the declaration of the static function, but the definition is left in another translation unit and the static
keyword prevents the code defining a function to be linked
Case 3:
Similar to case 2, except that now our header header.h
file is:
void FunctionInHeader(); // keyword static removed
Then the same command as in case 2 will succeed, and further executing ./main
will give the expected result. Here the FunctionInHeader
definition is in another translation unit, but the code defining it can be linked.
Thus, to conclude:
static keyword prevents the code defining a function to be linked,
when that function is defined in another translation unit than where it is called.
Public Shared Function GetFOMPrev(ByVal tdate As Date) As Date
Return tdate.AddDays(-(tdate.Day - 1))
End Function
Public Shared Function GetEOMPrev(ByVal tdate As Date) As Date
Return tdate.AddDays(-tdate.Day)
End Function
Usage:
'Get End of Month of Previous Month - Pass today's date
EOM = GetEOMPrev(Date.Today)
'Get First of Month of Previous Month - Pass date just calculated
FOM = GetFOMPrev(EOM)
There is no shorthand in VBA unfortunately, The closest you will get is a purely visual thing using the :
continuation character if you want it on one line for readability;
Dim clientToTest As String: clientToTest = clientsToTest(i)
Dim clientString As Variant: clientString = Split(clientToTest)
Hint (summary of other answers/comments): Works with objects too (Excel 2010):
Dim ws As Worksheet: Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim ws2 As New Worksheet: ws2.Name = "test"
You can also simply use the HtmlString
class
@(new HtmlString(Model.Content))
I had the same problem with a freshly installed copy of Chrome.
If nothing works, and your Use a proxy server your LAN
setting is unchecked, check it and then uncheck it . Believe it or not it might work. I don't know if I should consider it a bug or not.
You can if your processor is 64-bit and Virtualization Technology (VT) extension is enabled (it can be switched off in BIOS). You can't do it on 32-bit processor.
To check this under Linux you just need to look into /proc/cpuinfo file. Just look for the appropriate flag (vmx for Intel processor or svm for AMD processor)
egrep '(vmx|svm)' /proc/cpuinfo
To check this under Windows you need to use a program like CPU-Z which will display your processor architecture and supported extensions.
The Background Panel entry shows a couple of different ways depending on your requirements.
I know how to create a custom row + custom array adapter to support a custom row for the entire list view. But how can one listview support many different row styles?
You already know the basics. You just need to get your custom adapter to return a different layout/view based on the row/cursor information being provided.
A ListView
can support multiple row styles because it derives from AdapterView:
An AdapterView is a view whose children are determined by an Adapter.
If you look at the Adapter, you'll see methods that account for using row-specific views:
abstract int getViewTypeCount()
// Returns the number of types of Views that will be created ...
abstract int getItemViewType(int position)
// Get the type of View that will be created ...
abstract View getView(int position, View convertView, ViewGroup parent)
// Get a View that displays the data ...
The latter two methods provide the position so you can use that to determine the type of view you should use for that row.
Of course, you generally don't use AdapterView and Adapter directly, but rather use or derive from one of their subclasses. The subclasses of Adapter may add additional functionality that change how to get custom layouts for different rows. Since the view used for a given row is driven by the adapter, the trick is to get the adapter to return the desired view for a given row. How to do this differs depending on the specific adapter.
For example, to use ArrayAdapter,
getView()
to inflate, populate, and return the desired view for the given position. The getView()
method includes an opportunity reuse views via the convertView
parameter.But to use derivatives of CursorAdapter,
newView()
to inflate, populate, and return the desired view for the current cursor state (i.e. the current "row") [you also need to override bindView
so that widget can reuse views]However, to use SimpleCursorAdapter,
SimpleCursorAdapter.ViewBinder
with a setViewValue()
method to inflate, populate, and return the desired view for a given row (current cursor state) and data "column". The method can define just the "special" views and defer to SimpleCursorAdapter's standard behavior for the "normal" bindings.Look up the specific examples/tutorials for the kind of adapter you end up using.
$('tableName').find('tr').length
It's a limitation of the language. In section 6.7.8/4:
All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.
In section 6.6, the spec defines what must considered a constant expression. No where does it state that a const variable must be considered a constant expression. It is legal for a compiler to extend this (6.6/10 - An implementation may accept other forms of constant expressions
) but that would limit portability.
If you can change my_foo
so it does not have static storage, you would be okay:
int main()
{
foo_t my_foo = foo_init;
return 0;
}
java.util.Arrays.asList(new String[]{"a", "b"})
Add:
using System.Linq;
to the top of your file.
And then:
Car[] carList = ...
var carMake =
from item in carList
where item.Model == "bmw"
select item.Make;
or if you prefer the fluent syntax:
var carMake = carList
.Where(item => item.Model == "bmw")
.Select(item => item.Make);
Things to pay attention to:
item.Make
in the select
clause instead if s.Make
as in your code.item
and .Model
in your where
clauseIf you use JSON properly, you can have nested object without any issue :
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));
I used /etc/crontab
. I used vi
and entered in the PATHs I needed into this file and ran it as root. The normal crontab overwrites PATHs that you have set up. A good tutorial on how to do this.
The systemwide cron file looks like this:
This has the username field, as used by /etc/crontab.
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file.
# This file also has a username field, that none of the other crontabs do.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# m h dom mon dow user command
42 6 * * * root run-parts --report /etc/cron.daily
47 6 * * 7 root run-parts --report /etc/cron.weekly
52 6 1 * * root run-parts --report /etc/cron.monthly
01 01 * * 1-5 root python /path/to/file.py
If you have access to the NgModelController (you can only get access to it from a directive) then you can call
ngModel.$setViewValue("your new view value");
// or to keep the view value the same and just change it to dirty
ngModel.$setViewValue(ngModel.$viewValue);
Don't use absolute paths, make them relative to the 'resources' directory in your project. Quick and dirty code that displays the contents of MyTest.txt from the directory 'resources'.
@Test
public void testDefaultResource() {
// can we see default resources
BufferedInputStream result = (BufferedInputStream)
Config.class.getClassLoader().getResourceAsStream("MyTest.txt");
byte [] b = new byte[256];
int val = 0;
String txt = null;
do {
try {
val = result.read(b);
if (val > 0) {
txt += new String(b, 0, val);
}
} catch (IOException e) {
e.printStackTrace();
}
} while (val > -1);
System.out.println(txt);
}
Simple Array
let simpleArray = [1,2,3,4]
let commaSeperated = simpleArray.join(",");
console.log(commaSeperated);
_x000D_
Array of Objects with a particular attributes as comma separated.
let arrayOfObjects = [
{
id : 1,
name : "Name 1",
address : "Address 1"
},
{
id : 2,
name : "Name 2",
address : "Address 2"
},
{
id : 3,
name : "Name 3",
address : "Address 3"
}]
let names = arrayOfObjects.map(x => x.name).join(", ");
console.log(names);
_x000D_
div {_x000D_
height: 100px;_x000D_
width: 50%;_x000D_
margin: 0 auto;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
div:hover {_x000D_
overflow-y: scroll;_x000D_
}
_x000D_
<div>_x000D_
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It_x000D_
has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop_x000D_
publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</p>_x000D_
</div>
_x000D_
Would something like that work?
I know it's not the answer to the original question, but you may find yourself here with this problem.
If you want all of the duplicate items in your results, the following works.
var duplicates = list
.GroupBy( x => x ) // group matching items
.Where( g => g.Skip(1).Any() ) // where the group contains more than one item
.SelectMany( g => g ); // re-expand the groups with more than one item
In my situation I need all duplicates so that I can mark them in the UI as being errors.
Here is a little improvement for Smilediver's answer, it will not escape all no-ASCII chars but only these are really needed.
using System;
using System.Globalization;
using System.Text;
public static class CodeHelper
{
public static string ToLiteral(this string input)
{
var literal = new StringBuilder(input.Length + 2);
literal.Append("\"");
foreach (var c in input)
{
switch (c)
{
case '\'': literal.Append(@"\'"); break;
case '\"': literal.Append("\\\""); break;
case '\\': literal.Append(@"\\"); break;
case '\0': literal.Append(@"\0"); break;
case '\a': literal.Append(@"\a"); break;
case '\b': literal.Append(@"\b"); break;
case '\f': literal.Append(@"\f"); break;
case '\n': literal.Append(@"\n"); break;
case '\r': literal.Append(@"\r"); break;
case '\t': literal.Append(@"\t"); break;
case '\v': literal.Append(@"\v"); break;
default:
if (Char.GetUnicodeCategory(c) != UnicodeCategory.Control)
{
literal.Append(c);
}
else
{
literal.Append(@"\u");
literal.Append(((ushort)c).ToString("x4"));
}
break;
}
}
literal.Append("\"");
return literal.ToString();
}
}
It's rather safe to add @SafeVarargs
annotation to the method when you can control the way it's called (e.g. a private method of a class). You must make sure that only the instances of the declared generic type are passed to the method.
If the method exposed externally as a library, it becomes hard to catch such mistakes. In this case it's best to avoid this annotation and rewrite the solution with a collection type (e.g. Collection<Type1<Type2>>
) input instead of varargs (Type1<Type2>...
).
As for the naming, the term heap pollution phenomenon is quite misleading in my opinion. In the documentation the actual JVM heap is not event mentioned. There is a question at Software Engineering that contains some interesting thoughts on the naming of this phenomenon.
Gooye if it's possible to use Joda Time in your project then this code works for me:
String dateStr = "2012-10-01T09:45:00.000+02:00";
String customFormat = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
LocalDateTime parsedDate = dtf.parseLocalDateTime(dateStr);
String dateWithCustomFormat = parsedDate.toString(DateTimeFormat.forPattern(customFormat));
System.out.println(dateWithCustomFormat);
Working as of Feb 04 2014 :):
If you have tried installing pip through the Windows installer file from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip as suggested by @Colonel Panic, you might have installed the pip package manager successfully, but you might be unable to install any packages with pip. You might also have got the same SSL error as I got when I tried to install Beautiful Soup 4 if you look in the pip.log file:
Downloading/unpacking beautifulsoup4
Getting page https://pypi.python.org/simple/beautifulsoup4/
Could not fetch URL https://pypi.python.org/simple/beautifulsoup4/: **connection error: [Errno 1] _ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed**
Will skip URL https://pypi.python.org/simple/beautifulsoup4/ when looking for download links for beautifulsoup4
The problem is an issue with an old version of OpenSSL being incompatible with pip 1.3.1 and above versions. The easy workaround for now, is to install pip 1.2.1, which does not require SSL:
Installing Pip on Windows:
cd <path to extracted folder>/pip-1.2.1
python setup.py install
C:\Python27\Scripts
is in PATH because pip is installed in the C:\Python27\Scripts
directory unlike C:\Python27\Lib\site-packages
where Python packages are normally installedNow try to install any package using pip.
For example, to install the requests
package using pip, run this from cmd:
pip install requests
Whola! requests
will be successfully installed and you will get a success message.
I have this folder structure:
D:\JavaProjects\OlivePressApp\com\lynda\olivepress\Main.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\press\OlivePress.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Kalamata.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Ligurian.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Olive.class
Main.class
is in package com.lynda.olivepress
There are two other packages:
com.lynda.olivepress.press
com.lynda.olivepress.olive
1) Create a file named "Manifest.txt"
with Two Lines, First with Main-Class and a Second Empty Line.
Main-Class: com.lynda.olivepress.Main
D:\JavaProjects\OlivePressApp\ Manifest.txt
2) Create JAR with Manifest and Main-Class Entry Point
D:\JavaProjects\OlivePressApp>jar cfm OlivePressApp.jar Manifest.txt com/lynda/olivepress/Main.class com/lynda/olivepress/*
3) Run JAR
java -jar OlivePressApp.jar
Note: com/lynda/olivepress/*
means including the other two packages mentioned above, before point 1)
mysql_fetch_array()
expects parameter 1 to be resource boolean given in php error on server if you get this error : please select all privileges on your server
. u will get the answer..
Without using any plugin you can opt this logic.
$("#btn").click(function () {
//Hide all other elements other than printarea.
$("#printarea").show();
window.print();
});
Change padding-bottom , i.e may be the simplest possible way .
Well.. I'm not sure how portable os.chdir('..') would actually be. Under Unix those are real filenames. I would prefer the following:
import os
os.chdir(os.path.dirname(os.getcwd()))
That gets the current working directory, steps up one directory, and then changes to that directory.
`ALTER TABLE `table_name` CHANGE `column_name`
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP
Can be used to update the timestamp on update.
A short and sweet solution, using ES6:
document.querySelectorAll('.input')
.forEach(input => input.addEventListener('focus', this.onInputFocus));
The recommended way to style the Toolbar for a Light.DarkActionBar
clone would be to use Theme.AppCompat.Light.DarkActionbar
as parent/app theme and add the following attributes to the style to hide the default ActionBar:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
Then use the following as your Toolbar:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
For further modifications, you would create styles extending ThemeOverlay.AppCompat.Dark.ActionBar
and ThemeOverlay.AppCompat.Light
replacing the ones within AppBarLayout->android:theme
and Toolbar->app:popupTheme
. Also note that this will pick up your ?attr/colorPrimary
if you have set it in your main style so you might get a different background color.
You will find a good example of this is in the current project template with an Empty Activity
of Android Studio (1.4+).
You can try Alasql JavaScript library which can work together with XLSX.js library for easy export of Angular.js data. This is an example of controller with exportData() function:
function myCtrl($scope) {
$scope.exportData = function () {
alasql('SELECT * INTO XLSX("john.xlsx",{headers:true}) FROM ?',[$scope.items]);
};
$scope.items = [{
name: "John Smith",
email: "[email protected]",
dob: "1985-10-10"
}, {
name: "Jane Smith",
email: "[email protected]",
dob: "1988-12-22"
}];
}
See full HTML and JavaScript code for this example in jsFiddle.
UPDATED Another example with coloring cells.
Also you need to include two libraries:
Say:
sed "s|\$ROOT|${HOME}|" abc.sh
Note:
/
since the replacement contains /
$
in the pattern since you don't want to expand it.EDIT: In order to replace all occurrences of $ROOT
, say
sed "s|\$ROOT|${HOME}|g" abc.sh
Alternatively you can use Minio Client aka mc. Its Open Source and compatible with AWS S3. It is available for Linux, Windows, Mac, FreeBSD.
All you have do do is to run mc ls command for listing the contents.
$ mc ls s3/kline/ [2016-04-30 13:20:47 IST] 1.1MiB 1.jpg [2016-04-30 16:03:55 IST] 7.5KiB docker.png [2016-04-30 15:16:17 IST] 50KiB pi.png [2016-05-10 14:34:39 IST] 365KiB upton.pdf
Note:
Installing Minio Client Linux Download mc for:
$ chmod 755 mc $ ./mc --help
Setting up AWS credentials with Minio Client
$ mc config host add mys3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
Note: Please replace mys3 with alias you would like for this account and ,BKIKJAA5BMMU2RHO6IBB, V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 with your AWS ACCESS-KEY and SECRET-KEY
Hope it helps.
Disclaimer: I work for Minio
I'm guessing that Clients.Case_Number
and/or Staff.Emp_ID
are not exactly the same data type as Clients_has_Staff.Clients_Case_Number
and Clients_has_Staff.Staff_Emp_ID
.
Perhaps the columns in the parent tables are INT UNSIGNED
?
They need to be exactly the same data type in both tables.
gdb -ex=r --args myprogram arg1 arg2
-ex=r
is short for -ex=run
and tells gdb to run your program immediately, rather than wait for you to type "run" at the prompt. Then --args
says that everything that follows is the command and arguments, just as you'd normally type them at the commandline prompt.
string col1Value = rdr["ColumnOneName"].ToString();
or
string col1Value = rdr[0].ToString();
These are object
s, so you need to either cast them or .ToString()
.
You can use:
\\
That's ok, for example:
if (invName.substring(j,k).equals("\\")) {
copyf=invName.substring(0,j);
}
Two issues I can see here:
The empty() and remove() methods of jQuery actually do quite a bit of work. See John Resig's JavaScript Function Call Profiling for why.
The other thing is that for large amounts of tabular data you might consider a datagrid library such as the excellent DataTables to load your data on the fly from the server, increasing the number of network calls, but decreasing the size of those calls. I had a very complicated table with 1500 rows that got quite slow, changing to the new AJAX based table made this same data seem rather fast.
As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.
So, writing (in SLF4J version 1.7.x and later)
logger.error("one two three: {} {} {}", "a", "b",
"c", new Exception("something went wrong"));
or writing (in SLF4J version 1.6.x)
logger.error("one two three: {} {} {}", new Object[] {"a", "b",
"c", new Exception("something went wrong")});
will yield
one two three: a b c
java.lang.Exception: something went wrong
at Example.main(Example.java:13)
at java.lang.reflect.Method.invoke(Method.java:597)
at ...
The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.
I assigned the javascript in my Controller:
model.linkCode = "window.open('https://www.yahoo.com', '_blank')";
And in my view:
@section Scripts{
<script @Html.CspScriptNonce()>
$(function () {
@if (!String.IsNullOrEmpty(Model.linkCode))
{
WriteLiteral(Model.linkCode);
}
});
That opened a new tab with the link, and went to it.
Interestingly, run locally it engaged a popup blocker, but seemed to work fine on the servers.
dd-mm-yyyy hh:mm:ss.000 Universal sortable date/time pattern
There is nothing wrong with syntax of
$('#part' + number).html(text);
jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.
In your case you should pass a String to $()
that is
$(<a string>)
Make sure you have access to the variables number
and text
.
To test do:
function(){
alert(number + ":" + text);//or use console.log(number + ":" + text)
$('#part' + number).html(text);
});
If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.
It depends on either the configuration or programmatic change.
Therefore the most reliable way to check the current value is at runtime via code.
See the HttpSessionState.Timeout property; default value is 20 minutes.
You can access this propery in ASP.NET via HttpContext:
this.HttpContext.Session.Timeout // ASP.NET MVC controller
Page.Session.Timeout // ASP.NET Web Forms code-behind
HttpContext.Current.Session.Timeout // Elsewhere
both works similar but "===" even do case statements
"test" == "test" #=> true
"test" === "test" #=> true
here the difference
String === "test" #=> true
String == "test" #=> false
You can KILL the processid.
mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www | Sleep | 25946 | | NULL |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
mysql> kill 1193777;
But:
Or you configure your mysql-server by setting a shorter timeout on wait_timeout
and interactive_timeout
mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| table_lock_wait_timeout | 50 |
| wait_timeout | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)
Set with:
set global wait_timeout=3;
set global interactive_timeout=3;
(and also set in your configuration file, for when your server restarts)
But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...
If you can't get this information from DNS (e.g. you aren't authorized) then one alternative is to use Wolfram Alpha.
stackexchange.com
)You will be able to see a list of sub-domains there. Although I suspect it does not show ALL sub-domains.
Assuming their updates are on master, and you are on the branch you want to merge the changes into.
git remote add origin https://github.com/<github-username>/<repo-name>.git
git pull origin master
Also note that you will then want to push the merge back to your copy of the repository:
git push origin master
Try this:
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
public static void main(String[] argv) throws Exception {
JTextField textField = new JTextField();
textField.addKeyListener(new Keychecker());
JFrame jframe = new JFrame();
jframe.add(textField);
jframe.setSize(400, 350);
jframe.setVisible(true);
}
class Keychecker extends KeyAdapter {
@Override
public void keyPressed(KeyEvent event) {
char ch = event.getKeyChar();
System.out.println(event.getKeyChar());
}
}
you should return Scaffold widget and add your widget inside Scaffold
suck as this code :
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(child: new Text("Hello, World!"));
);
}
}
You might want to you use the @property
decorator,
>>> class Foo():
... @property
... def todo(self):
... raise NotImplementedError("To be implemented")
...
>>> f = Foo()
>>> f.todo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in todo
NotImplementedError: To be implemented
I found it very useful to encode my URL to a safe one when I was returning a value through Ajax/PHP to a URL which was then read by the page again.
PHP output with URL encoder for the special character &
:
// PHP returning the success information of an Ajax request
echo "".str_replace('&', '%26', $_POST['name']) . " category was changed";
// JavaScript sending the value to the URL
window.location.href = 'time.php?return=updated&val=' + msg;
// JavaScript/PHP executing the function printing the value of the URL,
// now with the text normally lost in space because of the reserved & character.
setTimeout("infoApp('updated','<?php echo $_GET['val'];?>');", 360);
For IntelliJ 13.1, go to File -> Settings -> Project Settings -> Compiler -> Java Compiler, and on the right-hand side, for Additional command line parameters
enter "-Xlint:unchecked"
.
The major difference between require
and import
, is that require
will automatically scan node_modules
to find modules, but import
, which comes from ES6, won't.
Most people use babel to compile import
and export
, which makes import
act the same as require
.
The future version of Node.js might support import
itself (actually, the experimental version already does), and judging by Node.js' notes, import
won't support node_modules
, it base on ES6, and must specify the path of the module.
So I would suggest you not use import
with babel, but this feature is not yet confirmed, it might support node_modules
in the future, who would know?
For reference, below is an example of how babel can convert ES6's import
syntax to CommonJS's require
syntax.
Say the fileapp_es6.js
contains this import:
import format from 'date-fns/format';
This is a directive to import the format function from the node package date-fns.
The related package.json
file could contain something like this:
"scripts": {
"start": "node app.js",
"build-server-file": "babel app_es6.js --out-file app.js",
"webpack": "webpack"
}
The related .babelrc
file could be something like this:
{
"presets": [
[
"env",
{
"targets":
{
"node": "current"
}
}
]
]
}
This build-server-file
script defined in the package.json
file is a directive for babel to parse the app_es6.js
file and output the file app.js
.
After running the build-server-file
script, if you open app.js
and look for the date-fns
import, you will see it has been converted into this:
var _format = require("date-fns/format");
var _format2 = _interopRequireDefault(_format);
Most of that file is gobbledygook to most humans, however computers understand it.
Also for reference, as an example of how a module can be created and imported into your project, if you install date-fns
and then open node_modules/date-fns/get_year/index.js
you can see it contains:
var parse = require('../parse/index.js')
function getYear (dirtyDate) {
var date = parse(dirtyDate)
var year = date.getFullYear()
return year
}
module.exports = getYear
Using the babel process above, your app_es6.js
file could then contain:
import getYear from 'date-fns/get_year';
// Which year is 2 July 2014?
var result = getYear(new Date(2014, 6, 2))
//=> 2014
And babel would convert the imports to:
var _get_year = require("date-fns/get_year");
var _get_year2 = _interopRequireDefault(_get_year);
And handle all references to the function accordingly.
I had the same problem. In order to modify variables from different classes, I made them extend the class they were to modify. I also made the super class's variables static so they can be changed by anything that inherits them. I also made them protected for more flexibility.
Source: Bad experiences. Good lessons.
I won't stress much on the difference as it is already covered, but notice the below:
android:backgroundTint
android:backgroundTintMode
are only available at API 21android:background
, and you want to change its default color, then you can use android:backgroundTint
to add a shade to it.example
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:background="@android:drawable/ic_dialog_email" />
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:background="@android:drawable/ic_dialog_email"
android:backgroundTint="@color/colorAccent" />
Another example
If you try to change the accent color of the FloatingActionButton
using android:background
you won't notice a change, that is because it's already utilizes app:srcCompat
, so in order to do that you can use android:backgroundTint
instead
In Spring Boot 2.2.x
you need to configure it like this:
@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
return builder.build()
}
Kotlin:
@Bean
fun objectMapper(builder: Jackson2ObjectMapperBuilder) = builder.build()
Following is correct way:
xmlhttp.open("GET","getuser.php?fname="+abc ,true);
Prior to HTML5, input type="text" simply means a field to insert free text, regardless of what you want it be. that is the job of validations you would have to do in order to guarantee the user enters a valid number
If you're using HTML5, you can use the new input types, one of which is number that automatically validates the text input, and forces it to be a number
keep in mind though, that if you're building a server side app (php for example) you will still have to validate the input on that side (make sure it is really a number) since it's pretty easy to hack the html and change the input type, removing the browser validation
Struggled to find this as well.
Heres a screenshot of how to do it:
If you use
ssh [email protected] "~/tools/run_pvt.pl $BUILD_NUMBER"
instead of
ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'
your shell will interpolate the $BUILD_NUMBER
before sending the command string to the remote host.
There are other ways to achieve this here: (Plot correlation matrix into a graph), but I like your version with the correlations in the boxes. Is there a way to add the variable names to the x and y column instead of just those index numbers? For me, that would make this a perfect solution. Thanks!
edit: I was trying to comment on the post by [Marc in the box], but I clearly don't know what I'm doing. However, I did manage to answer this question for myself.
if d is the matrix (or the original data frame) and the column names are what you want, then the following works:
axis(1, 1:dim(d)[2], colnames(d), las=2)
axis(2, 1:dim(d)[2], colnames(d), las=2)
las=0 would flip the names back to their normal position, mine were long, so I used las=2 to make them perpendicular to the axis.
edit2: to suppress the image() function printing numbers on the grid (otherwise they overlap your variable labels), add xaxt='n', e.g.:
image(x=seq(dim(x)[2]), y=seq(dim(y)[2]), z=COR, col=rev(heat.colors(20)), xlab="x column", ylab="y column", xaxt='n')
I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.
(function() {
var lastText = '';
$('#MyTextBox'), {
source: MyData
})
.on('autocompleteselect autocompletefocus', function(ev, ui) {
lastText = ui.item.label;
jqTag.data('autocomplete-item', ui.item);
})
.keyup(function(ev) {
if (lastText != jqTag.val()) {
// Clear when they stop typing
jqTag.data('autocomplete-item', null);
// Pass the event on as autocompleteclear so callers can listen for select/clear
var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
return jqTag.trigger(clearEv);
});
})();
With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.
Dang this is hard. Here is what I did to reject/delete/replace my ios build before it was released. The app was approved how ever I found found a bug I wanted to fix before releasing
To replace the bad build I did the following
I had the a similar problem and want to share my solution here.
I have the following HTML:
<div data-my-directive>
<div id='sub' ng-include='includedFile.htm'></div>
</div>
Problem: In the link-function of directive of the parent div I wanted to jquery'ing the child div#sub. But it just gave me an empty object because ng-include hadn't finished when link function of directive ran. So first I made a dirty workaround with $timeout, which worked but the delay-parameter depended on client speed (nobody likes that).
Works but dirty:
app.directive('myDirective', [function () {
var directive = {};
directive.link = function (scope, element, attrs) {
$timeout(function() {
//very dirty cause of client-depending varying delay time
$('#sub').css(/*whatever*/);
}, 350);
};
return directive;
}]);
Here's the clean solution:
app.directive('myDirective', [function () {
var directive = {};
directive.link = function (scope, element, attrs) {
scope.$on('$includeContentLoaded', function() {
//just happens in the moment when ng-included finished
$('#sub').css(/*whatever*/);
};
};
return directive;
}]);
Maybe it helps somebody.
I was confused about what 'add' really does. I just read a very enlightening paragraph from the book Git Pro that I'd like to add here, because it clarifies things
“It turns out that Git stages a file exactly as it is when you run the git add command. If you commit now, the version of benchmarks.rb as it was when you last ran the git add command is how it will go into the commit, not the version of the file as it looks in your working directory when you run git commit. If you modify a file after you run git add, you have to run git add again to stage the latest version of the file:”
Excerpt From: Chacon, Scott. “Pro Git.” Springer, 2009-08-19T00:00:00+00:00. iBooks. This material may be protected by copyright.