Uncomment this line (in /conf/logging.properties
)
org.apache.jasper.compiler.TldLocationsCache.level = FINE
Work's for me in tomcat 7.0.53!
In AndroidManifest.xml -> inside the activity which you want to use, add the following:
android:theme="@style/Theme.AppCompat.Light.NoActionBar"
//this is for hiding action bar
and in MainActivity.java -> inside onCreate() method, add the following :
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//this is for hiding status bar
You have an extra -c
you need to get rid of:
psexec -u administrator -p force \\135.20.230.160 -s -d cmd.exe /c "C:\Amitra\bogus.bat"
If you are using Sql Management Studio, just start it as Administrator.
Right click->Run as Administrator
Try this, it worked for me in a similar case:-
$http.get("your api url", {
headers: {
'If-Modified-Since': '0',
"Pragma": "no-cache",
"Expires": -1,
"Cache-Control": "no-cache, no-store, must-revalidate"
}
})
Just type below command on your command prompt & it will bind all sql file into single sql file,
c:/xampp/mysql/bin/sql/ type *.sql > OneFile.sql;
The link you gave does actually describe the differences, but it's buried at the bottom of the page:
http://www.cplusplus.com/reference/cstdio/fopen/
Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.
The conversion could be to normalize \r\n
to \n
(or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.
This should help you.
Dim Ws As Worksheet
Set Ws = Sheets("Sheet-Name")
Dim tbl As ListObject
Set tbl = Ws.ListObjects("Table-Name")
Dim newrow As ListRow
Set newrow = tbl.ListRows.Add
With newrow
.Range(1, Ws.Range("Table-Name[Table-Column-Name]").Column) = "Your Data"
End With
Download the map file and the uncompressed version of jQuery.
Put them with the minified version:
Include minified version into your HTML:
Check in Google Chrome:
Get familiar with Debugging JavaScript
Using cin's >> operator will drop leading whitespace and stop input at the first trailing whitespace. To grab an entire line of input, including spaces, try cin.getline()
. To grab one character at a time, you can use cin.get()
.
Try placing $PATH at the end.
export PATH=/usr/local/git/bin:/usr/local/bin:$PATH
It is clear from the error.
The HtmlHelpers appended with "For" expects lambda expression as a parameter.
If you are passing the value directly, better use Normal one.
e.g.
Instead of TextboxFor(....) use Textbox()
syntax for TextboxFor will be like Html.TextBoxFor(m=>m.Property)
In your scenario you can use basic for loop, as it will give you index to use.
@for(int i=0;i<Model.Theme.Count;i++)
{
@Html.LabelFor(m=>m.Theme[i].name)
@for(int j=0;j<Model.Theme[i].Products.Count;j++) )
{
@Html.LabelFor(m=>m.Theme[i].Products[j].name)
@for(int k=0;k<Model.Theme[i].Products[j].Orders.Count;k++)
{
@Html.TextBoxFor(m=>Model.Theme[i].Products[j].Orders[k].Quantity)
@Html.TextAreaFor(m=>Model.Theme[i].Products[j].Orders[k].Note)
@Html.EditorFor(m=>Model.Theme[i].Products[j].Orders[k].DateRequestedDeliveryFor)
}
}
}
Perhaps using SIMILAR TO
would work ?
SELECT * from table WHERE column SIMILAR TO '(AAA|BBB|CCC)%';
conda
is both a command line tool, and a python package.
Miniconda installer = Python + conda
Anaconda installer = Python + conda
+ meta package anaconda
meta Python pkg anaconda
= about 160 Python pkgs for daily use in data science
Anaconda installer = Miniconda installer + conda install anaconda
conda
is a python manager and an environment manager, which makes it possible to
conda install flake8
conda create -n myenv python=3.6
Miniconda installer = Python + conda
conda
, the package manager and environment manager, is a Python package. So Python is installed. Cause conda distribute Python interpreter with its own libraries/dependencies but not the existing ones on your operating system, other minimal dependencies like openssl
, ncurses
, sqlite
, etc are installed as well.
Basically, Miniconda is just conda
and its minimal dependencies. And the environment where conda
is installed is the "base" environment, which is previously called "root" environment.
Anaconda installer = Python + conda
+ meta package anaconda
meta Python package anaconda
= about 160 Python pkgs for daily use in data science
Meta packages, are packages that do NOT contain actual softwares and simply depend on other packages to be installed.
Download an anaconda
meta package from Anaconda Cloud and extract the content from it. The actual 160+ packages to be installed are listed in info/recipe/meta.yaml
.
package:
name: anaconda
version: '2019.07'
build:
ignore_run_exports:
- '*'
number: '0'
pin_depends: strict
string: py36_0
requirements:
build:
- python 3.6.8 haf84260_0
is_meta_pkg:
- true
run:
- alabaster 0.7.12 py36_0
- anaconda-client 1.7.2 py36_0
- anaconda-project 0.8.3 py_0
# ...
- beautifulsoup4 4.7.1 py36_1
# ...
- curl 7.65.2 ha441bb4_0
# ...
- hdf5 1.10.4 hfa1e0ec_0
# ...
- ipykernel 5.1.1 py36h39e3cac_0
- ipython 7.6.1 py36h39e3cac_0
- ipython_genutils 0.2.0 py36h241746c_0
- ipywidgets 7.5.0 py_0
# ...
- jupyter 1.0.0 py36_7
- jupyter_client 5.3.1 py_0
- jupyter_console 6.0.0 py36_0
- jupyter_core 4.5.0 py_0
- jupyterlab 1.0.2 py36hf63ae98_0
- jupyterlab_server 1.0.0 py_0
# ...
- matplotlib 3.1.0 py36h54f8f79_0
# ...
- mkl 2019.4 233
- mkl-service 2.0.2 py36h1de35cc_0
- mkl_fft 1.0.12 py36h5e564d8_0
- mkl_random 1.0.2 py36h27c97d8_0
# ...
- nltk 3.4.4 py36_0
# ...
- numpy 1.16.4 py36hacdab7b_0
- numpy-base 1.16.4 py36h6575580_0
- numpydoc 0.9.1 py_0
# ...
- pandas 0.24.2 py36h0a44026_0
- pandoc 2.2.3.2 0
# ...
- pillow 6.1.0 py36hb68e598_0
# ...
- pyqt 5.9.2 py36h655552a_2
# ...
- qt 5.9.7 h468cd18_1
- qtawesome 0.5.7 py36_1
- qtconsole 4.5.1 py_0
- qtpy 1.8.0 py_0
# ...
- requests 2.22.0 py36_0
# ...
- sphinx 2.1.2 py_0
- sphinxcontrib 1.0 py36_1
- sphinxcontrib-applehelp 1.0.1 py_0
- sphinxcontrib-devhelp 1.0.1 py_0
- sphinxcontrib-htmlhelp 1.0.2 py_0
- sphinxcontrib-jsmath 1.0.1 py_0
- sphinxcontrib-qthelp 1.0.2 py_0
- sphinxcontrib-serializinghtml 1.1.3 py_0
- sphinxcontrib-websupport 1.1.2 py_0
- spyder 3.3.6 py36_0
- spyder-kernels 0.5.1 py36_0
# ...
The pre-installed packages from meta pkg anaconda
are mainly for web scraping and data science. Like requests
, beautifulsoup
, numpy
, nltk
, etc.
If you have a Miniconda installed, conda install anaconda
will make it same as an Anaconda installation, except that the installation folder names are different.
Miniconda2 v.s. Miniconda. Anaconda2 v.s. Anaconda.
2
means the bundled Python interpreter for conda
in the "base" environment is Python 2, but not Python 3.
Although BeautifulSoup supports the HTML parser by default If you want to use any other third-party Python parsers you need to install that external parser like(lxml).
soup_object= BeautifulSoup(markup,"html.parser") #Python HTML parser
But if you don't specified any parser as parameter you will get an warning that no parser specified.
soup_object= BeautifulSoup(markup) #Warnning
To use any other external parser you need to install it and then need to specify it. like
pip install lxml
soup_object= BeautifulSoup(markup,'lxml') # C dependent parser
External parser have c and python dependency which may have some advantage and disadvantage.
If you don't want to group, then use the following method:
db.collection.aggregate( [
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $count: 'count' }
] );
Copy from php.net sample for inclusive range:
$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-08-31' );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $date){
echo $date->format("Ymd") . "<br>";
}
Wikipedia is a decent source for this info.
To learn about static library files like .a read Static libarary
To learn about shared library files like .so read Library_(computing)#Shared_libraries On this page, there is also useful info in the File naming section.
To have newline in code you use _
Example:
Dim a As Integer
a = 500 _
+ 80 _
+ 90
MsgBox a
Not sure about how to have read.csv
interpret it properly, but you can use gsub
to replace ","
with ""
, and then convert the string to numeric
using as.numeric
:
y <- c("1,200","20,000","100","12,111")
as.numeric(gsub(",", "", y))
# [1] 1200 20000 100 12111
This was also answered previously on R-Help (and in Q2 here).
Alternatively, you can pre-process the file, for instance with sed
in unix.
I would do it the following way:
>>> x = np.array([[1,0,0], [0,2,0], [1,1,0]])
>>> x
array([[1, 0, 0],
[0, 2, 0],
[1, 1, 0]])
>>> np.nonzero(x)
(array([0, 1, 2, 2]), array([0, 1, 0, 1]))
# if you want it in coordinates
>>> x[np.nonzero(x)]
array([1, 2, 1, 1])
>>> np.transpose(np.nonzero(x))
array([[0, 0],
[1, 1],
[2, 0],
[2, 1])
dgg
will delete everything from your current line to the top of the file.
d
is the deletion command, and gg
is a movement command that says go to the top of the file, so when used together, it means delete from my current position to the top of the file.
Also
dG
will delete all lines at or below the current one
This solution worked for me.
<html>
<body>
<form method="post" action="#">
<input type="text" id="number_id"/>
<input type="submit" value="send"/>
</form>
<p id="message"></p>
<script>
var flt=document.getElementById("number_id").value;
if(isNaN(flt)==false && Number.isInteger(flt)==false)
{
document.getElementById("message").innerHTML="the number_id is a float ";
}
else
{
document.getElementById("message").innerHTML="the number_id is a Integer";
}
</script>
</body>
</html>
with Kotlin I execute this code:
requireContext().startActivity<YourTargetActivity>()
Try this,
.success { background-color: #ccffcc; float:left;}
I had similar issue when I had plenty of extra records in csv file with empty values. If I open csv file in notepad then empty lines looks like this: ,,,, ,,,, ,,,, ,,,,
You can not see those if open in Excel. Please check in Notepad and delete those records
you can use this code to open (test.xlsx) file and modify A1 cell and then save it with a new name
import openpyxl
xfile = openpyxl.load_workbook('test.xlsx')
sheet = xfile.get_sheet_by_name('Sheet1')
sheet['A1'] = 'hello world'
xfile.save('text2.xlsx')
I generally install Apache + PHP + MySQL by-hand, not using any package like those you're talking about.
It's a bit more work, yes; but knowing how to install and configure your environment is great -- and useful.
The first time, you'll need maybe half a day or a day to configure those. But, at least, you'll know how to do so.
And the next times, things will be far more easy, and you'll need less time.
Else, you might want to take a look at Zend Server -- which is another package that bundles Apache + PHP + MySQL.
Or, as an alternative, don't use Windows.
If your production servers are running Linux, why not run Linux on your development machine?
And if you don't want to (or cannot) install Linux on your computer, use a Virtual Machine.
Here are three simple implementations, first the oneliner:
public static boolean oneLinerPalin(String str){
return str.equals(new StringBuffer(str).reverse().toString());
}
This is ofcourse quite slow since it creates a stringbuffer and reverses it, and the whole string is always checked nomatter if it is a palindrome or not, so here is an implementation that only checks the required amount of chars and does it in place, so no extra stringBuffers:
public static boolean isPalindrome(String str){
if(str.isEmpty()) return true;
int last = str.length() - 1;
for(int i = 0; i <= last / 2;i++)
if(str.charAt(i) != str.charAt(last - i))
return false;
return true;
}
And recursively:
public static boolean recursivePalin(String str){
return check(str, 0, str.length() - 1);
}
private static boolean check (String str,int start,int stop){
return stop - start < 2 ||
str.charAt(start) == str.charAt(stop) &&
check(str, start + 1, stop - 1);
}
I think you are looking for:
git update-index --skip-worktree FILENAME
which ignore changes made local
Here's http://devblog.avdi.org/2011/05/20/keep-local-modifications-in-git-tracked-files/ more explanation about these solution!
to undo use:
git update-index --no-skip-worktree FILENAME
Exchange rate from Euro to NOK on the first of January 2016:
=INDEX(GOOGLEFINANCE("CURRENCY:EURNOK"; "close"; DATE(2016;1;1)); 2; 2)
The INDEX()
function is used because GOOGLEFINANCE()
function actually prints out in 4 separate cells (2x2) when you call it with these arguments, with it the result will only be one cell.
$("#slide").animate({width:'toggle'},350);
Reference: https://api.jquery.com/animate/
I did not realize that the first nested element is actually an array. The correct way access to the post code key is as follows:
r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()
print j['state']
print j['places'][1]['post code']
I installed Oracle Express Edition and I have the same error. One of the possible reason that is maybe your user does not have permission to open this shortcut. Here is how I solved the problem.
1. Right-click the shortcut and select the properties
.
2. Now click the Open File Location
.
Now you will see there is a Get_Started
shortcut.
3. Now right-click the Get_Started
and select the properties
. Then select your user and give permission to your user in the security
tab.
You code should look like this:
public int getElement(int[] arrayOfInts, int index) {
return arrayOfInts[index];
}
Main points here are method return type, it should match with array elements type and if you are working from main()
- this method must be static also.
findOne, modify fields & save
User.findOne({username: oldUsername})
.then(user => {
user.username = newUser.username;
user.password = newUser.password;
user.rights = newUser.rights;
user.markModified('username');
user.markModified('password');
user.markModified('rights');
user.save(err => console.log(err));
});
User.findOneAndUpdate({username: oldUsername}, {$set: { username: newUser.username, user: newUser.password, user:newUser.rights;}}, {new: true}, (err, doc) => {
if (err) {
console.log("Something wrong when updating data!");
}
console.log(doc);
});
Also see updateOne
Set item using data['id'] = ...
.
import json
with open('data.json', 'r+') as f:
data = json.load(f)
data['id'] = 134 # <--- add `id` value.
f.seek(0) # <--- should reset file position to the beginning.
json.dump(data, f, indent=4)
f.truncate() # remove remaining part
In JavaScript, most functions are both callable and instantiable: they have both a [[Call]] and [[Construct]] internal methods.
As callable objects, you can use parentheses to call them, optionally passing some arguments. As a result of the call, the function can return a value.
var player = makeGamePlayer("John Smith", 15, 3);
The code above calls function makeGamePlayer
and stores the returned value in the variable player
. In this case, you may want to define the function like this:
function makeGamePlayer(name, totalScore, gamesPlayed) {
// Define desired object
var obj = {
name: name,
totalScore: totalScore,
gamesPlayed: gamesPlayed
};
// Return it
return obj;
}
Additionally, when you call a function you are also passing an additional argument under the hood, which determines the value of this
inside the function. In the case above, since makeGamePlayer
is not called as a method, the this
value will be the global object in sloppy mode, or undefined in strict mode.
As constructors, you can use the new
operator to instantiate them. This operator uses the [[Construct]] internal method (only available in constructors), which does something like this:
.prototype
of the constructorthis
valuevar player = new GamePlayer("John Smith", 15, 3);
The code above creates an instance of GamePlayer
and stores the returned value in the variable player
. In this case, you may want to define the function like this:
function GamePlayer(name,totalScore,gamesPlayed) {
// `this` is the instance which is currently being created
this.name = name;
this.totalScore = totalScore;
this.gamesPlayed = gamesPlayed;
// No need to return, but you can use `return this;` if you want
}
By convention, constructor names begin with an uppercase letter.
The advantage of using constructors is that the instances inherit from GamePlayer.prototype
. Then, you can define properties there and make them available in all instances
Another possible solution:
<div>
<h2 align="center">
San Andreas: Multiplayer
</h2>
<div align="center">
<font size="+1"><em class="heading_description">15 pence per
slot</em></font> <img src=
"http://fhers.com/images/game_servers/sa-mp.jpg" class=
"alignleft noTopMargin" style="width: 188px;" /> <a href="gfh"
class="order-small"><span>order</span></a>
</div>
</div>
Also helpful as well.
I think this question has been pretty well answered, but I just wanted to add a method using Python 3.8 and the new assignment expression (walrus operator) since it is stylistically simple.
import socket
host = "127.0.0.1"
port = 31337
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen()
con, addr = s.accept()
msg_list = []
while (walrus_msg := con.recv(3)) != b'\r\n':
msg_list.append(walrus_msg)
print(msg_list)
In this case, 3 bytes are received from the socket and immediately assigned to walrus_msg
. Once the socket receives a b'\r\n'
it breaks the loop. walrus_msg
are added to a msg_list
and printed after the loop breaks. This script is basic but was tested and works with a telnet session.
NOTE: The parenthesis around the (walrus_msg := con.recv(3))
are needed. Without this, while walrus_msg := con.recv(3) != b'\r\n':
evaluates walrus_msg
to True
instead of the actual data on the socket.
if we do this
@interface Class_B : Class_A
mean we are inheriting the Class_A into Class_B, in Class_B we can access all the variables of class_A.
if we are doing this
#import ....
@class Class_A
@interface Class_B
here we saying that we are using the Class_A in our program, but if we want to use the Class_A variables in Class_B we have to #import Class_A in .m file(make a object and use it's function and variables).
To add to @abevieiramota's excellent answer, you can get the euqivalent of tight_layout with constrained_layout. You will still get large horizontal gaps if you use imshow
instead of pcolormesh
because of the 1:1 aspect ratio imposed by imshow
.
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=2, constrained_layout=True)
for ax in axes.flat:
im = ax.pcolormesh(np.random.random((10,10)), vmin=0, vmax=1)
fig.colorbar(im, ax=axes.flat)
plt.show()
Update a row or column of a table
$update = "UPDATE daily_patients SET queue_status = 'pending' WHERE doctor_id = $room_no and serial_number= $serial_num";
if ($con->query($update) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $con->error;
}
Swift 5
Cant fetch data from your api.
Easiest way to parse json is Use Decodable
protocol. Or Codable
(Encodable & Decodable
).
For ex:
let json = """
{
"dueDate": {
"year": 2021,
"month": 2,
"day": 17
}
}
"""
struct WrapperModel: Codable {
var dueDate: DueDate
}
struct DueDate: Codable {
var year: Int
var month: Int
var day: Int
}
let jsonData = Data(json.utf8)
let decoder = JSONDecoder()
do {
let model = try decoder.decode(WrapperModel.self, from: jsonData)
print(model)
} catch {
print(error.localizedDescription)
}
Like Jaanus told:
Calling this (-selectRowAtIndexPath:animated:scrollPosition:) method does not cause the delegate to receive a tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath: message, nor will it send UITableViewSelectionDidChangeNotification notifications to observers.
So you just have to call the delegate
method yourself.
For example:
Swift 3 version:
let indexPath = IndexPath(row: 0, section: 0);
self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
self.tableView(self.tableView, didSelectRowAt: indexPath)
ObjectiveC version:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView selectRowAtIndexPath:indexPath
animated:YES
scrollPosition:UITableViewScrollPositionNone];
[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
Swift 2.3 version:
let indexPath = NSIndexPath(forRow: 0, inSection: 0);
self.tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)
It can and it should be easy as :
class OneHotEncoder:
def __init__(self,optionKeys):
length=len(optionKeys)
self.__dict__={optionKeys[j]:[0 if i!=j else 1 for i in range(length)] for j in range(length)}
Usage :
ohe=OneHotEncoder(["A","B","C","D"])
print(ohe.A)
print(ohe.D)
you might consider using the Relative and Absolute positining.
`.container {
position: relative;
}
.tag {
position: absolute;
}`
I have tested it there, also if you want it to change its position use this as its margin:
top: 20px;
left: 10px;
It will place it 20 pixels from top and 10 pixels from left; but leave this one if not necessary.
Just do:
echo substr($string, 0, -3);
You don't need to use a strlen
call, since, as noted in the substr docs:
If length is given and is negative, then that many characters will be omitted from the end of string
The ByteBuffer class is important because it forms a basis for the use of channels in Java. ByteBuffer class defines six categories of operations upon byte buffers, as stated in the Java 7 documentation:
Absolute and relative get and put methods that read and write single bytes;
Relative bulk get methods that transfer contiguous sequences of bytes from this buffer into an array;
Relative bulk put methods that transfer contiguous sequences of bytes from a byte array or some other byte buffer into this buffer;
Absolute and relative get and put methods that read and write values of other primitive types, translating them to and from sequences of bytes in a particular byte order;
Methods for creating view buffers, which allow a byte buffer to be viewed as a buffer containing values of some other primitive type; and
Methods for compacting, duplicating, and slicing a byte buffer.
Example code : Putting Bytes into a buffer.
// Create an empty ByteBuffer with a 10 byte capacity
ByteBuffer bbuf = ByteBuffer.allocate(10);
// Get the buffer's capacity
int capacity = bbuf.capacity(); // 10
// Use the absolute put(int, byte).
// This method does not affect the position.
bbuf.put(0, (byte)0xFF); // position=0
// Set the position
bbuf.position(5);
// Use the relative put(byte)
bbuf.put((byte)0xFF);
// Get the new position
int pos = bbuf.position(); // 6
// Get remaining byte count
int rem = bbuf.remaining(); // 4
// Set the limit
bbuf.limit(7); // remaining=1
// This convenience method sets the position to 0
bbuf.rewind(); // remaining=7
This is not the real problem, if you want to see why this is happening then please go to error log file of IIS.
in case of visual studio kindly navigate to:
C:\Users\User\Documents\IISExpress\TraceLogFiles\[your project name]\.
arrange file here in datewise descending and then open very first file.
it will look like:
now scroll down to bottom to see the GENERAL_RESPONSE_ENTITY_BUFFER
it is the actual problem. now solve it the above problem will solve automatically.
Another simple way using JOIN
and INSTR
Sub Sample()
Dim Mainfram(4) As String, strg As String
Dim cel As Range
Dim Delim As String
Delim = "#"
Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"
strg = Join(Mainfram, Delim)
strg = Delim & strg
For Each cel In Selection
If InStr(1, strg, Delim & cel.Value & Delim, vbTextCompare) Then _
Rows(cel.Row).Style = "Accent1"
Next cel
End Sub
In macOS 10.10+ / iOS 8.0+ (NS)DateComponentsFormatter
has been introduced to create a readable string.
It considers the user's locale und language.
let interval = 27005
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.unitsStyle = .full
let formattedString = formatter.string(from: TimeInterval(interval))!
print(formattedString)
The available unit styles are positional
, abbreviated
, short
, full
, spellOut
and brief
.
For more information please read the documenation.
If your mock involves a network request, another alternative is to have a real test server to hit. You can use a service to generate a request and response for your testing.
$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"[email protected]"));
echo "<pre>";
echo json_encode($products_arr,JSON_PRETTY_PRINT);
echo "</pre>";
//OR
$countries = array();
$countries["DK"] = array("code"=>"DK","name"=>"Denmark","d_code"=>"+45");
$countries["DJ"] = array("code"=>"DJ","name"=>"Djibouti","d_code"=>"+253");
$countries["DM"] = array("code"=>"DM","name"=>"Dominica","d_code"=>"+1");
foreach ($countries as $country){
echo "<pre>";
echo print_r($country);
echo "</pre>";
}
This will match yyyy-mm-dd
and also yyyy-m-d
:
^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$
If you're looking for an exact match for yyyy-mm-dd
then try this
^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$
or use this one if you need to find a date inside a string like The date is 2017-11-30
\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*
If you want to send an arbitrary amount of data to your server, POST is the only reliable method to do that. GET would also be possible but clients and servers allow just a limited URL length (something like 2048 characters).
If you want to update react use npx update react
on the terminal.
This is the fastest way:
if ($coll->isEmpty()) {...}
Other solutions like count
do a bit more than you need which costs slightly more time.
Plus, the isEmpty()
name quite precisely describes what you want to check there so your code will be more readable.
If you know for sure that your current encoding is pure ASCII, then you don't have to do anything because ASCII is already a valid UTF-8.
But if you still want to convert, just to be sure that its UTF-8, then you can use iconv
$string = iconv('ASCII', 'UTF-8//IGNORE', $string);
The IGNORE will discard any invalid characters just in case some were not valid ASCII.
Some important facts were not given in other answers:
"async await" is more complex at CIL level and thus costs memory and CPU time.
Any task can be canceled if the waiting time is unacceptable.
In the case "async await" we do not have a handler for such a task to cancel it or monitoring it.
Using Task is more flexible then "async await".
Any sync functionality can by wrapped by async.
public async Task<ActionResult> DoAsync(long id)
{
return await Task.Run(() => { return DoSync(id); } );
}
"async await" generate many problems. We do not now is await statement will be reached without runtime and context debugging. If first await not reached everything is blocked. Some times even await seems to be reached still everything is blocked:
https://github.com/dotnet/runtime/issues/36063
I do not see why I'm must live with the code duplication for sync and async method or using hacks.
Conclusion: Create Task manually and control them is much better. Handler to Task give more control. We can monitor Tasks and manage them:
https://github.com/lsmolinski/MonitoredQueueBackgroundWorkItem
Sorry for my english.
Use
SELECT * FROM table WHERE DATE(2012-05-05 00:00:00) = '2012-05-05'
Your route isn't ok, it should be like this (with ':')
app.get('/documents/:format/:type', function (req, res) {
var format = req.params.format,
type = req.params.type;
});
Also you cannot interchange parameter order unfortunately.
For more information on req.params
(and req.query
) check out the api reference here.
You will need to ask the picker's delegate, in the same way your application does. Here is how I do it from within my UIPickerViewDelegate:
func selectedRowValue(picker : UIPickerView, ic : Int) -> String {
//Row Index
let ir = picker.selectedRow(inComponent: ic);
//Value
let val = self.pickerView(picker,
titleForRow: ir,
forComponent: ic);
return val!;
}
In a Groovy script the scoping can be different than expected. That is because a Groovy script in itself is a class with a method that will run the code, but that is all done runtime. We can define a variable to be scoped to the script by either omitting the type definition or in Groovy 1.8 we can add the @Field annotation.
import groovy.transform.Field
var1 = 'var1'
@Field String var2 = 'var2'
def var3 = 'var3'
void printVars() {
println var1
println var2
println var3 // This won't work, because not in script scope.
}
The size member function.
myList.size();
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
Preface
This post is meant to be an easy-to-read alternative to litb's post.
The underlying purpose is the same; an explanation to "When?" and "Why?"
typename
andtemplate
must be applied.
typename
and template
?typename
and template
are usable in circumstances other than when declaring a template.
There are certain contexts in C++ where the compiler must explicitly be told how to treat a name, and all these contexts have one thing in common; they depend on at least one template-parameter.
We refer to such names, where there can be an ambiguity in interpretation, as; "dependent names".
This post will offer an explanation to the relationship between dependent-names, and the two keywords.
Try to explain what is going on in the following function-template, either to yourself, a friend, or perhaps your cat; what is happening in the statement marked (A)?
template<class T> void f_tmpl () { T::foo * x; /* <-- (A) */ }
It might not be as easy as one thinks, more specifically the result of evaluating (A) heavily depends on the definition of the type passed as template-parameter T
.
Different T
s can drastically change the semantics involved.
struct X { typedef int foo; }; /* (C) --> */ f_tmpl<X> ();
struct Y { static int const foo = 123; }; /* (D) --> */ f_tmpl<Y> ();
The two different scenarios:
If we instantiate the function-template with type X, as in (C), we will have a declaration of a pointer-to int named x, but;
if we instantiate the template with type Y, as in (D), (A) would instead consist of an expression that calculates the product of 123 multiplied with some already declared variable x.
The C++ Standard cares about our safety and well-being, at least in this case.
To prevent an implementation from potentially suffering from nasty surprises, the Standard mandates that we sort out the ambiguity of a dependent-name by explicitly stating the intent anywhere we'd like to treat the name as either a type-name, or a template-id.
If nothing is stated, the dependent-name will be considered to be either a variable, or a function.
If this was a Hollywood film, dependent-names would be the disease that spreads through body contact, instantly affects its host to make it confused. Confusion that could, possibly, lead to an ill-formed perso-, erhm.. program.
A dependent-name is any name that directly, or indirectly, depends on a template-parameter.
template<class T> void g_tmpl () {
SomeTrait<T>::type foo; // (E), ill-formed
SomeTrait<T>::NestedTrait<int>::type bar; // (F), ill-formed
foo.data<int> (); // (G), ill-formed
}
We have four dependent names in the above snippet:
SomeTrait<T>
, which include T
, and;SomeTrait<T>
, and;SomeTrait<T>
, and;SomeTrait<T>
.Neither of statement (E), (F) or (G) is valid if the compiler would interpret the dependent-names as variables/functions (which as stated earlier is what happens if we don't explicitly say otherwise).
To make g_tmpl
have a valid definition we must explicitly tell the compiler that we expect a type in (E), a template-id and a type in (F), and a template-id in (G).
template<class T> void g_tmpl () {
typename SomeTrait<T>::type foo; // (G), legal
typename SomeTrait<T>::template NestedTrait<int>::type bar; // (H), legal
foo.template data<int> (); // (I), legal
}
Every time a name denotes a type, all names involved must be either type-names or namespaces, with this in mind it's quite easy to see that we apply typename
at the beginning of our fully qualified name.
template
however, is different in this regard, since there's no way of coming to a conclusion such as; "oh, this is a template, then this other thing must also be a template". This means that we apply template
directly in front of any name that we'd like to treat as such.
"Can I just stick
typename
andtemplate
in front of any name? I don't want to worry about the context in which they appear..." -Some C++ Developer
The rules in the Standard states that you may apply the keywords as long as you are dealing with a qualified-name (K), but if the name isn't qualified the application is ill-formed (L).
namespace N {
template<class T>
struct X { };
}
N:: X<int> a; // ... legal
typename N::template X<int> b; // (K), legal
typename template X<int> c; // (L), ill-formed
Note: Applying typename
or template
in a context where it is not required is not considered good practice; just because you can do something, doesn't mean that you should.
Additionally there are contexts where typename
and template
are explicitly disallowed:
When specifying the bases of which a class inherits
Every name written in a derived class's base-specifier-list is already treated as a type-name, explicitly specifying typename
is both ill-formed, and redundant.
// .------- the base-specifier-list
template<class T> // v
struct Derived : typename SomeTrait<T>::type /* <- ill-formed */ {
...
};
When the template-id is the one being referred to in a derived class's using-directive
struct Base {
template<class T>
struct type { };
};
struct Derived : Base {
using Base::template type; // ill-formed
using Base::type; // legal
};
The simplest way, based on @nosklo's comment and answer:
import tempfile
tmp = tempfile.mkdtemp()
But if you want to manually control the creation of the directories:
import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)
That way you can easily clean up after yourself when you are done (for privacy, resources, security, whatever) with:
from shutil import rmtree
rmtree(tmp, ignore_errors=True)
This is similar to what applications like Google Chrome and Linux systemd
do. They just use a shorter hex hash and an app-specific prefix to "advertise" their presence.
You can also use the $inject service to get whatever service you like. I find that useful if I don't know the service name ahead of time but know the service interface. For example a directive that will plug a table into an ngResource end point or a generic delete-record button which interacts with any api end point. You don't want to re-implement the table directive for every controller or data-source.
template.html
<div my-directive api-service='ServiceName'></div>
my-directive.directive.coffee
angular.module 'my.module'
.factory 'myDirective', ($injector) ->
directive =
restrict: 'A'
link: (scope, element, attributes) ->
scope.apiService = $injector.get(attributes.apiService)
now your 'anonymous' service is fully available. If it is ngResource for example you can then use the standard ngResource interface to get your data
For example:
scope.apiService.query((response) ->
scope.data = response
, (errorResponse) ->
console.log "ERROR fetching data for service: #{attributes.apiService}"
console.log errorResponse.data
)
I have found this technique to be very useful when making elements that interact with API endpoints especially.
Ok it turns out I was doing something stupid. I hadn't appended the new file name to the path.
I had
rootDirectory = "C:\\safesite_documents"
but it should have been
rootDirectory = "C:\\safesite_documents\\newFile.jpg"
Sorry it was a stupid mistake as always.
Base on @brian-s-wilson 's answer; this bash helper function:
pipestatus() {
local S=("${PIPESTATUS[@]}")
if test -n "$*"
then test "$*" = "${S[*]}"
else ! [[ "${S[@]}" =~ [^0\ ] ]]
fi
}
used thus:
1: get_bad_things must succeed, but it should produce no output; but we want to see output that it does produce
get_bad_things | grep '^'
pipeinfo 0 1 || return
2: all pipeline must succeed
thing | something -q | thingy
pipeinfo || return
Stack allocation is much faster since all it really does is move the stack pointer. Using memory pools, you can get comparable performance out of heap allocation, but that comes with a slight added complexity and its own headaches.
Also, stack vs. heap is not only a performance consideration; it also tells you a lot about the expected lifetime of objects.
There are multiple ways to get a string representation of a type. Switches can also be used with user types:
var user interface{}
user = User{name: "Eugene"}
// .(type) can only be used inside a switch
switch v := user.(type) {
case int:
// Built-in types are possible (int, float64, string, etc.)
fmt.Printf("Integer: %v", v)
case User:
// User defined types work as well
fmt.Printf("It's a user: %s\n", user.(User).name)
}
// You can use reflection to get *reflect.rtype
userType := reflect.TypeOf(user)
fmt.Printf("%+v\n", userType)
// You can also use %T to get a string value
fmt.Printf("%T", user)
// You can even get it into a string
userTypeAsString := fmt.Sprintf("%T", user)
if userTypeAsString == "main.User" {
fmt.Printf("\nIt's definitely a user")
}
Link to a playground: https://play.golang.org/p/VDeNDUd9uK6
Use these:
webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setDisplayZoomControls(false);
Raw string literals:
>>> r'abc\dev\t'
'abc\\dev\\t'
string data = "THExxQUICKxxBROWNxxFOX";
return data.Replace("xx","|").Split('|');
Just choose the replace character carefully (choose one that isn't likely to be present in the string already)!
Just change the flag DEBUG
to override the console.log function. This should do the trick.
var DEBUG = false;
// ENABLE/DISABLE Console Logs
if(!DEBUG){
console.log = function() {}
}
I real all the solution but there is not a standard solution...
JUST REMOVE NODEJS AND INSTALL THE LATEST VERSION OF NODEJS
instead of many bad shortcut solutions.
It wouldn't be wrong to mention that Pexpect
does throw a similar error
#python -c "import pexpect; p=pexpect.spawn('/usr/local/ssl/bin/openssl_1.1.0f version'); p.interact()"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/pexpect.py", line 430, in __init__
self._spawn (command, args)
File "/usr/lib/python2.7/site-packages/pexpect.py", line 560, in _spawn
os.execv(self.command, self.args)
OSError: [Errno 8] Exec format error
Over here, the openssl_1.1.0f
file at the specified path has exec
command specified in it and is running the actual openssl binary when called.
Usually, I wouldn't mention this unless I have the root cause, but this problem was not there earlier. Unable to find the similar problem, the closest explanation to make it work is the same as the one provided by @jfs above.
what worked for me is both
/bin/bash
at the beginning of the command or file you are#!/bin/sh
as the first line.for ex.
#python -c "import pexpect; p=pexpect.spawn('/bin/bash /usr/local/ssl/bin/openssl_1.1.0f version'); p.interact()"
OpenSSL 1.1.0f 25 May 2017
Also check the database version. I was having the problem with VBA CreateDatabase(sTempDBName, dbLangGeneral) in Access 2010 where I was using a 2003 database trying to link a table in a 2010 database. When I manually tried the link I got a message about no support for linking to a later version. Creating the temp database I was trying to link to using the option dbVersion40 "CreateDatabase(sTempDBName, dbLangGeneral, dbVersion40)" cured it.
You cannot, due to security reasons.
Imagine:
<form name="foo" method="post" enctype="multipart/form-data">
<input type="file" value="c:/passwords.txt">
</form>
<script>document.foo.submit();</script>
You don't want the websites you visit to be able to do this, do you? =)
If you add -Wl,--start-group
to the linker flags it does not care which order they're in or if there are circular dependencies.
On Qt this means adding:
QMAKE_LFLAGS += -Wl,--start-group
Saves loads of time messing about and it doesn't seem to slow down linking much (which takes far less time than compilation anyway).
Simple HTML + Javascript approach without CSS
function editDropBox() {_x000D_
var cSelect = document.getElementById('changingList');_x000D_
_x000D_
var optionsSavehouse = [];_x000D_
if(cSelect != null) {_x000D_
var optionsArray = Array.from(cSelect.options);_x000D_
_x000D_
var arrayLength = optionsArray.length;_x000D_
for (var o = 0; o < arrayLength; o++) {_x000D_
var option = optionsArray[o];_x000D_
var oVal = option.value;_x000D_
_x000D_
if(oVal > 0) {_x000D_
var localParams = [];_x000D_
localParams.push(option.text);_x000D_
localParams.push(option.value);_x000D_
//localParams.push(option.selected); // if needed_x000D_
optionsSavehouse.push(localParams);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
var hidden = ("<input id='hidden_select_options' type='hidden' value='" + JSON.stringify(optionsSavehouse) + "' />");_x000D_
_x000D_
var cSpan = document.getElementById('changingSpan');_x000D_
if(cSpan != null) {_x000D_
cSpan.innerHTML = (hidden + "<input size='2' type='text' id='tempInput' name='fname' onchange='restoreDropBox()'>");_x000D_
}_x000D_
}_x000D_
_x000D_
function restoreDropBox() {_x000D_
var cSpan = document.getElementById('changingSpan');_x000D_
var cInput = document.getElementById('tempInput');_x000D_
var hOptions = document.getElementById('hidden_select_options');_x000D_
_x000D_
if(cSpan != null) {_x000D_
_x000D_
var optionsArray = [];_x000D_
_x000D_
if(hOptions != null) {_x000D_
optionsArray = JSON.parse(hOptions.value);_x000D_
}_x000D_
_x000D_
var selectList = "<select id='changingList'>\n";_x000D_
_x000D_
var arrayLength = optionsArray.length;_x000D_
for (var o = 0; o < arrayLength; o++) {_x000D_
var option = optionsArray[o];_x000D_
selectList += ("<option value='" + option[1] + "'>" + option[0] + "</option>\n");_x000D_
}_x000D_
_x000D_
if(cInput != null) {_x000D_
selectList += ("<option value='-1' selected>" + cInput.value + "</option>\n");_x000D_
}_x000D_
_x000D_
selectList += ("<option value='-2' onclick='editDropBox()'>- Edit -</option>\n</select>");_x000D_
cSpan.innerHTML = selectList;_x000D_
}_x000D_
}
_x000D_
<span id="changingSpan">_x000D_
<select id="changingList">_x000D_
<option value="1">Apple</option>_x000D_
<option value="2">Banana</option>_x000D_
<option value="3">Cherry</option>_x000D_
<option value="4">Dewberry</option>_x000D_
<option onclick="editDropBox()" value="-2">- Edit -</option>_x000D_
</select>_x000D_
</span>
_x000D_
Now Django has __date queryset filter to query datetime objects against dates in development version. Thus, it will be available in 1.9 soon.
I think the best way to download any file generated by REST call is to use window.location example :
$http({_x000D_
url: url,_x000D_
method: 'GET'_x000D_
})_x000D_
.then(function scb(response) {_x000D_
var dataResponse = response.data;_x000D_
//if response.data for example is : localhost/export/data.csv_x000D_
_x000D_
//the following will download the file without changing the current page location_x000D_
window.location = 'http://'+ response.data_x000D_
}, function(response) {_x000D_
showWarningNotification($filter('translate')("global.errorGetDataServer"));_x000D_
});
_x000D_
The space before the =
is interpreted as part of the name, and the space after it (as well as the quotation marks) are interpreted as part of the value. So the variable you’ve created can be referenced with %location %
. If that’s not what you want, remove the extra space(s) in the definition.
I tried all the thing that are mentioned above, but still it is not working.
but finally I found the issue in Angular site.Try to import formModule in module.ts thats it.
onProgressChanged() should be called on every progress changed, not just on first and last touch (that why you have onStartTrackingTouch() and onStopTrackingTouch() methods).
Make sure that your SeekBar have more than 1 value, that is to say your MAX>=3.
In your onCreate:
yourSeekBar=(SeekBar) findViewById(R.id.yourSeekBar);
yourSeekBar.setOnSeekBarChangeListener(new yourListener());
Your listener:
private class yourListener implements SeekBar.OnSeekBarChangeListener {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// Log the progress
Log.d("DEBUG", "Progress is: "+progress);
//set textView's text
yourTextView.setText(""+progress);
}
public void onStartTrackingTouch(SeekBar seekBar) {}
public void onStopTrackingTouch(SeekBar seekBar) {}
}
Please share some code and the Log results for furter help.
Having 2 elements with the same ID is not valid html according to the W3C specification.
When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById
method, which returns only the first element with that ID.
However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll
, if available), which apparently selects both elements. Results may vary on a per browser basis.
However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.
If you absolutely must select by duplicate ID, use an attribute selector:
$('[id="a"]');
Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/
Note: if possible, you should qualify that selector with a tag selector, like this:
$('span[id="a"]');
It can be added by using:
$psql -d databaseName -c "CREATE EXTENSION dblink"
I have found all of the above solutions work just fine because they trigger your IDE to rebuild the project. No magic involved.
The "real" solution for this issue is that you should just ditch your previous build directory.
Many times the problem comes because php
does not support short open tags in php.ini
file, i.e:
<?
phpinfo();
?>
You must use:
<?php
phpinfo();
?>
List is interface and ArrayList is implemented concrete class. It is always recommended to use.
List<String> arrayList = new ArrayList<String>();
Because here list reference is flexible. It can also hold LinkedList or Vector
object.
Ok, at that time got it done with the help of a friend and the code looks like this.
Sub Saving()
Dim part1 As String
Dim part2 As String
part1 = Range("C5").Value
part2 = Range("C8").Value
ActiveWorkbook.SaveAs Filename:= _
"C:\-docs\cmat\Desktop\pieteikumi\" & part1 & " " & part2 & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub
How do I edit this part (FileFormat:= _ xlOpenXMLWorkbookMacroEnabled) for it to save as Excel 97-2013 Workbook, have tried several variations with no success. Thankyou
Seems, that I found the solution, but my idea is flawed. By doing this FileFormat:= _ xlOpenXMLWorkbook, it drops out a popup saying, the you cannot save this workbook as a file without Macro enabled. So, is this impossible?
For anyone who lands here by searching:
content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8
or some subset of that error:
A similar error was caused in my case by building and running a service without proper attributes. I got this error message when I tried to update the service reference in my client application. It was resolved when I correctly applied [DataContract]
and [DataMember]
attributes to my custom classes.
This would most likely be applicable if your service was set up and working and then it broke after you edited it.
Knockout.js validation is handy but it is not robust. You always have to create server side validation replica. In your case (as you use knockout.js) you are sending JSON data to server and back asynchronously, so you can make user think that he sees client side validation, but in fact it would be asynchronous server side validation.
Take a look at example here upida.cloudapp.net:8080/org.upida.example.knockout/order/create?clientId=1 This is a "Create Order" link. Try to click "save", and play with products. This example is done using upida library (there are spring mvc version and asp.net mvc of this library) from codeplex.
There are many ways how you can fix this issue, if you know the root of the issue.
Problem 1
Firstly, it may be a problem with your apache not having the mod_rewrite.c module installed or enabled.
For this reason, you would have to enable it as follows
Open up your console and type into it, this:
sudo a2enmod rewrite
Restart your apache server.
service apache2 restart
Problem 2
You may also, in addition to the above, if it does not work, have to change the override rule from the apache conf file (either apache2.conf, http.conf , or 000-default file).
Locate "Directory /var/www/"
Change the "Override None" to "Override All"
Problem 3
If you get an error stating rewrite module is not found, then probably your userdir module is not enabled. For this reason you need to enable it.
Type this into the console:
sudo a2enmod userdir
Then try enabling the rewrite module if still not enabled (as mentioned above).
To read further on this, you can visit this site: http://seventhsoulmountain.blogspot.com/2014/02/wordpress-permalink-ubuntu-problem-solutions.html
No, there isn't an equivalent. The <iframe>
element is still valid in HTML5. Depending on what exact interaction you need there might be different APIs. For example there's the postMessage
method which allows you to achieve cross domain javascript interaction. But if you want to display cross domain HTML contents (styled with CSS and made interactive with javascript) iframe
stays as a good way to do.
I've got the same issue, my model is binding from another form, I've added ng-change
and ng-model
and it still doesn't work:
<input type="hidden" id="pdf-url" class="form-control" ng-model="pdfUrl"/>
<ng-dropzone
dropzone="dropzone"
dropzone-config="dropzoneButtonCfg"
model="pdfUrl">
</ng-dropzone>
An input #pdf-url
gets data from dropzone (two ways binding), however, ng-change
doesn't work in this case. $scope.$watch
is a solution for me:
$scope.$watch('pdfUrl', function updatePdfUrl(newPdfUrl, oldPdfUrl) {
if (newPdfUrl !== oldPdfUrl) {
// It's updated - Do something you want here.
}
});
Hope this help.
For people Googling,
The solid answer should be.
const substrings = ['connect', 'ready'];
const str = 'disconnect';
if (substrings.some(v => str === v)) {
// Will only return when the `str` is included in the `substrings`
}
You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.
The easiest solution for this is creating a shortcode. Then you can use something like this
function input_func( $atts ) {
extract( shortcode_atts( array(
'type' => 'text',
'name' => '',
), $atts ) );
return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );
See the Shortcode_API.
I got a similar problem , I parsed the youtube url. The code is;
$json_is = "http://gdata.youtube.com/feeds/api/videos?q=".$this->video_url."&max-results=1&alt=json";
$video_info = json_decode ( file_get_contents ( $json_is ), true );
$video_title = is_array ( $video_info ) ? $video_info ['feed'] ['entry'] [0] ['title'] ['$t'] : '';
Then I realise that $this->video_url
include the whitespace. I solved that using trim($this->video_url)
.
Maybe it will help you . Good Luck
You can also reference the obj
once you are inside the function instead of this
.
var obj = {
key1: "it",
key2: function(){return obj.key1 + " works!"}
};
alert(obj.key2());
If it is a windows system, then it may be because you are using 32 bit winpcap library in a 64 bit pc or vie versa. If it is a 64 bit pc then copy the winpcap library and header packet.lib and wpcap.lib from winpcap/lib/x64 to the winpcap/lib directory and overwrite the existing
I have a simple approach.
Step 1: Mount /var/run/docker.sock:/var/run/docker.sock (So you will be able to execute docker commands inside your container)
Step 2: Execute this below inside your container. The key part here is (--network host as this will execute from host context)
docker run -i --rm --network host -v /opt/test.sh:/test.sh alpine:3.7 sh /test.sh
test.sh should contain the some commands (ifconfig, netstat etc...) whatever you need. Now you will be able to get host context output.
If you have the liberty to configure your webserver yourself, tools like mod_xsendfile (for Apache) are considerably better than reading and printing the file in PHP. Your PHP code would look like this:
header("Content-type: $type");
header("X-Sendfile: $file"); # make sure $file is the full path, not relative
exit();
mod_xsendfile picks up the X-Sendfile header and sends the file to the browser itself. This can make a real difference in performance, especially for big files. Most of the proposed solutions read the whole file into memory and then print it out. That's OK for a 20kbyte image file, but if you have a 200 MByte TIFF file, you're bound to get problems.
t(sapply(a, '[', 1:max(sapply(a, length))))
where 'a' is a list. Would work for unequal row size
If you are using vue2-google-maps like me, the code to set the size looks like this:
<gmap-marker
..
:icon="{
..
anchor: { x: iconSize, y: iconSize },
scaledSize: { height: iconSize, width: iconSize },
}"
>
Without VBA...
If you can use a helper column, you can use the MATCH
function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match
To simply identify duplicates, use a helper column
Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:
=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")
Drag/copy this forumla down, and it should identify the duplicates.
To highlight cells, use conditional formatting:
With some tinkering, you can use this MATCH
function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.
Something like:
=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))
For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:
=B1="Duplicate"
This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.
With the help of user=User.query.filter_by(username=form.username.data).first()
statement you will get the specified user in user
variable.
Now you can change the value of the new object variable like user.no_of_logins += 1
and save the changes with the session
's commit method.
The jquery colortip plugin also supports <br>
tags in the title attribute, you might want to look into that one.
And for all of us who use Eclipse keymaps the shortcut is Ctrl+H. Expect limited options compared to eclipse or you will be disappointed.
Get the id of the div
whose content you want to change then assign the text as below:
var myDiv = document.getElementById("divId");
myDiv.innerHTML = "Content To Show";
If you want to delete for example the last 3
commits, run the following command to remove the changes from the file system (working tree) and commit history (index) on your local branch:
git reset --hard HEAD~3
Then run the following command (on your local machine) to force the remote branch to rewrite its history:
git push --force
Congratulations! All DONE!
Some notes:
You can retrieve the desired commit id by running
git log
Then you can replace HEAD~N
with <desired-commit-id>
like this:
git reset --hard <desired-commit-id>
If you want to keep changes on file system and just modify index (commit history), use --soft
flag like git reset --soft HEAD~3
. Then you have chance to check your latest changes and keep or drop all or parts of them. In the latter case runnig git status
shows the files changed since <desired-commit-id>
. If you use --hard
option, git status
will tell you that your local branch is exactly the same as the remote one. If you don't use --hard
nor --soft
, the default mode is used that is --mixed
. In this mode, git help reset
says:
Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated.
You need to use to_timestamp()
to convert your string to a proper timestamp
value:
to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
If your column is of type DATE
(which also supports seconds), you need to use to_date()
to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
To get this into a where
condition use the following:
select *
from TableA
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')
You never need to use to_timestamp()
on a column that is of type timestamp
.
You can try this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<layer-list>
<item android:left="1dp" android:top="3dp">
<shape>
<solid android:color="#a5040d" />
<corners android:radius="3dip"/>
</shape>
</item>
</layer-list>
</item>
<item>
<layer-list>
<item android:left="0dp" android:top="0dp">
<shape>
<solid android:color="#99080d" />
<corners android:radius="3dip"/>
</shape>
</item>
<item android:bottom="3dp" android:right="2dp">
<shape>
<solid android:color="#a5040d" />
<corners android:radius="3dip"/>
</shape>
</item>
</layer-list>
</item>
>>> s = "foobar"
>>> list(s)
['f', 'o', 'o', 'b', 'a', 'r']
You need list
Navigate to file -> Project structure -> modules -> click on green plus button to add a module.
Select new module -> select Application Module in Android option -> give a module name -> next -> next -> finish
Select project that to be include in module -> click apply -> okay
Now you will be able to see the full project structure; then open the module form project window (the left panel), select res then select layout -> your layout name(.xml).
Now you will be able to see the design view and text view both...
In this sample in catch block i change the value of counter and it will break while block:
class TestBreak {
public static void main(String[] a) {
int counter = 0;
while(counter<5) {
try {
counter++;
int x = counter/0;
}
catch(Exception e) {
counter = 1000;
}
}
}
}k
In my case, I use Symfony2.3.x and the minimum-stability parameter is by default "stable" (which is good). I wanted to import a repo not in packagist but had the same issue "Your requirements could not be resolved to an installable set of packages.". It appeared that the composer.json in the repo I tried to import use a minimum-stability "dev".
So to resolve this issue, don't forget to verify the minimum-stability
. I solved it by requiring a dev-master
version instead of master
as stated in this post.
If you're ok with POSIX, you can also use popen()
/pclose()
#include <stdio.h>
#include <stdlib.h>
int main(void) {
/* ls -al | grep '^d' */
FILE *pp;
pp = popen("ls -al", "r");
if (pp != NULL) {
while (1) {
char *line;
char buf[1000];
line = fgets(buf, sizeof buf, pp);
if (line == NULL) break;
if (line[0] == 'd') printf("%s", line); /* line includes '\n' */
}
pclose(pp);
}
return 0;
}
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
If you use Android, you can simply use android.text.format.Formatter.formatFileSize().
Alternatively, here's a solution based on this popular post:
/**
* Formats the bytes to a human readable format
*
* @param si true if each kilo==1000, false if kilo==1024
*/
@SuppressLint("DefaultLocale")
public static String humanReadableByteCount(final long bytes, final boolean si)
{
final int unit = si ? 1000 : 1024;
if(bytes<unit)
return bytes + " B";
double result = bytes;
final String unitsToUse = (si ? "k" : "K") + "MGTPE";
int i = 0;
final int unitsCount = unitsToUse.length();
while(true)
{
result /= unit;
if(result < unit)
break;
// Check if we can go further:
if(i == unitsCount-1)
break;
++i;
}
final StringBuilder sb = new StringBuilder(9);
sb.append(String.format("%.1f ", result));
sb.append(unitsToUse.charAt(i));
if(si)
sb.append('B');
else sb.append('i').append('B');
final String resultStr = sb.toString();
return resultStr;
}
Or in Kotlin:
/**
* formats the bytes to a human readable format
*
* @param si true if each kilo==1000, false if kilo==1024
*/
@SuppressLint("DefaultLocale")
fun humanReadableByteCount(bytes: Long, si: Boolean): String? {
val unit = if (si) 1000.0 else 1024.0
if (bytes < unit)
return "$bytes B"
var result = bytes.toDouble()
val unitsToUse = (if (si) "k" else "K") + "MGTPE"
var i = 0
val unitsCount = unitsToUse.length
while (true) {
result /= unit
if (result < unit || i == unitsCount - 1)
break
++i
}
return with(StringBuilder(9)) {
append(String.format("%.1f ", result))
append(unitsToUse[i])
if (si) append('B') else append("iB")
}.toString()
}
Basically, it will make your code a lot easier to compile under other compilers which also implement the ANSI standard, and, if you are careful in which libraries/api calls you use, under other operating systems/platforms.
The first one, turns off SPECIFIC features of GCC. (-ansi) The second one, will complain about ANYTHING at all that does not adhere to the standard (not only specific features of GCC, but your constructs too.) (-pedantic).
From your description I suspect the most likely explanation is that you have some error in your memory management. You said you've been working on iPhone development for a few weeks, but not whether you are experienced with Objective C in general. If you've come from another background it can take a little while before you really internalise the memory management rules - unless you make a big point of it.
Remember, anything you get from an allocation function (usually the static alloc method, but there are a few others), or a copy method, you own the memory too and must release it when you are done.
But if you get something back from just about anything else including factory methods (e.g. [NSString stringWithFormat]
) then you'll have an autorelease reference, which means it could be released at some time in the future by other code - so it is vital that if you need to keep it around beyond the immediate function that you retain it. If you don't, the memory may remain allocated while you are using it, or be released but coincidentally still valid, during your emulator testing, but is more likely to be released and show up as bad access errors when running on the device.
The best way to track these things down, and a good idea anyway (even if there are no apparent problems) is to run the app in the Instruments tool, especially with the Leaks option.
According to this discussion, Promise
has finally been called CompletableFuture
for inclusion in Java 8, and its javadoc explains:
A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.
An example is also given on the list:
f.then((s -> aStringFunction(s)).thenAsync(s -> ...);
Note that the final API is slightly different but allows similar asynchronous execution:
CompletableFuture<String> f = ...;
f.thenApply(this::modifyString).thenAccept(System.out::println);
MySQL 5.7 changed the secure model: now MySQL root login requires a sudo
The simplest (and safest) solution will be create a new user and grant required privileges.
1. Connect to mysql
sudo mysql --user=root mysql
2. Create a user for phpMyAdmin
CREATE USER 'phpmyadmin'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'phpmyadmin'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;
Reference - https://askubuntu.com/questions/763336/cannot-enter-phpmyadmin-as-root-mysql-5-7
jQuery.offset
needs to be combined with scrollTop
and scrollLeft
as shown in this diagram:
Demo:
function getViewportOffset($e) {_x000D_
var $window = $(window),_x000D_
scrollLeft = $window.scrollLeft(),_x000D_
scrollTop = $window.scrollTop(),_x000D_
offset = $e.offset(),_x000D_
rect1 = { x1: scrollLeft, y1: scrollTop, x2: scrollLeft + $window.width(), y2: scrollTop + $window.height() },_x000D_
rect2 = { x1: offset.left, y1: offset.top, x2: offset.left + $e.width(), y2: offset.top + $e.height() };_x000D_
return {_x000D_
left: offset.left - scrollLeft,_x000D_
top: offset.top - scrollTop,_x000D_
insideViewport: rect1.x1 < rect2.x2 && rect1.x2 > rect2.x1 && rect1.y1 < rect2.y2 && rect1.y2 > rect2.y1_x000D_
};_x000D_
}_x000D_
$(window).on("load scroll resize", function() {_x000D_
var viewportOffset = getViewportOffset($("#element"));_x000D_
$("#log").text("left: " + viewportOffset.left + ", top: " + viewportOffset.top + ", insideViewport: " + viewportOffset.insideViewport);_x000D_
});
_x000D_
body { margin: 0; padding: 0; width: 1600px; height: 2048px; background-color: #CCCCCC; }_x000D_
#element { width: 384px; height: 384px; margin-top: 1088px; margin-left: 768px; background-color: #99CCFF; }_x000D_
#log { position: fixed; left: 0; top: 0; font: medium monospace; background-color: #EEE8AA; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- scroll right and bottom to locate the blue square -->_x000D_
<div id="element"></div>_x000D_
<div id="log"></div>
_x000D_
The necessary method is Mockito#verify:
public static <T> T verify(T mock,
VerificationMode mode)
mock
is your mocked object and mode
is the VerificationMode
that describes how the mock should be verified. Possible modes are:
verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");
You'll need these static imports from the Mockito
class in order to use the verify
method and these verification modes:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
So in your case the correct syntax will be:
Mockito.verify(mock, times(4)).send()
This verifies that the method send
was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.
If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode
. A simple
verify(mock).someMethod("was called once");
would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");
.
It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");
, but we can write
verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");
instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.
Just Go To the Genymotion Installation Directory and then in folder tools you will see adb.exe there open command prompt here and run adb commands
Ralph's answer is fabulous. I would rather use StringBuilder class to build/decorate the String because the usage of it is more look like Builder pattern.
public String decorateTheString(String orgStr){
StringBuilder builder = new StringBuilder();
builder.append(orgStr);
builder.deleteCharAt(orgStr.length()-1);
builder.insert(0,builder.hashCode());
return builder.toString();
}
It can be use as a helper/builder to build the String, not the String itself.
try this:
update `list`
set `test` = `number`
You can try with Directory.GetFiles and fix your pattern
string[] files = Directory.GetFiles(@"c:\", "*.txt");
foreach (string file in files)
{
File.Copy(file, "....");
}
Or Move
foreach (string file in files)
{
File.Move(file, "....");
}
you can simply restart the activity where your alertdialog appear or another activity depend on your judgement. if you want to restart activity use this finish(); startActivity(getIntent());
Sprintf is what you are looking for.
Example
fmt.Sprintf("foo: %s", bar)
You can also see it in use in the Errors example as part of "A Tour of Go."
return fmt.Sprintf("at %v, %s", e.When, e.What)
for (Tweet : tweets){ ...
should really be
for(Tweet tweet: tweets){...
You can also use Criteria.DISTINCT_ROOT_ENTITY
with Hibernate HQL query as well.
Example:
Query query = getSession().createQuery("from java_pojo_name");
query.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return query.list();
I want to add to other answers that setters can be used to prevent putting the object in an invalid state.
For instance let's suppose that I've to set a TaxId, modelled as a String. The first version of the setter can be as follows:
private String taxId;
public void setTaxId(String taxId) {
this.taxId = taxId;
}
However we'd better prevent the use to set the object with an invalid taxId, so we can introduce a check:
private String taxId;
public void setTaxId(String taxId) throws IllegalArgumentException {
if (isTaxIdValid(taxId)) {
throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid");
}
this.taxId = taxId;
}
The next step, to improve the modularity of the program, is to make the TaxId itself as an Object, able to check itself.
private final TaxId taxId = new TaxId()
public void setTaxId(String taxIdString) throws IllegalArgumentException {
taxId.set(taxIdString); //will throw exception if not valid
}
Similarly for the getter, what if we don't have a value yet? Maybe we want to have a different path, we could say:
public String getTaxId() throws IllegalStateException {
return taxId.get(); //will throw exception if not set
}
You need to use a group by clause.
SELECT site_id, MAX(ts) as TIME, count(*) group by site_id
For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root
can run smoothly.
You could also just use the bytes where they are, casting them to the type you need.
unsigned char *bytePtr = (unsigned char *)[data bytes];
If you want a version that raises an error:
"string to search".index("needle")
If you want a version that returns -1:
"string to search".find("needle")
This is more efficient than the 'in' syntax
int padding = ([[UIScreen mainScreen] bounds].size.height <= 480) ? 15 : 55;
means
int padding;
if ([[UIScreen mainScreen] bounds].size.height <= 480)
padding = 15;
else
padding = 55;
https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.
<script>
function equalHeight(group) {
tallest = 0;
group.each(function() {
thisHeight = $(this).height();
if(thisHeight > tallest) {
tallest = thisHeight;
}
});
group.height(tallest);
}
$(document).ready(function() {
equalHeight($(".column"));
});
</script>
It works for 5.7.8:
mysql> create table t1(updated datetime NOT NULL DEFAULT '0000-00-00 00:00:00');
Query OK, 0 rows affected (0.01 sec)
mysql> show create table t1;
+-------+-------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+-------------------------------------------------------------------------------------------------------------------------+
| t1 | CREATE TABLE `t1` (
`updated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |
+-------+-------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> select version();
+-----------+
| version() |
+-----------+
| 5.7.8-rc |
+-----------+
1 row in set (0.00 sec)
You can create a SQLFiddle to recreate your issue.
If it works for MySQL 5.6 and 5.7.8, but fails on 5.7.11. Then it probably is a regression bug for 5.7.11.
In the component.css or app.css add Icon Color styles
.material-icons.color_green { color: #00FF00; }
.material-icons.color_white { color: #FFFFFF; }
In the component.html set the icon class
<mat-icon class="material-icons color_green">games</mat-icon>
<mat-icon class="material-icons color_white">cloud</mat-icon>
ng build
I'm trying to redirect my current web site to other section on the same page, using JavaScript. This follow code work for me:
location.href='/otherSection'
Use reflection
System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));
You can use :+
to append element to array and +:
to prepend it:
0 +: array :+ 4
should produce:
res3: Array[Int] = Array(0, 1, 2, 3, 4)
It's the same as with any other implementation of Seq
.
mplcursors worked for me. mplcursors provides clickable annotation for matplotlib. It is heavily inspired from mpldatacursor (https://github.com/joferkington/mpldatacursor), with a much simplified API
import matplotlib.pyplot as plt
import numpy as np
import mplcursors
data = np.outer(range(10), range(1, 5))
fig, ax = plt.subplots()
lines = ax.plot(data)
ax.set_title("Click somewhere on a line.\nRight-click to deselect.\n"
"Annotations can be dragged.")
mplcursors.cursor(lines) # or just mplcursors.cursor()
plt.show()
By default, gcc selects the language based on the file extension, but you can force gcc to select a different language backend with the -x option thus:
gcc -x c++
More options are detailed in the gcc man page under "Options controlling the kind of output". See e.g. http://linux.die.net/man/1/gcc (search on the page for the text -x language
).
This facility is very useful in cases where gcc can't guess the language using a file extension, for example if you're generating code and feeding it to gcc via stdin.
Any chance your IIS is configured to require SSL on connections to your site/application?
I'd use recursion just in case so you can deep copy the map
and avoid bad surprises in case you were to change a map
element that is a map
itself.
Here's an example in a utils.go:
package utils
func CopyMap(m map[string]interface{}) map[string]interface{} {
cp := make(map[string]interface{})
for k, v := range m {
vm, ok := v.(map[string]interface{})
if ok {
cp[k] = CopyMap(vm)
} else {
cp[k] = v
}
}
return cp
}
And its test file (i.e. utils_test.go):
package utils
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestCopyMap(t *testing.T) {
m1 := map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
}
m2 := CopyMap(m1)
m1["a"] = "zzz"
delete(m1, "b")
require.Equal(t, map[string]interface{}{"a": "zzz"}, m1)
require.Equal(t, map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
}, m2)
}
It should easy enough to adapt if you need the map
key to be something else instead of a string
.
I assume that your style-sheet "style.css" is already located in the assets-folder
load the web-page with jsoup:
doc = Jsoup.connect("http://....").get();
remove links to external style-sheets:
// remove links to external style-sheets
doc.head().getElementsByTag("link").remove();
set link to local style-sheet:
// set link to local stylesheet
// <link rel="stylesheet" type="text/css" href="style.css" />
doc.head().appendElement("link").attr("rel", "stylesheet").attr("type", "text/css").attr("href", "style.css");
make string from jsoup-doc/web-page:
String htmldata = doc.outerHtml();
display web-page in webview:
WebView webview = new WebView(this);
setContentView(webview);
webview.loadDataWithBaseURL("file:///android_asset/.", htmlData, "text/html", "UTF-8", null);
For a group of textboxes in a form:
private System.Windows.Forms.TextBox lastFocus;
private void textBox_GotFocus(object sender, System.Windows.Forms.MouseEventArgs e)
{
TextBox senderTextBox = sender as TextBox;
if (lastFocus!=senderTextBox){
senderTextBox.SelectAll();
}
lastFocus = senderTextBox;
}
A reference
in Docker is what points to an image. This could be in a remote registry or the local registry. Let me describe the error message first and then show the solutions for this.
invalid reference format
This means that the reference we have used is not a valid format. This means, the reference (pointer) we have used to identify an image is invalid. Generally, this is followed by a description as follows. This will make the error much clearer.
invalid reference format: repository name must be lowercase
This means the reference we are using should not have uppercase letters. Try running docker run Ubuntu
(wrong) vs docker run ubuntu
(correct). Docker does not allow any uppercase characters as an image reference. Simple troubleshooting steps.
1) Dockerfile contains a capital letters as images.
FROM Ubuntu (wrong)
FROM ubuntu (correct)
2) Image name defined in the docker-compose.yml had uppercase letters
3) If you are using Jenkins or GoCD for deploying your docker container, please check the run command, whether the image name includes a capital letter.
Please read this document written specifically for this error.
For Spark 1.5 or later, you can use the functions package:
from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))
Quick explanation:
withColumn
is called to add (or replace, if the name exists) a column to the data frame. regexp_replace
will generate a new column by replacing all substrings that match the pattern.Sure there's an entity for tabs:
	
(The tab is ASCII character 9, or Unicode U+0009.)
However, just like literal tabs (ones you type in to your text editor), all tab characters are treated as whitespace by HTML parsers and collapsed into a single space except those within a <pre>
block, where literal tabs will be rendered as 8 spaces in a monospace font.
I managed to get it working by following Option 2 on the Windows installation instructions on the following page: https://github.com/nodejs/node-gyp.
I had to close the current command line interface and reopen it after doing the installation on another one logged in as Administrator.
Old question, but none of the answers satisfies me. One of my systems is running Ubuntu 12.04 LTS and for some reason there's no package python3-pip
or python-pip
for Python 3. So here is what I've done (all commands were executed as root):
Install setuptools
for Python3 in case you haven't.
apt-get install python3-setuptools
or
aptitude install python3-setuptools
With Python 2.4+ you can invoke easy_install
with specific Python version by using python -m easy_install
. So pip
for Python 3 could be installed by:
python3 -m easy_install pip
That's it, you got pip
for Python 3. Now just invoke pip
with the specific version of Python to install package for Python 3. For example, with Python 3.2 installed on my system, I used:
pip-3.2 install [package]
3 Ways to Install Applications On Android Without The Market
And don't forget to enable Unknown sources in your Android device Settings, before installing apk, else Android platform will not allow you to install apk directly
As it was already said, this can handle the problem:
$url='http://stackoverflow.com/questions/3711357/get-title-and-meta-tags-of-external-site/4640613';
$meta=get_meta_tags($url);
echo $title=$meta['title'];
//php - Get Title and Meta Tags of External site - Stack Overflow
Are you sure you've connected to the db? (I ask because I don't see a port specified)
try:
mongoose.connection.on("open", function(){
console.log("mongodb is connected!!");
});
Also, you can do a "show collections" in mongo shell to see the collections within your db - maybe try adding a record via mongoose and see where it ends up?
From the look of your connection string, you should see the record in the "test" db.
Hope it helps!
After long time stuck this issue, finally solved like this
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.textsize));
create folder like this res/values/dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="textsize">8sp</dimen>
</resources>
You can find the most up to date answer for the value in your project just execute the
mvn3 help:effective-pom
command and find the <build> ... <directory>
tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.
You can still unit test a void method by asserting that it had the appropriate side effect. In your method1
example, your unit test might look something like:
public void checkIfValidElementsWithDollarSign() {
checkIfValidElement("$",19);
assert ErrorFile.errorMessages.contains("There is a dollar sign in the specified parameter");
}
There may be different reason for reported issue, few days back also face this issue 'duplicate jar', after upgrading studio. From all stackoverflow I tried all the suggestion but nothing worked for me.
But this is for sure some duplicate jar is there, For me it was present in one library libs folder as well as project libs folder. So I removed from project libs folder as it was not required here. So be careful while updating the studio, and try to understand all the gradle error.
Although using File.separator to reference a file name is overkill (for those who imagine far off lands, I imagine their JVM implementation would replace a /
with a :
just like the windows jvm replaces it with a \
).
However, sometimes you are getting the file reference, not creating it, and you need to parse it, and to be able to do that, you need to know the separator on the platform. File.separator helps you do that.
You can have only one default export which you declare like:
export default App;
or
export default class App extends React.Component {...
and later do import App from './App'
If you want to export something more you can use named exports which you declare without default
keyword like:
export {
About,
Contact,
}
or:
export About;
export Contact;
or:
export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);
and later you import them like:
import App, { About, Contact } from './App';
EDIT:
There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js
file. Other than that why export anything if it is no used outside the file?. Correct main.js
:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'
class App extends React.Component {
...
}
class Home extends React.Component {
...
}
class About extends React.Component {
...
}
class Contact extends React.Component {
...
}
ReactDOM.render((
<Router history = {browserHistory}>
<Route path = "/" component = {App}>
<IndexRoute component = {Home} />
<Route path = "home" component = {Home} />
<Route path = "about" component = {About} />
<Route path = "contact" component = {Contact} />
</Route>
</Router>
), document.getElementById('app'))
EDIT2:
another thing is that this tutorial is based on react-router-V3 which has different api than v4.
The PowerShell string evaluation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()
for($i=0;$i -lt $ds.Tables[1].Rows.Count;$i++)
{
write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
}
Additionally foreach
allows you to iterate through a collection or array without needing to figure out the length.
Rewritten (and edited for compile) -
foreach ($Row in $ds.Tables[1].Rows)
{
write-host "value is : $($Row[0])"
}
this works wonders - no its turn to call this procedure form code with DataTable with schema exactly matching the custType create table customer ( id int identity(1,1) primary key, name varchar(50), cnt varchar(10) )
create type custType as table
(
ctId int,
ctName varchar(20)
)
insert into customer values('y1', 'c1')
insert into customer values('y2', 'c2')
insert into customer values('y3', 'c3')
insert into customer values('y4', 'c4')
insert into customer values('y5', 'c5')
declare @ct as custType
insert @ct (ctid, ctName) values(3, 'y33'), (4, 'y44')
exec multiUpdate @ct
create Proc multiUpdate (@ct custType readonly) as begin
update customer set Name = t.ctName from @ct t where t.ctId = customer.id
end
public DataTable UpdateLevels(DataTable dt)
{
DataTable dtRet = new DataTable();
using (SqlConnection con = new SqlConnection(datalayer.bimCS))
{
SqlCommand command = new SqlCommand();
command.CommandText = "UpdateLevels";
command.Parameters.Clear();
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@ct", dt).SqlDbType = SqlDbType.Structured;
command.Connection = con;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
dataAdapter.SelectCommand = command;
dataAdapter.Fill(dtRet);
}
}
}
Use the lubridate
package and function wday
:
library(lubridate)
df$date <- as.Date(df$date)
wday(df$date, label=TRUE)
[1] Wed Wed Thurs
Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat
In your XML layout:
<Button
android:id="@+id/cancelskill"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_weight="1"
android:background="@drawable/button_border"
android:padding="10dp"
android:text="Cancel"
android:textAllCaps="false"
android:textColor="#ffffff"
android:textSize="20dp" />
In the drawable folder, create a file for the button's border style:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke
android:width="1dp"
android:color="#f43f10" />
</shape>
And in your Activity:
GradientDrawable gd1 = new GradientDrawable();
gd1.setColor(0xFFF43F10); // Changes this drawbale to use a single color instead of a gradient
gd1.setCornerRadius(5);
gd1.setStroke(1, 0xFFF43F10);
cancelskill.setBackgroundDrawable(gd1);
cancelskill.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancelskill.setBackgroundColor(Color.parseColor("#ffffff"));
cancelskill.setTextColor(Color.parseColor("#f43f10"));
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFFFFFFFF); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(5);
gd.setStroke(1, 0xFFF43F10);
cancelskill.setBackgroundDrawable(gd);
finish();
}
});
Ok, looks like I missed an obvious step, but posting this in case anyone else does the same.
When upgrading to 1.7, my models became unmanaged (managed = False
) - I had them as True
before but seems it got reverted.
Removing that line (To default to True) and then running makemigrations
immediately made a migration module and now it's working. makemigrations
will not work on unmanaged tables (Which is obvious in hindsight)
This answer relates to modern setups (TypeScript 2.x, Webpack > 2.x)
You don't need to install @types/node (which is all of Node.js types and is irrelevant for front-end code, actually complicating things such as setTimout different return values, etc..
You do need to install @types/webpack-env
npm i -D @types/webpack-env
which gives the runtime signatures that Webpack has (including require
, require.ensure
, etc.)
Also make sure that your tsconfig.json file has no set 'types' array -> which will make it pickup all type definitions in your node_modules/@types folder.
If you want to restrict search of types you can set the typeRoot property to node_modules/@types.
Referring to Volomike's answer, I would suggest replacing the line
nViewH -= 250;
with
nViewH = nViewH / window.devicePixelRatio;
It works exactly as I check on a HTC Magic (PixelRatio = 1) and a Samsung Galaxy Tab 7" (PixelRatio = 1.5).
Just try this in razor
@{
var selectList = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "Google", Value = "Google"},
new SelectListItem {Text = "Other", Value = "Other"},
}, "Value", "Text");
}
and then
@Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { @class = "css-class" })
or
@Html.DropDownList("ddlDropDownList", selectList, "Default label", new { @class = "css-class" })
this should work also with different predicate
myFunction(strings.find( _ == mystring ).isDefined)
<a href="#Foo" onclick="return runMyFunction();">Do it!</a>
and
function runMyFunction() {
//code
return true;
}
This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.
Since the accepted answer and also the next highest voted answer have, in my opinion, some problems, I'd like to offer one more answer that is based closely on Ihor B.'s answer with some small but important modifications.
This solution allows you to run profiling on either by wrapping a function call with the profile
function and calling it, or by decorating your function/method with the @profile
decorator.
The first technique is useful when you want to profile some third-party code without messing with its source, whereas the second technique is a bit "cleaner" and works better when you are don't mind modifying the source of the function/method you want to profile.
I've also modified the output, so that you get RSS, VMS, and shared memory. I don't care much about the "before" and "after" values, but only the delta, so I removed those (if you're comparing to Ihor B.'s answer).
# profile.py
import time
import os
import psutil
import inspect
def elapsed_since(start):
#return time.strftime("%H:%M:%S", time.gmtime(time.time() - start))
elapsed = time.time() - start
if elapsed < 1:
return str(round(elapsed*1000,2)) + "ms"
if elapsed < 60:
return str(round(elapsed, 2)) + "s"
if elapsed < 3600:
return str(round(elapsed/60, 2)) + "min"
else:
return str(round(elapsed / 3600, 2)) + "hrs"
def get_process_memory():
process = psutil.Process(os.getpid())
mi = process.memory_info()
return mi.rss, mi.vms, mi.shared
def format_bytes(bytes):
if abs(bytes) < 1000:
return str(bytes)+"B"
elif abs(bytes) < 1e6:
return str(round(bytes/1e3,2)) + "kB"
elif abs(bytes) < 1e9:
return str(round(bytes / 1e6, 2)) + "MB"
else:
return str(round(bytes / 1e9, 2)) + "GB"
def profile(func, *args, **kwargs):
def wrapper(*args, **kwargs):
rss_before, vms_before, shared_before = get_process_memory()
start = time.time()
result = func(*args, **kwargs)
elapsed_time = elapsed_since(start)
rss_after, vms_after, shared_after = get_process_memory()
print("Profiling: {:>20} RSS: {:>8} | VMS: {:>8} | SHR {"
":>8} | time: {:>8}"
.format("<" + func.__name__ + ">",
format_bytes(rss_after - rss_before),
format_bytes(vms_after - vms_before),
format_bytes(shared_after - shared_before),
elapsed_time))
return result
if inspect.isfunction(func):
return wrapper
elif inspect.ismethod(func):
return wrapper(*args,**kwargs)
profile.py
:from profile import profile
from time import sleep
from sklearn import datasets # Just an example of 3rd party function call
# Method 1
run_profiling = profile(datasets.load_digits)
data = run_profiling()
# Method 2
@profile
def my_function():
# do some stuff
a_list = []
for i in range(1,100000):
a_list.append(i)
return a_list
res = my_function()
This should result in output similar to the below:
Profiling: <load_digits> RSS: 5.07MB | VMS: 4.91MB | SHR 73.73kB | time: 89.99ms
Profiling: <my_function> RSS: 1.06MB | VMS: 1.35MB | SHR 0B | time: 8.43ms
profile(my_function, arg)
to profile my_function(arg)
There are three ways I am aware of. The first not being the prettiest and the second being the common way in most programming languages:
'I mustn''t sin!'
\
before the single quote'
: 'I mustn\'t sin!'
"I mustn't sin!"
This allows for parallel execution on all android versions with API 4+ (Android 1.6+):
@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
void startMyTask(AsyncTask asyncTask) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
else
asyncTask.execute(params);
}
This is a summary of Arhimed's excellent answer.
Please make sure you use API level 11 or higher as your project build target. In Eclipse, that is Project > Properties > Android > Project Build Target
. This will not break backward compatibility to lower API levels. Don't worry, you will get Lint errors if your accidentally use features introduced later than minSdkVersion
. If you really want to use features introduced later than minSdkVersion
, you can suppress those errors using annotations, but in that case, you need take care about compatibility yourself. This is exactly what happened in the code snippet above.
To add on to Andreas' answer, you can install only the dependencies by using:
npm install --production
It is possible to use it with normal Statement
's as well (not just PreparedStatement
)
Statement statement = conn.createStatement();
int updateCount = statement.executeUpdate("insert into x...)", Statement.RETURN_GENERATED_KEYS);
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
return generatedKeys.getLong(1);
}
else {
throw new SQLException("Creating failed, no ID obtained.");
}
}
Just in case you do this for a lot of functions in your class:
class Foo {
public:
virtual void f1() {
// ...
}
virtual void f2() {
// ...
}
//...
};
class Bar : public Foo {
private:
typedef Foo super;
public:
void f1() {
super::f1();
}
};
This might save a bit of writing if you want to rename Foo.
In case anyone is wondering what input value
<input (keydown.enter)="search($event.target.value)" />
You can also do:
Integer a = '1182-2'.split('-')[0] as Integer
Integer b = '1182-2'.split('-')[1] as Integer
//a=1182 b=2
In addition to @delmadord's answer and your comments:
Currently there is no method to create subquery in FROM
clause, so you need to manually use raw statement, then, if necessary, you will merge all the bindings:
$sub = Abc::where(..)->groupBy(..); // Eloquent Builder instance
$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder
->count();
Mind that you need to merge bindings in correct order. If you have other bound clauses, you must put them after mergeBindings
:
$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
// ->where(..) wrong
->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder
// ->where(..) correct
->count();
I was facing this problem even with use Illuminate\Http\Request;
line at the top of my controller. Kept pulling my hair till I realized that I was doing $request::ip()
instead of $request->ip()
. Can happen to you if you didn't sleep all night and are looking at the code at 6am with half-opened eyes.
Hope this helps someone down the road.
Use requests.packages.urllib3.disable_warnings()
and verify=False
on requests
methods.
import requests
from urllib3.exceptions import InsecureRequestWarning
# Suppress only the single warning from urllib3 needed.
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
# Set `verify=False` on `requests.post`.
requests.post(url='https://example.com', data={'bar':'baz'}, verify=False)
You can't search LONGs directly. LONGs can't appear in the WHERE clause. They can appear in the SELECT list though so you can use that to narrow down the number of rows you'd have to examine.
Oracle has recommended converting LONGs to CLOBs for at least the past 2 releases. There are fewer restrictions on CLOBs.
Use Json
class instead of Content
as shown following:
// When I want to return an error:
if (!isFileSupported)
{
Response.StatusCode = (int) HttpStatusCode.BadRequest;
return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
}
else
{
// When I want to return sucess:
Response.StatusCode = (int)HttpStatusCode.OK;
return Json("Message sent!", MediaTypeNames.Text.Plain);
}
Also set contentType:
contentType: 'application/json; charset=utf-8',
To be verbose it the removal of extension is demonstrated for workbooks.. which now have a variety of extensions . . a new unsaved Book1 has no ext . works the same for files
Function WorkbookIsOpen(FWNa$, Optional AnyExt As Boolean = False) As Boolean
Dim wWB As Workbook, WBNa$, PD%
FWNa = Trim(FWNa)
If FWNa <> "" Then
For Each wWB In Workbooks
WBNa = wWB.Name
If AnyExt Then
PD = InStr(WBNa, ".")
If PD > 0 Then WBNa = Left(WBNa, PD - 1)
PD = InStr(FWNa, ".")
If PD > 0 Then FWNa = Left(FWNa, PD - 1)
'
' the alternative of using split.. see commented out below
' looks neater but takes a bit longer then the pair of instr and left
' VBA does about 800,000 of these small splits/sec
' and about 20,000,000 Instr Lefts per sec
' of course if not checking for other extensions they do not matter
' and to any reasonable program
' THIS DISCUSSIONOF TIME TAKEN DOES NOT MATTER
' IN doing about doing 2000 of this routine per sec
' WBNa = Split(WBNa, ".")(0)
'FWNa = Split(FWNa, ".")(0)
End If
If WBNa = FWNa Then
WorkbookIsOpen = True
Exit Function
End If
Next wWB
End If
End Function
Use:
L = ['Thanks You', 'Its fine no problem', 'Are you sure']
#create new df
df = pd.DataFrame({'col':L})
print (df)
col
0 Thanks You
1 Its fine no problem
2 Are you sure
df = pd.DataFrame({'oldcol':[1,2,3]})
#add column to existing df
df['col'] = L
print (df)
oldcol col
0 1 Thanks You
1 2 Its fine no problem
2 3 Are you sure
Thank you DYZ:
#default column name 0
df = pd.DataFrame(L)
print (df)
0
0 Thanks You
1 Its fine no problem
2 Are you sure
If you meant just ABC as simple value, answer above is the one that works fine.
If you meant concatenation of values of rows that are not selected by your main query, you will need to use a subquery.
Something like this may work:
SELECT t1.col1,
t1.col2,
(SELECT GROUP_CONCAT(col2 SEPARATOR '') FROM Table1 t2 WHERE t2.col1 != 0) as col3
FROM Table1 t1
WHERE t1.col1 = 0;
Actual syntax maybe a bit off though
sed is a stream editor. I would say try man sed.If you didn't find this man page in your system refer this URL:
Through
remove_column :table_name, :column_name
in a migration file
You can remove a column directly in a rails console by typing:
ActiveRecord::Base.remove_column :table_name, :column_name
I just remove the outline from all the tags in the page by selecting all and applying outline:none to everything:)
*:focus {outline:none}
As bagofcole mentioned, you might need to add !important as well, so the style will look like this:
*:focus {outline:none !important}
I had the same problem, there was no extension=php_soap.dll in my php.ini But this was because I had copied the php.ini from a old and previous php version (not a good idea). I found the dll in the ext directory so I just could put it myself into the php.ini extension=php_soap.dll After Apache restart all worked with soap :)
Step (1): smtp.EnableSsl = true;
if not enough:
Step (2): "Access for less secure apps" must be enabled for the Gmail account used by the NetworkCredential
using google's settings page: