At last I managed to achieve what I intended with all your help and the post Change a link style onclick. Here is the code for that. I used JavaScript for doing this.
<html>
<head>
<style type="text/css">
.item {
width:900px;
padding:0;
margin:0;
list-style-type:none;
}
a {
display:block;
width:60;
line-height:25px; /*24px*/
border-bottom:1px none #808080;
font-family:'arial narrow',sans-serif;
color:#00F;
text-align:center;
text-decoration:none;
background:#CCC;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
margin-bottom:0em;
padding: 0px;
}
a.item {
float:left; /* For horizontal left to right display. */
width:145px; /* For maintaining equal */
margin-right: 5px; /* space between two boxes. */
}
a.selected{
background:orange;
color:white;
}
</style>
</head>
<body>
<a class="item" href="#" >item 1</a>
<a class="item" href="#" >item 2</a>
<a class="item" href="#" >item 3</a>
<a class="item" href="#" >item 4</a>
<a class="item" href="#" >item 5</a>
<a class="item" href="#" >item 6</a>
<script>
var anchorArr=document.getElementsByTagName("a");
var prevA="";
for(var i=0;i<anchorArr.length;i++)
{
anchorArr[i].onclick = function(){
if(prevA!="" && prevA!=this)
{
prevA.className="item";
}
this.className="item selected";
prevA=this;
}
}
</script>
</body>
</html>
A funny way to do this is
>>> np.array([True, False, False]) + 0
np.array([1, 0, 0])
For this you have two choices:
exe
converter. I recommend pyinstaller
as it seems to have the best results. The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.
Sort of. As Bobby says:
svn co file:///.../trunk/foo file:///.../trunk/bar file:///.../trunk/hum
will get the folders, but you will get separate folders from a subversion perspective. You will have to go separate commits and updates on each subfolder.
I don't believe you can checkout a partial tree and then work with the partial tree as a single entity.
!! Outdated answer, since CSS3 brought this feature
Is there a way to position a background image a certain number of pixels from the right of its element?
Nope.
Popular workarounds include
margin-right
on the element insteadtop right
String toAdd = "toAdd";
StringBuilder s = new StringBuilder();
for(int count = 0; count < MAX; count++) {
s.append(toAdd);
}
String output = s.toString();
I admit that my approach escapes the whole "Code First" concept. But if you have the ability to just change the default value in the table itself... it's much simpler than the lengths that you have to go through above... I'm just too lazy to do all that work!
It almost seems as if the posters original idea would work:
[DefaultValue(true)]
public bool IsAdmin { get; set; }
I thought they just made the mistake of adding quotes... but alas no such intuitiveness. The other suggestions were just too much for me (granted I have the privileges needed to go into the table and make the changes... where not every developer will in every situation). In the end I just did it the old fashioned way. I set the default value in the SQL Server table... I mean really, enough already! NOTE: I further tested doing an add-migration and update-database and the changes stuck.
This seems to work:
def sanitize_utf8(string)
return nil if string.nil?
return string if string.valid_encoding?
string.chars.select { |c| c.valid_encoding? }.join
end
You should be able to use the /quiet
or /qn
options with msiexec
to perform a silent install.
MSI packages export public properties, which you can set with the PROPERTY=value
syntax on the end of the msiexec
parameters.
For example, this command installs a package with no UI and no reboot, with a log and two properties:
msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2
You can read the options for msiexec
by just running it with no options from Start -> Run.
This one works better if you don't have the python on path or want to specify the directory :
//for Windows
npm config set python C:\Python27\python.exe
//for Linux
npm config set python /usr/bin/python27
I would rather use Matchers.<byte[]>any()
. This worked for me.
Yes You Can!
I worked on a project that did that (see comment). Unfortunately no code samples from that one, but googling revealed these:
How you can integrate data from several Web services using Excel and VBA
STEP BY STEP: Consuming Web Services through VBA (Excel or Word)
This answer is to give a better understanding of this warning
Deprecation warning is caused when you use moment to create time object, var today = moment();
.
If this warning is okay with you then I have a simpler method.
Don't use date
object from js
use moment
instead. For example use moment()
to get the current date.
Or convert the js
date object to moment
date. You can simply do that specifying the format of your js
date object.
ie, moment("js date", "js date format");
eg:
moment("2014 04 25", "YYYY MM DD");
(BUT YOU CAN ONLY USE THIS METHOD UNTIL IT'S DEPRECIATED, this may be depreciated from moment
in the future)
Never mind, I found the answer.
This will do the trick.
Dim colIndex As Long
colIndex = Application.Match(colName, Range(Cells(rowIndex, 1), Cells(rowIndex, 100)), 0)
**to scroll up to desired height. I have come up with some good solution **
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.scrollBy(0, childView.getHeight());
}
}, 100);
Use the getTime
method to get the time in total milliseconds since 1970-01-01, and subtract those:
var time = new Date().getTime() - new Date("2013-02-20T12:01:04.753Z").getTime();
Create in your Site.css (or in another place) a new class named for example .font-bold and set it to your element
.font-bold {
font-weight: bold;
}
You can paste the lines in from a text editor that uses UNIX-style line endings (CR+LF). I use Notepad++. First go to Settings/Preferences/New Document and change the format from Windows to Unix. Then open a new document, type in your lines, and copy them into SSMS.
I think the lightsail as the name suggest is light weight and meant for initial development. For production sites and apps with high volume it simply becomes unavailable and hangs....It is just a sandbox to play with things. Further lack of support reduces its reliability. There should be an option to migrate to EC2, when u fully develop your apps or sites..So that with same minimum configuration you can migrate to scalable EC2..
Since PostgreSQL 10
CREATE TABLE test_new (
id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
payload text
);
Multiple exit is good if you manage it well
The first step is to specify the reasons of exit. Mine is usually something like this:
1. No need to execute the function
2. Error is found
3. Early completion
4. Normal completion
I suppose you can group "1. No need to execute the function" into "3. Early completion" (a very early completion if you will).
The second step is to let the world outside the function know the reason of exit. The pseudo-code looks something like this:
function foo (input, output, exit_status)
exit_status == UNDEFINED
if (check_the_need_to_execute == false) then
exit_status = NO_NEED_TO_EXECUTE // reason #1
exit
useful_work
if (error_is_found == true) then
exit_status = ERROR // reason #2
exit
if (need_to_go_further == false) then
exit_status = EARLY_COMPLETION // reason #3
exit
more_work
if (error_is_found == true) then
exit_status = ERROR
else
exit_status = NORMAL_COMPLETION // reason #4
end function
Obviously, if it's beneficial to move a lump of work in the illustration above into a separate function, you should do so.
If you want to, you can be more specific with the exit status, say, with several error codes and early completion codes to pinpoint the reason (or even the location) of exit.
Even if you force this function into one that has only a single exit, I think you still need to specify exit status anyway. The caller needs to know whether it's OK to use the output, and it helps maintenance.
If you are using the source command on Windows remember to use f:/myfolder/mysubfolder/file.sql
and not f:\myfolder\mysubfolder\file.sql
I'm from Oracle env and I would do it like this in Oracle:
select * from table
where trunc(somedatefield, 'MONTH') =
trunc(sysdate -INTERVAL '0-1' YEAR TO MONTH, 'MONTH')
Idea: I'm running a scheduled report of previous month (from day 1 to the last day of the month, not windowed). This could be index unfriendly, but Oracle has fast date handling anyways. Is there a similar simple and short way in MS SQL? The answer comparing year and month separately seems silly to Oracle folks.
=IIf((CountRows("ScannerStatisticsData")=0),False,True)
Should be replaced with
=IIf((CountRows("ScannerStatisticsData")=0),True,False)
because the Visibility expression set up the Hidden value.
you need to cast int to str before concatenating. for that use str(temperature)
. Or you can print the same output using ,
if you don't want to convert like this.
print("the furnace is now",temperature , "degrees!")
I added these aliases to my ~/.bashrc:
alias pushall='for i in `git remote`; do git push $i; done;'
alias pullall='for i in `git remote`; do git pull $i; done;'
It looks like your 'trainData' is a list of strings:
['-214' '-153' '-58' ..., '36' '191' '-37']
Change your 'trainData' to a numeric type.
import numpy as np
np.array(['1','2','3']).astype(np.float)
I think this should do the trick:
<table border="1px" align="center">
According to http://w3schools.com/tags/tag_table.asp this is deprecated, but try it. If it does not work, go for styles, as mentioned on the site.
if you have zsh installed you can also update ~/.zprofile
with
if [[ -z "$LC_ALL" ]]; then
export LC_ALL='en_US.UTF-8'
fi
and check the output using the locale
cmd as show above
? locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
I would suggest you to use Glide library. To use Glide you need to add this to add these dependencies
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support:support-v4:23.4.0'
to your grandle (Module:app) file.
Then use this line of code to load your gif image
Glide.with(context).load(R.drawable.loading).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).crossFade().into(loadingImageView);
See Python's document on sharing global variables across modules:
The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).
config.py:
x = 0 # Default value of the 'x' configuration setting
Import the config module in all modules of your application; the module then becomes available as a global name.
main.py:
import config print (config.x)
or
from config import x print (x)
In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.
Try putting this into the top of your file (before any other output):
<?php
header('Content-Type: text/html; charset=UTF-8');
?>
With Windows 10 / Powershell ctrl + c did not work; Powershell tried to gracefully stop the app.
Used normal cmd and had no issues stopping the ng serve with ctrl + c.
For c++ use std::array<int/*type*/, 10/*size*/>
instead of c-style array. This is available with c++11 standard, and which is a good practice. See it here for standard and examples. If you want to stick to old c-style arrays for reasons, there two possible ways:
int *a = new int[5]();
Here leave the parenthesis empty, otherwise it will give compile error. This will initialize all the elements in the allocated array. Here if you don't use the parenthesis, it will still initialize the integer values with zeros because new will call the constructor, which is in this case int()
.int *a = new int[5] {0, 0, 0};
This is allowed in c++11 standard. Here you can initialize array elements with any value you want. Here make sure your initializer list(values in {}) size should not be greater than your array size. Initializer list size less than array size is fine. Remaining values in array will be initialized with 0.This is how managed to change my data table row background (DataTables 1.10.19)
$('#memberList').DataTable({
"processing": true,
"serverSide": true,
"pageLength":25,
"ajax":{
"dataType": "json",
"type": "POST",
"url": mainUrl+"/getMember",
},
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "email" },
{ "data": "phone" },
{ "data": "country_id" },
{ "data": "created_at" },
{ "data": "action" },
],
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
switch(aData['country_id']){
case 1:
$('td', nRow).css('background-color', '#dacfcf')
break;
}
}
});
You can use fnRowCallback
method function to change the background.
If you are in office intranet (otherwise dangerous) which is always protected by firewalls simply have the following lines in your ~/.ssh/config
.
Host *
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
.... but how do we find the equivalent class in the second List to pass to the method below;
This is your actual problem; you must have at least one immutable property, a id or something like that, to identify corresponding objects in both lists. If you do not have such a property you, cannot solve the problem without errors. You can just try to guess corresponding objects by searching for minimal or logical changes.
If you have such an property, the solution becomes really simple.
Enumerable.Join(
listA, listB,
a => a.Id, b => b.Id,
(a, b) => CompareTwoClass_ReturnDifferences(a, b))
thanks to you both danbruc and Noldorin for your feedback. both Lists will be the same length and in the same order. so the method above is close, but can you modify this method to pass the enum.Current to the method i posted above?
Now I am confused ... what is the problem with that? Why not just the following?
for (Int32 i = 0; i < Math.Min(listA.Count, listB.Count); i++)
{
yield return CompareTwoClass_ReturnDifferences(listA[i], listB[i]);
}
The Math.Min() call may even be left out if equal length is guaranted.
Noldorin's implementation is of course smarter because of the delegate and the use of enumerators instead of using ICollection.
My 2 cents:
using (ZipArchive archive = ZipFile.Open(zFile, ZipArchiveMode.Create))
{
foreach (var fPath in filePaths)
{
archive.CreateEntryFromFile(fPath,Path.GetFileName(fPath));
}
}
So Zip files could be created directly from files/dirs.
org.eclipse.m2e.core.prefs file is in .settings folder. If you face the problem of
An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException
Delete the project from eclipse then by deleting the .settings folder & .project file in the project -> then re-import the project.
You can push your local branch to a new remote branch like so:
git push origin master:test
(Assuming origin
is your remote, master
is your local branch name and test
is the name of the new remote branch, you wish to create.)
If at the same time you want to set up your local branch to track the newly created remote branch, you can do so with -u
(on newer versions of Git) or --set-upstream
, so:
git push -u origin master:test
or
git push --set-upstream origin master:test
...will create a new remote branch, named test
, in remote repository origin
, based on your local master
, and setup your local master
to track it.
Use Below code:
private void getCallDeatils() {
StringBuffer stringBuffer = new StringBuffer();
Cursor managedCursor = getActivity().managedQuery(CallLog.Calls.CONTENT_URI, null, null, null, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
stringBuffer.append("Call Deatils");
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String reportDate = df.format(callDayTime);
String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
stringBuffer.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- " + dir + " \nCall Date:--- " +callDate + " \nCall duration in sec :--- " + callDuration);
stringBuffer.append("\n----------------------------------");
logs.add(new LogClass(phNumber,dir,reportDate,callDuration));
}
Installing git and running npm install from git-bash worked for me. Make sure you are in the correct directory.
For a lambda-avoiding method, first define your own function:
def MyFn(a):
return a[1]
then:
sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=MyFn)
Used this approach for array of bytes:
Initially:
byte[] bytes = new byte[0];
Whenever required (Need to provide original length for extending):
Array.Resize<byte>(ref bytes, bytes.Length + requiredSize);
Reset:
Array.Resize<byte>(ref bytes, 0);
Typed List Method
Initially:
List<byte> bytes = new List<byte>();
Whenever required:
bytes.AddRange(new byte[length]);
Release/Clear:
bytes.Clear()
I've always used .place()
for my tkinter widgets.
place syntax
You can specify the size of it just by changing the keyword arguments!
Of course, you will have to call .place()
again if you want to change it.
Works in python 3.8.2, if you're wondering.
You simply need to make cab
a string:
cab = '6176'
As the error message states, you cannot do <int> in <string>
:
>>> 1 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>>
because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").
In fact, Python only allows you to use the in
operator with a right operand of type string if the left operand is also of type string:
>>> '1' in '123' # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>
use net stop mysql57 instead, it should be the version that is not specified
Like this:
import operator
l = [...]
sorted_list = sorted(l, key=operator.itemgetter(desired_item_index))
Just for anybody who is interested. I was working on an iOS project that required similar functionality so I ended porting the answer by @jeznag to swift
private func addMinutesToDate(minutes: Int, beforeDate: NSDate) -> NSDate {
var SIXTY_SECONDS = 60
var m = (Double) (minutes * SIXTY_SECONDS)
var c = beforeDate.timeIntervalSince1970 + m
var newDate = NSDate(timeIntervalSince1970: c)
return newDate
}
Have you added this gem to your gemfile?
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
move that gem out of assets group and then run bundle again, I hope that would help!
Why extend jQuery? What would be the benefit of extending jQuery vs just having a global function?
function qs(key) {
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}
http://jsfiddle.net/gilly3/sgxcL/
An alternative approach would be to parse the entire query string and store the values in an object for later use. This approach doesn't require a regular expression and extends the window.location
object (but, could just as easily use a global variable):
location.queryString = {};
location.search.substr(1).split("&").forEach(function (pair) {
if (pair === "") return;
var parts = pair.split("=");
location.queryString[parts[0]] = parts[1] &&
decodeURIComponent(parts[1].replace(/\+/g, " "));
});
http://jsfiddle.net/gilly3/YnCeu/
This version also makes use of Array.forEach()
, which is unavailable natively in IE7 and IE8. It can be added by using the implementation at MDN, or you can use jQuery's $.each()
instead.
Assuming, that you have root access on the box you can do:
sudo -u postgres psql
If that fails with a database "postgres" does not exists this block.
sudo -u postgres psql template1
Then sudo nano /etc/postgresql/11/main/pg_hba.conf file
local all postgres ident
For newer versions of PostgreSQL ident actually might be peer.
Inside the psql shell you can give the DB user postgres a password:
ALTER USER postgres PASSWORD 'newPassword';
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
This can be done with a linear layout too.
Just provide Height = 0dp and weight = 1 to the layout above and the one you want in the bottom. Just write height = wrap content and no weight.
It provides wrap content for the layout (the one that contains your edit text and button) and then the one that has weight occupies the rest of the layout.
I discovered this by accident.
$file = '../image.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
$img = file_get_contents($file);
echo $img;
This is works for me! I have test it on code igniter. if i use readfile, the image won't display. Sometimes only display jpg, sometimes only big file. But after i changed it to "file_get_contents" , I get the flavour, and works!! this is the screenshoot: Screenshot of "secure image" from database
use button array like this.it will create 3 dynamic buttons bcoz h variable has value of 3
private void button1_Click(object sender, EventArgs e)
{
int h =3;
Button[] buttonArray = new Button[8];
for (int i = 0; i <= h-1; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Size = new Size(20, 43);
buttonArray[i].Name= ""+i+"";
buttonArray[i].Click += button_Click;//function
buttonArray[i].Location = new Point(40, 20 + (i * 20));
panel1.Controls.Add(buttonArray[i]);
} }
This solution allows you to forget select element. Helpful when you do not have an id on select elements.
$("#first").select2()
.on("select2:select", function (e) {
var selected_element = $(e.currentTarget);
var select_val = selected_element.val();
});
Formatter class is also a good option. fmt.format("%.2f", variable); 2 here is showing how many decimals you want. You can change it to 4 for example. Don't forget to close the formatter.
private static int nJars, nCartons, totalOunces, OuncesTolbs, lbs;
public static void main(String[] args)
{
computeShippingCost();
}
public static void computeShippingCost()
{
System.out.print("Enter a number of jars: ");
Scanner kboard = new Scanner (System.in);
nJars = kboard.nextInt();
int nCartons = (nJars + 11) / 12;
int totalOunces = (nJars * 21) + (nCartons * 25);
int lbs = totalOunces / 16;
double shippingCost = ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0;
Formatter fmt = new Formatter();
fmt.format("%.2f", shippingCost);
System.out.print("$" + fmt);
fmt.close();
}
solve(c)
does give the correct inverse. The issue with your code is that you are using the wrong operator for matrix multiplication. You should use solve(c) %*% c
to invoke matrix multiplication in R.
R performs element by element multiplication when you invoke solve(c) * c
.
You can use Cell.Interior.Color
, I've used it to count the number of cells in a range that have a given background color (ie. matching my legend).
UIImage *img = [UIImage imageNamed:@"anyImageName"];
imageNamed:
Returns the image object associated with the specified filename.+ (UIImage *)imageNamed:(NSString *)name
Parameters
name
The name of the file. If this is the first time the image is being loaded, the method looks for an image with the specified name in the application’s main bundle.
Return Value
The image object for the specified file, or nil if the method could not find the specified image.Discussion
This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.
In Python 3 this is the default behavior, but if you aren't using that you can import division like so:
>>> from __future__ import division
>>> 144/314
0.4585987261146497
Alternatively you can cast one of the variables to a float when doing your division which will do the same thing
sum = 144
women_onboard = 314
proportion_womenclass3_survived = sum / float(np.size(women_onboard))
A simpler approach relies on redirection from the page LOGIN_REDIRECT_URL. The key thing to realize is that the user information is automatically included in the request.
Suppose:
LOGIN_REDIRECT_URL = '/profiles/home'
and you have configured a urlpattern:
(r'^profiles/home', home),
Then, all you need to write for the view home()
is:
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
@login_required
def home(request):
return HttpResponseRedirect(
reverse(NAME_OF_PROFILE_VIEW,
args=[request.user.username]))
where NAME_OF_PROFILE_VIEW
is the name of the callback that you are using. With django-profiles, NAME_OF_PROFILE_VIEW
can be 'profiles_profile_detail'.
History from Learn Python the Hard Way:
Python's original rendition of a class was broken in many serious ways. By the time this fault was recognized it was already too late, and they had to support it. In order to fix the problem, they needed some "new class" style so that the "old classes" would keep working but you can use the new more correct version.
They decided that they would use a word "object", lowercased, to be the "class" that you inherit from to make a class. It is confusing, but a class inherits from the class named "object" to make a class but it's not an object really its a class, but don't forget to inherit from object.
Also just to let you know what the difference between new-style classes and old-style classes is, it's that new-style classes always inherit from object
class or from another class that inherited from object
:
class NewStyle(object):
pass
Another example is:
class AnotherExampleOfNewStyle(NewStyle):
pass
While an old-style base class looks like this:
class OldStyle():
pass
And an old-style child class looks like this:
class OldStyleSubclass(OldStyle):
pass
You can see that an Old Style base class doesn't inherit from any other class, however, Old Style classes can, of course, inherit from one another. Inheriting from object guarantees that certain functionality is available in every Python class. New style classes were introduced in Python 2.2
In powershell :
$this_script_path = $(Get-Item $($MyInvocation.MyCommand.Path)).DirectoryName
$parent_folder = Split-Path $this_script_path -Leaf
Godaddy hosting it seems fixed on .htaccess
, myself it is working
RewriteRule ^(.*)$ index.php/$1 [L]
to
RewriteRule ^(.*)$ index.php?/$1 [QSA,L]
I find the solution in spring.io,like this:
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
I had a different scenario, but still landed on this answer.
I had imported my root project folder containing multiple Maven projects but also some other stuff used in this project.
IntelliJ recognised the Java files, but didn't resolve the Maven dependencies.
I fixed this by performing a right-click on each pom and then "Add as maven project"
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
One thing that caught me out and surprised me was, in an inherited project, the files it was referring to were referred to on a relative path outside of the project folder but yet existed in the project folder.
In solution explorer, single click each file with the error, bring up the Properties window (right-click, Properties), and ensure the "Relative Path" is just the file name (e.g. MyMissingFile.cpp
) if it is in the project folder. In my case it was set to: ..\..\Some Other Folder\MyMissingFile.cpp
.
paste()
is the way to go. As the previous posters pointed out, paste can do two things:
concatenate values into one "string", e.g.
> paste("Hello", "world", sep=" ")
[1] "Hello world"
where the argument sep
specifies the character(s) to be used between the arguments to concatenate,
or collapse character vectors
> x <- c("Hello", "World")
> x
[1] "Hello" "World"
> paste(x, collapse="--")
[1] "Hello--World"
where the argument collapse
specifies the character(s) to be used between the elements of the vector to be collapsed.
You can even combine both:
> paste(x, "and some more", sep="|-|", collapse="--")
[1] "Hello|-|and some more--World|-|and some more"
Hope this helps.
The message indicates that the last line of the file doesn't end with an End Of Line (EOL) character (linefeed (\n
) or carriage return+linefeed (\r\n
)). The original intention of this message was to warn you that the file may be incomplete; most datafiles have an EOL character as the very last character in the file.
The remedy is simple:
You can override the onBackPressed()
method in your activity and remove the call to super class.
@Override
public void onBackPressed() {
//remove call to the super class
//super.onBackPressed();
}
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
RenderPartial takes another parameter that is simply a ViewDataDictionary. You're almost there, just call it like this:
Html.RenderPartial(
"ProductImageForm",
image,
new ViewDataDictionary { { "index", index } }
);
Note that this will override the default ViewData that all your other Views have by default. If you are adding anything to ViewData, it will not be in this new dictionary that you're passing to your partial view.
import java.util.Date;
Date now = new Date();
Note that the Date object is mutable and if you want to do anything sophisticated, use jodatime.
If you are still struggling to find an answer, specially if you produced a file for the output, and you prefer a clear alternative:
echo "hi" | grep "use this hack to hide the oputut :) "
There are several problems here:
The newdata
argument of predict()
needs a predictor variable. You should thus pass it values for Coupon
, instead of Total
, which is the response variable in your model.
The predictor variable needs to be passed in as a named column in a data frame, so that
predict()
knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).
For this to work, your original call should pass df
in through the data
argument, rather than using it directly in your formula. (This way, the name of the column in newdata
will be able to match the name on the RHS of the formula).
With those changes incorporated, this will work:
model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")
If you're talking about automatic XML serialization of objects, check out Castor:
Castor is an Open Source data binding framework for Java[tm]. It's the shortest path between Java objects, XML documents and relational tables. Castor provides Java-to-XML binding, Java-to-SQL persistence, and more.
For me.. the problem was that the anchor needs a title, and that was missing!
put this command in your vimrc file
set ic
always do case insensitive search
If you are trying to get extra data in fragments then you can try using:
Place data using:
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER);
Get data using:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getArguments().getInt(ARG_SECTION_NUMBER);
getArguments().getString(ARG_SECTION_STRING);
getArguments().getBoolean(ARG_SECTION_BOOL);
getArguments().getChar(ARG_SECTION_CHAR);
getArguments().getByte(ARG_SECTION_DATA);
}
Just start it with a slash? This means root. As long as you're testing on a web server (e.g. localhost) and not a file system (e.g. C:) then that should be all you need to do.
Here's a bit of JavaScript and jQuery I threw together to wrap the first word of each paragraph with a <span>
tag.
$(function() {
$('#content p').each(function() {
var text = this.innerHTML;
var firstSpaceIndex = text.indexOf(" ");
if (firstSpaceIndex > 0) {
var substrBefore = text.substring(0,firstSpaceIndex);
var substrAfter = text.substring(firstSpaceIndex, text.length)
var newText = '<span class="firstWord">' + substrBefore + '</span>' + substrAfter;
this.innerHTML = newText;
} else {
this.innerHTML = '<span class="firstWord">' + text + '</span>';
}
});
});
You can then use CSS to create a style for .firstWord
.
It's not perfect, as it doesn't account for every type of whitespace; however, I'm sure it could accomplish what you're after with a few tweaks.
Keep in mind that this code will only execute after page load, so it may take a split second to see the effect.
git remote update && git status
Found this on the answer to Check if pull needed in Git
git remote update
to bring your remote refs up to date. Then you can do one of several things, such as:
git status -uno
will tell you whether the branch you are tracking is ahead, behind or has diverged. If it says nothing, the local and remote are the same.
git show-branch *master
will show you the commits in all of the branches whose names end in master (eg master and origin/master).If you use
-v
withgit remote update
you can see which branches got updated, so you don't really need any further commands.
; For Windows Users to back to temp directory
set backup
set backupdir=C:\WINDOWS\Temp
set backupskip=C:\WINDOWS\Temp\*
set directory=C:\WINDOWS\Temp
set writebackup
For a Dotted effect on a Canvas, set this attribute to the paint object :
paint.setPathEffect(new DashPathEffect(new float[] {0,30}, 0));
And change the value 30 as your render suits you : it represents the "distance" between each dots.
For newer android studio 3.0.0 and gradle update, this needed to be included in project level build.gradle file for android Gradle build tools and related dependencies since Google moved to its own maven repository.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
// NOTE: Do not place your application dependencies here; they belong
}
}
allprojects {
repositories {
jcenter()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Try to set date.timezone
in php.ini
file. Or you can manually set it using ini_set()
or date_default_timezone_set()
.
workaround solution for special case:
if the newline character is the last character (as is the case with most file inputs), then for any element in the collection you can index as follows:
foobar= foobar[:-1]
to slice out your newline character.
The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.
That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!
<style>
html, body {
height: 100%;
}
#tableContainer-1 {
height: 100%;
width: 100%;
display: table;
}
#tableContainer-2 {
vertical-align: middle;
display: table-cell;
height: 100%;
}
#myTable {
margin: 0 auto;
}
</style>
<div id="tableContainer-1">
<div id="tableContainer-2">
<table id="myTable" border>
<tr><td>Name</td><td>J W BUSH</td></tr>
<tr><td>Proficiency</td><td>PHP</td></tr>
<tr><td>Company</td><td>BLAH BLAH</td></tr>
</table>
</div>
</div>
Late to the party, but for anyone tasked with creating their own or wants to see how this would work, here's the function with an added bonus of rearranging the start-stop values based on the desired increment:
def RANGE(start, stop=None, increment=1):
if stop is None:
stop = start
start = 1
value_list = sorted([start, stop])
if increment == 0:
print('Error! Please enter nonzero increment value!')
else:
value_list = sorted([start, stop])
if increment < 0:
start = value_list[1]
stop = value_list[0]
while start >= stop:
worker = start
start += increment
yield worker
else:
start = value_list[0]
stop = value_list[1]
while start < stop:
worker = start
start += increment
yield worker
Negative increment:
for i in RANGE(1, 10, -1):
print(i)
Or, with start-stop reversed:
for i in RANGE(10, 1, -1):
print(i)
Output:
10
9
8
7
6
5
4
3
2
1
Regular increment:
for i in RANGE(1, 10):
print(i)
Output:
1
2
3
4
5
6
7
8
9
Zero increment:
for i in RANGE(1, 10, 0):
print(i)
Output:
'Error! Please enter nonzero increment value!'
This is all you need:
background-repeat: no-repeat;
You can set the datagridview
DataSource
to null
and rebind it again.
private void button1_Click(object sender, EventArgs e)
{
myAccesscon.ConnectionString = connectionString;
dataGridView.DataSource = null;
dataGridView.Update();
dataGridView.Refresh();
OleDbCommand cmd = new OleDbCommand(sql, myAccesscon);
myAccesscon.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable bookings = new DataTable();
da.Fill(bookings);
dataGridView.DataSource = bookings;
myAccesscon.Close();
}
If you are using AngularJS, and you are using Angular Bootstrap : https://angular-ui.github.io/bootstrap/
You can do this so nice like this :
HTML:
<nav id="header-navbar" class="navbar navbar-default" ng-class="{'navbar-fixed-top':scrollDown}" role="navigation" scroll-nav>
<div class="container-fluid top-header">
<!--- Rest of code --->
</div>
</nav>
CSS: (Note here I use padding as bigger nav to shrink without padding you can modify as you want)
nav.navbar {
-webkit-transition: all 0.4s ease;
transition: all 0.4s ease;
background-color: white;
margin-bottom: 0;
padding: 25px;
}
.navbar-fixed-top {
padding: 0;
}
And then add your directive
Directive: (Note you may need to change this.pageYOffset >= 50
from 50 to more or less to fulfill your needs)
angular.module('app')
.directive('scrollNav', function ($window) {
return function(scope, element, attrs) {
angular.element($window).bind("scroll", function() {
if (this.pageYOffset >= 50) {
scope.scrollDown = true;
} else {
scope.scrollDown = false;
}
scope.$apply();
});
};
});
This will do the job nicely, animated and cool way.
Try to use the following strategies in order to improve your app performance:
If your're looking to set the current datetime for a dateTime column (like i was when I googled), use this way
$table->dateTime('signed_when')->useCurrent();
Here it is:
[chr(i) for i in xrange(127)]
Singletons give you the ability to combine two bad traits in one class. That's wrong in pretty much every way.
A singleton gives you:
Number one is straightforward. Globals are generally bad. We should never make objects globally accessible unless we really need it.
Number two may sound like it makes sense, but let's think about it. When was the last time you **accidentally* created a new object instead of referencing an existing one? Since this is tagged C++, let's use an example from that language. Do you often accidentally write
std::ostream os;
os << "hello world\n";
When you intended to write
std::cout << "hello world\n";
Of course not. We don't need protection against this error, because that kind of error just doesn't happen. If it does, the correct response is to go home and sleep for 12-20 hours and hope you feel better.
If only one object is needed, simply create one instance. If one object should be globally accessible, make it a global. But that doesn't mean it should be impossible to create other instances of it.
The "only one instance is possible" constraint doesn't really protect us against likely bugs. But it does make our code very hard to refactor and maintain. Because quite often we find out later that we did need more than one instance. We do have more than one database, we do have more than one configuration object, we do want several loggers. Our unit tests may want to be able to create and recreate these objects every test, to take a common example.
So a singleton should be used if and only if, we need both the traits it offers: If we need global access (which is rare, because globals are generally discouraged) and we need to prevent anyone from ever creating more than one instance of a class (which sounds to me like a design issue). The only reason I can see for this is if creating two instances would corrupt our application state - probably because the class contains a number of static members or similar silliness. In which case the obvious answer is to fix that class. It shouldn't depend on being the only instance.
If you need global access to an object, make it a global, like std::cout
. But don't constrain the number of instances that can be created.
If you absolutely, positively need to constrain the number of instances of a class to just one, and there is no way that creating a second instance can ever be handled safely, then enforce that. But don't make it globally accessible as well.
If you do need both traits, then 1) make it a singleton, and 2) let me know what you need that for, because I'm having a hard time imagining such a case.
According to this page https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/Attributes.html it is only available if (Enabled only in a UIWebView with the allowsInlineMediaPlayback property set to YES.) I understand in Mobile Safari this is YES on iPad and NO on iPhone and iPod Touch.
There are a lot of good answers. The key is that you must set nestedScrollingEnabled
to false
. As mentioned above you can do it in java code:
mRecyclerView.setNestedScrollingEnabled(false);
But also you have an opportunity to set the same property in xml code (android:nestedScrollingEnabled="false"
):
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:nestedScrollingEnabled="false"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Are you sure you can't get access to request / session scope variables from a JSF page?
This is what I'm doing in our login page, using Spring Security:
<h:outputText
rendered="#{param.loginFailed == 1 and SPRING_SECURITY_LAST_EXCEPTION != null}">
<span class="msg-error">#{SPRING_SECURITY_LAST_EXCEPTION.message}</span>
</h:outputText>
Read http://chris-alexander.co.uk/on-engineering/dev/android-fragments-within-fragments/
article. fragment.isResumed() checking helps me in onDestroyView w/o using onSaveInstanceState method.
open Manifest and add attribute theme = "@style/Theme.AppCompat.Light.NoActionBar" to activity you want it without actionbar :
<application
...
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
...
</activity>
</application>
Maybe not very elegant, but it does the job:
exec(open("script.py").read())
To completely stop the rest of the script from running you can just do
exit; //In place of break. The rest of the code will not execute
Multiple inheritance is one of those things that generally causes more problems than it solves. In C++ it fits the pattern of giving you enough rope to hang yourself, but Java and C# have chosen to go the safer route of not giving you the option. The biggest problem is what to do if you inherit multiple classes that have a method with the same signature that the inheritee doesn't implement. Which class's method should it choose? Or should that not compile? There is generally another way to implement most things that doesn't rely on multiple inheritance.
Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:
1. First create a css class
<style type="text/css">
.scrollable{
overflow: auto;
width: 70px; /* adjust this width depending to amount of text to display */
height: 80px; /* adjust height depending on number of options to display */
border: 1px silver solid;
}
.scrollable select{
border: none;
}
</style>
2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.
<div class="scrollable">
<select size="6" multiple="multiple">
<option value="1" selected>option 1 The Long Option</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5 Another Longer than the Long Option ;)</option>
<option value="6">option 6</option>
</select>
</div>
As for second question - you can use Fiddler filters to set response X-Frame-Options
header manually to something like ALLOW-FROM *
. But, of course, this trick will work only for you - other users still won't be able to see iframe content(if they not do the same).
You did not assign the "linux" to the question but you mentioned "Linux top". And thus this might be helpful:
Use the small Linux tool threadcpu to identify the most cpu using threads. It calls jstack to get the thread name. And with "sort -n" in pipe you get the list of threads ordered by cpu usage.
More details can be found here: http://www.tuxad.com/blog/archives/2018/10/01/threadcpu_-_show_cpu_usage_of_threads/index.html
And if you still need more details then create a thread dump or run strace on the thread.
This should do the trick:
<?php
$product_meta = get_post_meta($post_id);
echo wp_get_attachment_image( $product_meta['_thumbnail_id'][0], 'full' );
?>
You can change the parameters according to your needs.
No, you can't achieve that without setting a fixed height (or using a script).
Here are 2 answers of mine, showing how to use a script to achieve something like that:
If you want to import a CSS file like that, just give the file itself a .php extension and import it anyway. It will work just fine :)
In Nexus 5, Go to Settings -> Google -> Security and uncheck "Scan device for Security threats" and "Improve harmful app detection".
Take a look at the domReady script that allows setting up of multiple functions to execute when the DOM has loaded. It's basically what the Dom ready does in many popular JavaScript libraries, but is lightweight and can be taken and added at the start of your external script file.
Example usage
// add reference to domReady script or place
// contents of script before here
function codeAddress() {
}
domReady(codeAddress);
Now you should be able to use the new proxy integration type for Lambda to automatically get the full request in standard shape, rather than configure mappings.
Under Window > Preferences, go to the Run/Debug > Console section, then you should see an option "Limit console output." You can unchecked this or change the number in the "Console buffer size (characters)" text box below. Do Unchecked.
This is for the Eclipse like Galileo, Kepler, Juno, Luna, Mars and Helios.
After implementing a classic pattern like
class Singleton {
private instance: Singleton;
private constructor() {}
public getInstance() {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
}
}
I realized it's pretty useless in case you want some other class to be a singleton too. It's not extendable. You have to write that singleton stuff for every class you want to be a singleton.
Decorators for the rescue.
@singleton
class MyClassThatIsSingletonToo {}
You can write decorator by yourself or take some from npm. I found this proxy-based implementation from @keenondrums/singleton package neat enough.
It all falls back to the definition of modulus: It is the remainder, for example, 7 mod 3 = 1. This because 7 = 3(2) + 1, in which 1 is the remainder.
To do this process on a simple calculator do the following: Take the dividend (7) and divide by the divisor (3), note the answer and discard all the decimals -> example 7/3 = 2.3333333, only worry about the 2. Now multiply this number by the divisor (3) and subtract the resulting number from the original dividend.
so 2*3 = 6, and 7 - 6 = 1, thus 1 is 7mod3
In your notification implementation, use a code like this:
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
...
Intent intent = new Intent(this, ExampleActivity.class);
intent.putExtra("EXTRA_KEY", "value");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
nBuilder.setContentIntent(pendingIntent);
...
To Get Intent extra values in the ExampleActivity, use the following code:
...
Intent intent = getIntent();
if(intent!=null) {
String extraKey = intent.getStringExtra("EXTRA_KEY");
}
...
VERY IMPORTANT NOTE: the Intent::putExtra() method is an Overloaded one. To get the extra key, you need to use Intent::get[Type]Extra() method.
Note: NOTIFICATION_ID and NOTIFICATION_CHANNEL_ID are an constants declared in ExampleActivity
You can configure patterns to hide files and folders from the explorer and searches.
File > Preferences > Settings
). This will open the setting screen.files:exclude
in the search at the top.node_modules/
then click OK. The pattern syntax is powerful. You can find pattern matching details under the Search Across Files topic. When you are done it should look something like this:
If you want to directly edit the settings file: For example to hide a top level node_modules folder in your workspace:
"files.exclude": {
"node_modules/": true
}
To hide all files that start with ._
such as ._.DS_Store
files found on OSX:
"files.exclude": {
"**/._*": true
}
You also have the ability to change Workspace Settings (Main menu: File > Preferences > Workspace Settings
). Workspace settings will create a .vscode/settings.json
file in your current workspace and will only be applied to that workspace. User Settings will be applied globally to any instance of VS Code you open, but they won't override Workspace Settings if present. Read more on customizing User and Workspace Settings.
No one here posted an answer with all of the correct CSS variations, so here it is:
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
sql server 2012
with
student as
(select sid,year from (
values (101,5),(102,5),(103,4),(104,3),(105,2),(106,1),(107,4)
) as student(sid,year)
)
select iif(year=5,sid,year) as myCol,* from student
myCol sid year
101 101 5
102 102 5
4 103 4
3 104 3
2 105 2
1 106 1
4 107 4
In C++11 you can:
#include <tuple>
std::tuple<int, int> divide(int dividend, int divisor) {
return std::make_tuple(dividend / divisor, dividend % divisor);
}
#include <iostream>
int main() {
using namespace std;
int quotient, remainder;
tie(quotient, remainder) = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
In C++17:
#include <tuple>
std::tuple<int, int> divide(int dividend, int divisor) {
return {dividend / divisor, dividend % divisor};
}
#include <iostream>
int main() {
using namespace std;
auto [quotient, remainder] = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
or with structs:
auto divide(int dividend, int divisor) {
struct result {int quotient; int remainder;};
return result {dividend / divisor, dividend % divisor};
}
#include <iostream>
int main() {
using namespace std;
auto result = divide(14, 3);
cout << result.quotient << ',' << result.remainder << endl;
// or
auto [quotient, remainder] = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
Change your data to that formats to use sqlite datetime formats.
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDDDDDDDD
SELECT * FROM test WHERE date BETWEEN '2011-01-11' AND '2011-08-11'
Some things that you should check:
Check the include folder in your version of VS (in "C:\Program Files\Microsoft Visual Studio xx.x\VC\include
" check for the file which you are including, iostream
, make sure it's there).
Check your projects Include Directories in <Project Name> >
Properties > Configuration Properties > VC++ Directories > Include
Directories
- (it should look like this: $(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;
)
Make sure that you selected the correct project for this code
(File > New > Project > Visual C++ > Win32 Console Application
)
Make sure that you don't have <iostream.h>
anywhere in your code files, VS doesn't support that (in the same project, check your other code files, .cpp and .h files for <iostream.h>
and remove it).
Make sure that you don't have more than one main()
function in your
project code files (in the same project, check your other code files, .cpp and .h files for the main()
function and remove it or replace it with another name).
Some things you could try building with:
using namespace std;
from your main()
function and put it
after the include directive.std::cout
without using namespace std;
.If you're using fs-extra, you can skip the JSON.stringify
part with the writeJson function:
const fsExtra = require('fs-extra');
fsExtra.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
console.log('success!')
})
.catch(err => {
console.error(err)
})
I would suggest adding stdout
and stderr
file in systemd service
file itself.
Referring : https://www.freedesktop.org/software/systemd/man/systemd.exec.html#StandardOutput=
As you have configured it should not like:
StandardOutput=/home/user/log1.log
StandardError=/home/user/log2.log
It should be:
StandardOutput=file:/home/user/log1.log
StandardError=file:/home/user/log2.log
This works when you don't want to restart the service again and again.
This will create a new file and does not append to the existing file.
Use Instead:
StandardOutput=append:/home/user/log1.log
StandardError=append:/home/user/log2.log
NOTE: Make sure you create the directory already. I guess it does not support to create a directory.
New Version queries have a different format
To reach a lat long by url use (e.g.)
This works for me:
class MyClass {
static MyEnum: { Value1; Value2; Value3; }
= {
Value1: "Value1",
Value2: "Value2",
Value3: "Value3"
};
}
or
module MyModule {
export var MyEnum: { Value1; Value2; Value3; }
= {
Value1: "Value1",
Value2: "Value2",
Value3: "Value3"
};
}
8)
Update: Shortly after posting this I discovered another way, but forgot to post an update (however, someone already did mentioned it above):
enum MyEnum {
value1 = <any>"value1 ",
value2 = <any>"value2 ",
value3 = <any>"value3 "
}
Remember this if all your Strings in the column do not have an underscore (...or else if null value will be the output):
SELECT COALESCE
(SUBSTR("STRING_COLUMN" , 0, INSTR("STRING_COLUMN", '_')-1),
"STRING_COLUMN")
AS OUTPUT FROM DUAL
The following is an example of using JDK7.
public class CopyFileVisitor extends SimpleFileVisitor<Path> {
private final Path targetPath;
private Path sourcePath = null;
public CopyFileVisitor(Path targetPath) {
this.targetPath = targetPath;
}
@Override
public FileVisitResult preVisitDirectory(final Path dir,
final BasicFileAttributes attrs) throws IOException {
if (sourcePath == null) {
sourcePath = dir;
} else {
Files.createDirectories(targetPath.resolve(sourcePath
.relativize(dir)));
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(final Path file,
final BasicFileAttributes attrs) throws IOException {
Files.copy(file,
targetPath.resolve(sourcePath.relativize(file)));
return FileVisitResult.CONTINUE;
}
}
To use the visitor do the following
Files.walkFileTree(sourcePath, new CopyFileVisitor(targetPath));
If you'd rather just inline everything (not too efficient if you use it often, but good for quickies)
final Path targetPath = // target
final Path sourcePath = // source
Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(final Path dir,
final BasicFileAttributes attrs) throws IOException {
Files.createDirectories(targetPath.resolve(sourcePath
.relativize(dir)));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(final Path file,
final BasicFileAttributes attrs) throws IOException {
Files.copy(file,
targetPath.resolve(sourcePath.relativize(file)));
return FileVisitResult.CONTINUE;
}
});
Your function is:
function data(){
$a = "abc";
$b = "def";
$c = "ghi";
return array($a, $b, $c);
}
It returns an array where position 0 is $a, position 1 is $b and position 2 is $c. You can therefore access $a by doing just this:
data()[0]
If you do $myvar = data()[0] and print $myvar, you will get "abc", which was the value assigned to $a inside the function.
NOTE: I intend to make this a "one stop post" where you can use the Correct
way to find the last row. This will also cover the best practices to follow when finding the last row. And hence I will keep on updating it whenever I come across a new scenario/information.
Some of the most common ways of finding last row which are highly unreliable and hence should never be used.
UsedRange
should NEVER be used to find the last cell which has data. It is highly unreliable. Try this experiment.
Type something in cell A5
. Now when you calculate the last row with any of the methods given below, it will give you 5. Now color the cell A10
red. If you now use the any of the below code, you will still get 5. If you use Usedrange.Rows.Count
what do you get? It won't be 5.
Here is a scenario to show how UsedRange
works.
xlDown
is equally unreliable.
Consider this code
lastrow = Range("A1").End(xlDown).Row
What would happen if there was only one cell (A1
) which had data? You will end up reaching the last row in the worksheet! It's like selecting cell A1
and then pressing End key and then pressing Down Arrow key. This will also give you unreliable results if there are blank cells in a range.
CountA
is also unreliable because it will give you incorrect result if there are blank cells in between.
And hence one should avoid the use of UsedRange
, xlDown
and CountA
to find the last cell.
To find the last Row in Col E use this
With Sheets("Sheet1")
LastRow = .Range("E" & .Rows.Count).End(xlUp).Row
End With
If you notice that we have a .
before Rows.Count
. We often chose to ignore that. See THIS question on the possible error that you may get. I always advise using .
before Rows.Count
and Columns.Count
. That question is a classic scenario where the code will fail because the Rows.Count
returns 65536
for Excel 2003 and earlier and 1048576
for Excel 2007 and later. Similarly Columns.Count
returns 256
and 16384
, respectively.
The above fact that Excel 2007+ has 1048576
rows also emphasizes on the fact that we should always declare the variable which will hold the row value as Long
instead of Integer
else you will get an Overflow
error.
Note that this approach will skip any hidden rows. Looking back at my screenshot above for column A, if row 8 were hidden, this approach would return 5
instead of 8
.
To find the Effective
last row in the sheet, use this. Notice the use of Application.WorksheetFunction.CountA(.Cells)
. This is required because if there are no cells with data in the worksheet then .Find
will give you Run Time Error 91: Object Variable or With block variable not set
With Sheets("Sheet1")
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastrow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lastrow = 1
End If
End With
The same principles apply, for example to get the last row in the third column of a table:
Sub FindLastRowInExcelTableColAandB()
Dim lastRow As Long
Dim ws As Worksheet, tbl as ListObject
Set ws = Sheets("Sheet1") 'Modify as needed
'Assuming the name of the table is "Table1", modify as needed
Set tbl = ws.ListObjects("Table1")
With tbl.ListColumns(3).Range
lastrow = .Find(What:="*", _
After:=.Cells(1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End With
End Sub
According to this article:
JavaScript is a scripting language developed by Netscape Communications designed for developing client and server Internet applications. Netscape Navigator is designed to interpret JavaScript embedded into Web pages. JavaScript is independent of Sun Microsystem's Java language.
Microsoft JScript is an open implementation of Netscape's JavaScript. JScript is a high-performance scripting language designed to create active online content for the World Wide Web. JScript allows developers to link and automate a wide variety of objects in Web pages, including ActiveX controls and Java programs. Microsoft Internet Explorer is designed to interpret JScript embedded into Web pages.
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
use
$(document).height()property and set to the div from script and set
overflow=auto
for scrolling
Below is the way to crop an image.
image_path: The path to the image to edit
coords: A tuple of x/y coordinates (x1, y1, x2, y2)[open the image in mspaint and check the "ruler" in view tab to see the coordinates]
saved_location: Path to save the cropped image
from PIL import Image
def crop(image_path, coords, saved_location:
image_obj = Image.open("Path of the image to be cropped")
cropped_image = image_obj.crop(coords)
cropped_image.save(saved_location)
cropped_image.show()
if __name__ == '__main__':
image = "image.jpg"
crop(image, (100, 210, 710,380 ), 'cropped.jpg')
If you're using VS Express 2015, just go to your control panel --> programs and features --> select vs 2015 --> click change, then in the VS Express installer select 'Modify' --> select Publishing tools, and finish. Once setup completes the changes you will be able to create your installer.
If you want to get all keys, ECMAScript 5 introduced Object.keys
. This is only supported by newer browsers but the MDC documentation provides an alternative implementation (which also uses for...in
btw):
if(!Object.keys) Object.keys = function(o){
if (o !== Object(o))
throw new TypeError('Object.keys called on non-object');
var ret=[],p;
for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
return ret;
}
Of course if you want both, key and value, then for...in
is the only reasonable solution.
the problem's actually caused by dependency. I spent whole the day to solve this prblm. Firstly, right click on project > Maven > add dependency
In "EnterGroupId, ArtifactId, or sha1...." box, type "org.springframework".
Then, from droped down list, expand "spring-web" list > Choose the newest version of jar file > Click OK.
Done!!!
It means exactly what it says. You're trying to insert a value into a column that has a FK constraint on it that doesn't match any values in the lookup table.
Use sort -n
or sort --numeric-sort
.
Have you tried using a icon font like http://fortawesome.github.io/Font-Awesome/
Bootstrap comes with their own library, but it doesn't have as many icons as Font Awesome.
I setup my git
to autorebase on a git checkout
# in my ~/.gitconfig file
[branch]
autosetupmerge = always
autosetuprebase = always
Otherwise, it automatically merges when you switch between branches, which I think is the worst possible choice as the default.
However, this has a side effect, when I switch to a branch and then git cherry-pick <commit-id>
I end up in this weird state every single time it has a conflict.
I actually have to abort the rebase
, but first I fix the conflict, git add /path/to/file
the file (another very strange way to resolve the conflict in this case?!), then do a git commit -i /path/to/file
. Now I can abort the rebase
:
git checkout <other-branch>
git cherry-pick <commit-id>
...edit-conflict(s)...
git add path/to/file
git commit -i path/to/file
git rebase --abort
git commit .
git push --force origin <other-branch>
The second git commit .
seems to come from the abort. I'll fix my answer if I find out that I should abort the rebase
sooner.
The --force
on the push is required if you skip other commits and both branches are not smooth (both are missing commits from the other).
First off, EC2 and Elastic Compute Cloud are the same thing.
Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.
EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n
number of instances.
Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.
For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.
In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.
Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/
Older version of Express use app.use(express.json())
or bodyParser.json()
read more about bodyParser middleware
On latest version of express we could simply use res.json()
const express = require('express'),
port = process.env.port || 3000,
app = express()
app.get('/', (req, res) => res.json({key: "value"}))
app.listen(port, () => console.log(`Server start at ${port}`))
Put the @optional
in front of methods or properties.
window.location = appurl;// fb://method/call..
!window.document.webkitHidden && setTimeout(function () {
setTimeout(function () {
window.location = weburl; // http://itunes.apple.com/..
}, 100);
}, 600);
document.webkitHidden
is to detect if your app is already invoked and current safari tab to going to the background, this code is from www.baidu.com
It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.
Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:
SQL> select * from dba_directories;
... and if not, create one
SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
SQL> grant all on directory DATA_PUMP_DIR to myuser; -- DBAs dont need this grant
Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:
$ expdp system/manager schemas=user1 dumpfile=user1.dpdmp
Or specifying a specific directory, add directory=<directory name>
:
C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR
With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:
$ exp system/manager owner=user1 file=user1.dmp
Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.
Example for American UTF8 (UNIX):
$ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
Windows uses SET, example using Japanese UTF8:
C:\> set NLS_LANG=Japanese_Japan.AL32UTF8
More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624
The listed return type of the method is Task<string>
. You're trying to return a string
. They are not the same, nor is there an implicit conversion from string to Task<string>
, hence the error.
You're likely confusing this with an async
method in which the return value is automatically wrapped in a Task
by the compiler. Currently that method is not an async method. You almost certainly meant to do this:
private async Task<string> methodAsync()
{
await Task.Delay(10000);
return "Hello";
}
There are two key changes. First, the method is marked as async
, which means the return type is wrapped in a Task
, making the method compile. Next, we don't want to do a blocking wait. As a general rule, when using the await
model always avoid blocking waits when you can. Task.Delay
is a task that will be completed after the specified number of milliseconds. By await
-ing that task we are effectively performing a non-blocking wait for that time (in actuality the remainder of the method is a continuation of that task).
If you prefer a 4.0 way of doing it, without using await
, you can do this:
private Task<string> methodAsync()
{
return Task.Delay(10000)
.ContinueWith(t => "Hello");
}
The first version will compile down to something that is more or less like this, but it will have some extra boilerplate code in their for supporting error handling and other functionality of await
we aren't leveraging here.
If your Thread.Sleep(10000)
is really meant to just be a placeholder for some long running method, as opposed to just a way of waiting for a while, then you'll need to ensure that the work is done in another thread, instead of the current context. The easiest way of doing that is through Task.Run
:
private Task<string> methodAsync()
{
return Task.Run(()=>
{
SomeLongRunningMethod();
return "Hello";
});
}
Or more likely:
private Task<string> methodAsync()
{
return Task.Run(()=>
{
return SomeLongRunningMethodThatReturnsAString();
});
}
Change return false;
to return true;
in longClickListener
You long click the button, if it returns true then it does the work. If it returns false then it does it's work and also calls the short click and then the onClick also works.
A stream is a continuous flow of liquid, air, or gas.
Java stream is a flow of data from a source into a destination. The source or destination can be a disk, memory, socket, or other programs. The data can be bytes, characters, or objects. The same applies for C# or C++ streams. A good metaphor for Java streams is water flowing from a tap into a bathtub and later into a drainage.
The data represents the static part of the stream; the read and write methods the dynamic part of the stream.
InputStream
represents a flow of data from the source, the OutputStream
represents a flow of data into the destination.
Finally, InputStream
and OutputStream
are abstractions over low-level access to data, such as C file pointers.
You can sort your array with random key
sorted(array, key = lambda x: random.random())
key only be read once so comparing item during sort still efficient.
but look like random.shuffle(array)
will be faster since it written in C
You can use this one it's for YYYY-MM-DD. It checks if it's a valid date and that the value is not NULL. It returns TRUE
if everythings check out to be correct or FALSE
if anything is invalid. It doesn't get easier then this!
function validateDate(date) {
var matches = /^(\d{4})[-\/](\d{2})[-\/](\d{2})$/.exec(date);
if (matches == null) return false;
var d = matches[3];
var m = matches[2] - 1;
var y = matches[1] ;
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
Be aware that months need to be subtracted like this: var m = matches[2] - 1;
else the new Date()
instance won't be properly made.
You can do it by using Flexbox which is a good technique these days.
For using Flexbox you should give display: flex;
and align-items: center;
to your parent or #outer
div element. The code should be like this:
#outer {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
}
_x000D_
<div id="outer">_x000D_
<div id="inner">Foo foo</div>_x000D_
</div>
_x000D_
This should center your child or #inner
div horizontally. But you can't actually see any changes. Because our #outer
div has no height or in other words, its height is set to auto, so it has the same height as all of its child elements. So after a little of visual styling, the result code should be like this:
#outer {_x000D_
height: 500px;_x000D_
display: flex;_x000D_
align-items: center;_x000D_
background-color: blue;_x000D_
}_x000D_
_x000D_
#inner {_x000D_
height: 100px;_x000D_
background: yellow;_x000D_
}
_x000D_
<div id="outer">_x000D_
<div id="inner">Foo foo</div>_x000D_
</div>
_x000D_
You can see #inner
div is now centered. Flexbox is the new method of positioning elements in horizontal or vertical stacks with CSS and it's got 96% of global browsers compatibility. So you are free to use it and if you want to find out more about Flexbox visit CSS-Tricks article. That is the best place to learn using Flexbox in my opinion.
You can achieve this by putting the alt
tag in the div
were your image will appear.
Example:
<div id="yourImage" alt="nameOfImage"></div>
As a general rule of thumb, I use 1 cm margins when producing pdfs. I work in the geospatial industry and produce pdf maps that reference a specific geographic scale. Therefore, I do not have the option to 'fit document to printable area,' because this would make the reference scale inaccurate. You must also realize that when you fit to printable area, you are fitting your already existing margins inside the printer margins, so you end up with double margins. Make your margins the right size and your documents will print perfectly. Many modern printers can print with margins less than 3 mm, so 1 cm as a general rule should be sufficient. However, if it is a high profile job, get the specs of the printer you will be printing with and ensure that your margins are adequate. All you need is the brand and model number and you can find spec sheets through a google search.
The most readable CSS-only solution would probably be to use the aria-expanded attribute. Remember that you'll need to add aria-expanded="false" to all collapse-elements as this is not set on load (only on first click).
<h2 data-toggle="collapse" href="#collapseId" aria-expanded="false">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="glyphicon glyphicon-chevron-down"></span> Title
</h2>
h2[aria-expanded="false"] span.glyphicon-chevron-down,
h2[aria-expanded="true"] span.glyphicon-chevron-right
{
display: none;
}
h2[aria-expanded="true"] span.glyphicon-chevron-down,
h2[aria-expanded="false"] span.glyphicon-chevron-right
{
display: inline;
}
Works with Bootstrap 3.x.
What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.
Why not do something like this:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.
Make sure to target x86 on your project in Visual Studio. This should fix your trouble.
Update PHP 7.4
Curly brace access syntax is deprecated since PHP 7.4
Update 2019
Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.
Simply iterate its using {}
Example:
$videos{0}->id
This way your object is not destroyed and you can easily iterate through object.
For PHP 5.6 and below use this
$videos{0}['id']
Both array() and the stdClass objects can be accessed using the
current()
key()
next()
prev()
reset()
end()
functions.
So, if your object looks like
object(stdClass)#19 (3) {
[0]=>
object(stdClass)#20 (22) {
["id"]=>
string(1) "123"
etc...
Then you can just do;
$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object
If you need the key for some reason, you can do;
reset($obj); //Ensure that we're at the first element
$key = key($obj);
Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4
2022 Update:
After PHP 7.4, using current()
, end()
, etc functions on objects is deprecated.
In newer versions of PHP, use the ArrayIterator class:
$objIterator = new ArrayIterator($obj);
$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object
$key = $objIterator->key(); // and gets the key
Basically, you need to catch the OperationCanceledException
and check the state of the cancellation token that was passed to SendAsync
(or GetAsync
, or whatever HttpClient
method you're using):
IsCancellationRequested
is true), it means the request really was canceledOf course, this isn't very convenient... it would be better to receive a TimeoutException
in case of timeout. I propose a solution here based on a custom HTTP message handler: Better timeout handling with HttpClient
Sure, Xcode->Preferences and turn on Show line numbers.
Two native solutions
performance.now
--> Call to ... took 6.414999981643632
milliseconds.console.time
--> Call to ... took 5.815
millisecondsThe difference between both is precision.
For usage and explanation read on.
Performance.now
(For microsecond precision use)
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
function doSomething(){
for(i=0;i<1000000;i++){var x = i*i;}
}
_x000D_
Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.
Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().
console.time
Example: (timeEnd
wrapped in setTimeout
for simulation)
console.time('Search page');
doSomething();
console.timeEnd('Search page');
function doSomething(){
for(i=0;i<1000000;i++){var x = i*i;}
}
_x000D_
You can change the Timer-Name for different operations.
If you're trying to hide upload img and show bandwidth img on bandwidth click and viceversa this would work
<script>
function show_img(id)
{
if(id=='bandwidth')
{
$("#upload").hide();
$("#bandwith").show();
}
else if(id=='upload')
{
$("#upload").show();
$("#bandwith").hide();
}
return false;
}
</script>
<a href="#" onclick="javascript:show_img('bandwidth');">Bandwidth</a>
<a href="#" onclick="javascript:show_img('upload');">Upload</a>
<p align="center">
<img src="/media/img/close.png" style="visibility: hidden;" id="bandwidth"/>
<img src="/media/img/close.png" style="visibility: hidden;" id="upload"/>
</p>
Include the type specifier in your format expression:
>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'
find
commandfind / -iname "*vimrc*" -type f 2>/dev/null
There are many answers already, but it can sometimes be useful to simply run a "find" for anything containing the name "vimrc".
The reason is that this will show you what files you actualy have available on the system currently, rather than what you might put on your system. (The information for which you would obtain from :version
as explained in other answers.)
On my system this produces
/usr/share/vim/vim82/vimrc_example.vim
/usr/share/vim/vim82/gvimrc_example.vim
/etc/vim/gvimrc
/etc/vim/vimrc
/etc/vim/vimrc.tiny
Which is quite useful because it tells us that there are 2 example files installed in the share directorys for both gvim and vim, and that there are also some system-wide config files below /etc/
.
On my system, I also have a file at ~/.vimrc
but this does not appear in this list because it is a link to another file, stored under ~/Linux-Config
. But you won't have this directory, it's specific to machines I use on my own network.
find
syntax usedExplanation:
/
(find works recursively)*vimrc*
which means any name with vimrc
(case insensitive) in it somewhere, can be preceeded or followed by anything or nothing (*
)/dev/null
otherwise the output is spammed with unreadable errors from /proc
Use et.setBackgroundResource(R.color.white);
Check out php-ip-2-country from code.google. The database they provide is updated daily, so it is not necessary to connect to an outside server for the check if you host your own SQL server. So using the code you would only have to type:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
if(!empty($ip)){
require('./phpip2country.class.php');
/**
* Newest data (SQL) avaliable on project website
* @link http://code.google.com/p/php-ip-2-country/
*/
$dbConfigArray = array(
'host' => 'localhost', //example host name
'port' => 3306, //3306 -default mysql port number
'dbName' => 'ip_to_country', //example db name
'dbUserName' => 'ip_to_country', //example user name
'dbUserPassword' => 'QrDB9Y8CKMdLDH8Q', //example user password
'tableName' => 'ip_to_country', //example table name
);
$phpIp2Country = new phpIp2Country($ip,$dbConfigArray);
$country = $phpIp2Country->getInfo(IP_COUNTRY_NAME);
echo $country;
?>
Example Code (from the resource)
<?
require('phpip2country.class.php');
$dbConfigArray = array(
'host' => 'localhost', //example host name
'port' => 3306, //3306 -default mysql port number
'dbName' => 'ip_to_country', //example db name
'dbUserName' => 'ip_to_country', //example user name
'dbUserPassword' => 'QrDB9Y8CKMdLDH8Q', //example user password
'tableName' => 'ip_to_country', //example table name
);
$phpIp2Country = new phpIp2Country('213.180.138.148',$dbConfigArray);
print_r($phpIp2Country->getInfo(IP_INFO));
?>
Output
Array
(
[IP_FROM] => 3585376256
[IP_TO] => 3585384447
[REGISTRY] => RIPE
[ASSIGNED] => 948758400
[CTRY] => PL
[CNTRY] => POL
[COUNTRY] => POLAND
[IP_STR] => 213.180.138.148
[IP_VALUE] => 3585378964
[IP_FROM_STR] => 127.255.255.255
[IP_TO_STR] => 127.255.255.255
)
Using a supposed name property as the map key:
for (Product p: productList) { s.put(p.getName(), p); }
Using refs
is not best practice because it reads the DOM directly, it's better to use React's state
instead. Also, your button doesn't change because the component is not re-rendered and stays in its initial state.
You can use setState
together with an onChange
event listener to render the component again every time the input field changes:
// Input field listens to change, updates React's state and re-renders the component.
<input onChange={e => this.setState({ value: e.target.value })} value={this.state.value} />
// Button is disabled when input state is empty.
<button disabled={!this.state.value} />
Here's a working example:
class AddItem extends React.Component {_x000D_
constructor() {_x000D_
super();_x000D_
this.state = { value: '' };_x000D_
this.onChange = this.onChange.bind(this);_x000D_
this.add = this.add.bind(this);_x000D_
}_x000D_
_x000D_
add() {_x000D_
this.props.onButtonClick(this.state.value);_x000D_
this.setState({ value: '' });_x000D_
}_x000D_
_x000D_
onChange(e) {_x000D_
this.setState({ value: e.target.value });_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div className="add-item">_x000D_
<input_x000D_
type="text"_x000D_
className="add-item__input"_x000D_
value={this.state.value}_x000D_
onChange={this.onChange}_x000D_
placeholder={this.props.placeholder}_x000D_
/>_x000D_
<button_x000D_
disabled={!this.state.value}_x000D_
className="add-item__button"_x000D_
onClick={this.add}_x000D_
>_x000D_
Add_x000D_
</button>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<AddItem placeholder="Value" onButtonClick={v => console.log(v)} />,_x000D_
document.getElementById('View')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id='View'></div>
_x000D_
You can use this commands:
docker exec -it yournamecontainer psql -U postgres -c "CREATE DATABASE mydatabase ENCODING 'LATIN1' TEMPLATE template0 LC_COLLATE 'C' LC_CTYPE 'C';"
docker exec -it yournamecontainer psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE postgres TO postgres;"
In Bootstrap 3, columns are specified using percentages. (In Bootstrap 2, this was only the case if a column/span was within a .row-fluid
element, but that's no longer necessary and that class no longer exists.) If you use a .container
, then @Michael is absolutely right that you'll be stuck with a fixed-width layout. However, you should be in good shape if you just avoid using a .container element.
<body>
<div class="row">
<div class="col-lg-4">...</div>
<div class="col-lg-8">...</div>
</div>
</body>
The margin for the body is already 0, so you should be able to get up right to the edge. (Columns still have a 15px padding on both sides, so you may have to account for that in your design, but this shouldn't stop you, and you can always customize this when you download Bootstrap.)
What exactly do you mean by "validation failure"? What are you validating? Are you referring to something like a syntax error (e.g. malformed XML)?
If that's the case, I'd say 400 Bad Request is probably the right thing, but without knowing what it is you're "validating", it's impossible to say.
Several problems here:
import java.util.Iterator
Map.Entry entry = (Map.Entry) iter.next();
then you need to use hm.entrySet().iterator()
, not hm.keySet().iterator()
. Either you iterate on the keys, or on the entries.In one line:
String niceFormattedJson = JsonWriter.formatJson(jsonString)
or
System.out.println(JsonWriter.formatJson(jsonString.toString()));
The json-io libray (https://github.com/jdereg/json-io) is a small (75K) library with no other dependencies than the JDK.
In addition to pretty-printing JSON, you can serialize Java objects (entire Java object graphs with cycles) to JSON, as well as read them in.
I found a customer matcher here: https://raw.github.com/gist/917903/92d7101f643e07896659f84609c117c4c279dfad/have_content_type.rb
Put it in spec/support/matchers/have_content_type.rb and make sure to load stuff from support with something like this in you spec/spec_helper.rb
Dir[Rails.root.join('spec/support/**/*.rb')].each {|f| require f}
Here is the code itself, just in case it disappeared from the given link.
RSpec::Matchers.define :have_content_type do |content_type|
CONTENT_HEADER_MATCHER = /^(.*?)(?:; charset=(.*))?$/
chain :with_charset do |charset|
@charset = charset
end
match do |response|
_, content, charset = *content_type_header.match(CONTENT_HEADER_MATCHER).to_a
if @charset
@charset == charset && content == content_type
else
content == content_type
end
end
failure_message_for_should do |response|
if @charset
"Content type #{content_type_header.inspect} should match #{content_type.inspect} with charset #{@charset}"
else
"Content type #{content_type_header.inspect} should match #{content_type.inspect}"
end
end
failure_message_for_should_not do |model|
if @charset
"Content type #{content_type_header.inspect} should not match #{content_type.inspect} with charset #{@charset}"
else
"Content type #{content_type_header.inspect} should not match #{content_type.inspect}"
end
end
def content_type_header
response.headers['Content-Type']
end
end
//get query¶ms in express
//etc. example.com/user/000000?sex=female
app.get('/user/:id', function(req, res) {
const query = req.query;// query = {sex:"female"}
const params = req.params; //params = {id:"000000"}
})
Here's my take on comments within package.json
/ bower.json
:
I have file package.json.js
that contains a script that exports the actual package.json
. Running the script overwrites the old package.json
and tells me what changes it made, perfect to help you keep track of automatic changes npm
made. That way I can even programmatically define what packages I want to use.
The latest Grunt task is here: https://gist.github.com/MarZab/72fa6b85bc9e71de5991
.list-wrap {
width: 355px;
height: 100%;
position: relative;
.list {
position: absolute;
top: 0;
bottom: 0;
overflow-y: auto;
width: 100%;
}
}
The onload will always be trigger, i slove this problem use try catch block.It will throw an exception when you try to get the contentDocument.
iframe.onload = function(){
var that = $(this)[0];
try{
that.contentDocument;
}
catch(err){
//TODO
}
}
For references and the future, one should read the doc here https://dev.mysql.com/doc/mysql-secure-deployment-guide/5.7/en/secure-deployment-password-validation.html
Then you should edit your mysqld.cnf
file, for instance :
vim /etc/mysql/mysql.conf.d/mysqld.cnf
Then, add in the [mysqld] part, the following :
plugin-load-add=validate_password.so
validate_password_policy=LOW
Basically, if you edit your default, it will looks like :
[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
plugin-load-add=validate_password.so
validate_password_policy=LOW
Then, you can restart:
systemctl restart mysql
If you forget the plugin-load-add=validate_password.so
part, you will it an error at restart.
Enjoy !
1) If the object is created via a pointer and that pointer is later deleted or given a new address to point to, does the object that it was pointing to call its destructor (assuming nothing else is pointing to it)?
It depends on the type of pointers. For example, smart pointers often delete their objects when they are deleted. Ordinary pointers do not. The same is true when a pointer is made to point to a different object. Some smart pointers will destroy the old object, or will destroy it if it has no more references. Ordinary pointers have no such smarts. They just hold an address and allow you to perform operations on the objects they point to by specifically doing so.
2) Following up on question 1, what defines when an object goes out of scope (not regarding to when an object leaves a given {block}). So, in other words, when is a destructor called on an object in a linked list?
That's up to the implementation of the linked list. Typical collections destroy all their contained objects when they are destroyed.
So, a linked list of pointers would typically destroy the pointers but not the objects they point to. (Which may be correct. They may be references by other pointers.) A linked list specifically designed to contain pointers, however, might delete the objects on its own destruction.
A linked list of smart pointers could automatically delete the objects when the pointers are deleted, or do so if they had no more references. It's all up to you to pick the pieces that do what you want.
3) Would you ever want to call a destructor manually?
Sure. One example would be if you want to replace an object with another object of the same type but don't want to free memory just to allocate it again. You can destroy the old object in place and construct a new one in place. (However, generally this is a bad idea.)
// pointer is destroyed because it goes out of scope,
// but not the object it pointed to. memory leak
if (1) {
Foo *myfoo = new Foo("foo");
}
// pointer is destroyed because it goes out of scope,
// object it points to is deleted. no memory leak
if(1) {
Foo *myfoo = new Foo("foo");
delete myfoo;
}
// no memory leak, object goes out of scope
if(1) {
Foo myfoo("foo");
}
I wasn't happy with AppCompat, so I wrote my own CardView and backported ripples. Here it's running on Galaxy S with Gingerbread, so it's definitely possible.
For more details check the source code.
if you want to use md5 encryptioon you can do it in your php script
$pass = $_GET['pass'];
$newPass = md5($pass)
and then insert it into the database that way, however MD5 is a one way encryption method and is near on impossible to decrypt without difficulty
#import "ViewController.h"
@interface ViewController ()
{
NSMutableArray *name;
}
@end
- (void)viewDidLoad
{
[super viewDidLoad];
name=[[NSMutableArray alloc]init];
[name addObject:@"ronak"];
[name addObject:@"vibha"];
[name addObject:@"shivani"];
[name addObject:@"nidhi"];
[name addObject:@"firdosh"];
[name addObject:@"himani"];
_tableview_outlet.delegate = self;
_tableview_outlet.dataSource = self;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [name count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [name objectAtIndex:indexPath.row];
return cell;
}
Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.
Having added a new view controller scene to your storyboard, you then have to:
Create a UIViewController
subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":
And then select a unique name for the new view controller subclass:
Specify this new subclass as the base class for the scene you just added to the storyboard.
Now hook up any IBOutlet
and IBAction
references for this new scene with the new view controller subclass.
It is better to use .Value2() instead of .Value(). This is faster and gives the exact value in the cell. For certain type of data, truncation can be observed when .Value() is used.
Collecting the best comments from Gene's answer, the best solution by far, is by using sponge
from moreutils.
sudo apt-get install moreutils
# The complete one-liner:
find ./ -iname '*.java' -type f -exec bash -c 'expand -t 4 "$0" | sponge "$0"' {} \;
Explanation:
./
is recursively searching from current directory-iname
is a case insensitive match (for both *.java
and *.JAVA
likes)type -f
finds only regular files (no directories, binaries or symlinks)-exec bash -c
execute following commands in a subshell for each file name, {}
expand -t 4
expands all TABs to 4 spacessponge
soak up standard input (from expand
) and write to a file (the same one)*. NOTE: * A simple file redirection (> "$0"
) won't work here because it would overwrite the file too soon.
Advantage: All original file permissions are retained and no intermediate tmp
files are used.
If you are using OS X systems, there is no service
commands. So you won't be able to execure sudo service mongod start
.
Check this answer https://unix.stackexchange.com/a/155746 for more help!
May be you want this (oop in javascript)
function box(color)
{
this.color=color;
}
var box1=new box('red');
var box2=new box('white');
As others have noted the call to .remove()
is asynchronous. We should all be aware nothing happens 'instantly', even if it is at the speed of light.
What you mean by 'instantly' is that the next line of code should be able to execute after the call to .remove()
. With asynchronous operations the next line may be when the data has been removed, it may not - it is totally down to chance and the amount of time that has elapsed.
.remove()
takes one parameter a callback function to help deal with this situation to perform operations after we know that the operation has been completed (with or without an error). .push()
takes two params, a value and a callback just like .remove()
.
Here is your example code with modifications:
ref = new Firebase("myfirebase.com")
ref.push({key:val}, function(error){
//do stuff after push completed
});
// deletes all data pushed so far
ref.remove(function(error){
//do stuff after removal
});
Use the :checked selector to determine the checkbox's state:
$('input[type=checkbox]').click(function() {
if($(this).is(':checked')) {
...
} else {
...
}
});
You may also try the following code with exception handling. Here you have a method removeLast(String s, int n)
(it is actually an modified version of masud.m's answer). You have to provide the String
s and how many char
you want to remove from the last to this removeLast(String s, int n)
function. If the number of char
s have to remove from the last is greater than the given String
length then it throws a StringIndexOutOfBoundException
with a custom message -
public String removeLast(String s, int n) throws StringIndexOutOfBoundsException{
int strLength = s.length();
if(n>strLength){
throw new StringIndexOutOfBoundsException("Number of character to remove from end is greater than the length of the string");
}
else if(null!=s && !s.isEmpty()){
s = s.substring(0, s.length()-n);
}
return s;
}
Try PHPMyAdmin which has some really nice visualisation and editing feature. I am pretty sure you can even export to exel from it.