Since it appears you are using jQuery, here is a jQuery solution.
$(function() {
$('#Eframe').on("mousewheel", function() {
alert($(document).scrollTop());
});
});
Not much to explain here. If you want, here is the jQuery documentation.
I would like to offer this general purpose template solution that expands on the correct solution provided by Yi Jiang's.
The additional benefits include:
In the html you place the following structure:
<div class="information_popup_container">
<div class="information">
<!-- The thing or things you want to hover over go here such as images, tables,
paragraphs, objects other divisions etc. -->
</div>
<div class="popup_information">
<!-- The thing or things you want to popup go here such as images, tables,
paragraphs, objects other divisions etc. -->
</div>
</div>
In the css you place the following structure:
div.information_popup_container {
position: absolute;
width:0px;
height:0px;
/* Position Information */
/* Appearance Information */
}
div.information_popup_container > div.information {
/* Position Information */
/* Appearance Information */
}
div.information_popup_container > div.popup_information {
position: fixed;
visibility: hidden;
/* Position Information */
/* Appearance Information */
}
div.information_popup_container > div.information:hover + div.popup_information {
visibility: visible;
z-index: 200;
}
As additional information. When the popup contains information that you might want to cut and paste or contains an object that you might want to interact with then first replace:
div.information_popup_container > div.information:hover + div.popup_information {
visibility: visible;
z-index: 200;
}
with
div.information_popup_container > div.information:hover + div.popup_information
,div.information_popup_container > div.popup_information:hover {
visibility: visible;
z-index: 200;
}
And second, adjust the position of div.popup so that there is an overlap with div.information. A few pixels is sufficient to ensure that the div.popup is can receive the hover when moving the cusor off div.information.
This does not work as expected with Internet Explorer 10.0.9200 and does work as expected with Opera 12.16, Firefox 18.0 and Google Chrome 28.0.15.
See fiddle http://jsfiddle.net/F68Le/ for a complete example with a popup multilevel menu.
Without a bit of information about what files are in your repository (pure source code, images, executables, ...), it's a bit hard to answer the question :)
Beside this, I'll consider that you're willing to default to LF as line endings in your working directory because you're willing to make sure that text files have LF line endings in your .git repository wether you work on Windows or Linux. Indeed better safe than sorry....
However, there's a better alternative: Benefit from LF line endings in your Linux workdir, CRLF line endings in your Windows workdir AND LF line endings in your repository.
As you're partially working on Linux and Windows, make sure core.eol
is set to native
and core.autocrlf
is set to true
.
Then, replace the content of your .gitattributes
file with the following
* text=auto
This will let Git handle the automagic line endings conversion for you, on commits and checkouts. Binary files won't be altered, files detected as being text files will see the line endings converted on the fly.
However, as you know the content of your repository, you may give Git a hand and help him detect text files from binary files.
Provided you work on a C based image processing project, replace the content of your .gitattributes
file with the following
* text=auto
*.txt text
*.c text
*.h text
*.jpg binary
This will make sure files which extension is c, h, or txt will be stored with LF line endings in your repo and will have native line endings in the working directory. Jpeg files won't be touched. All of the others will be benefit from the same automagic filtering as seen above.
In order to get a get a deeper understanding of the inner details of all this, I'd suggest you to dive into this very good post "Mind the end of your line" from Tim Clem, a Githubber.
As a real world example, you can also peek at this commit where those changes to a .gitattributes
file are demonstrated.
UPDATE to the answer considering the following comment
I actually don't want CRLF in my Windows directories, because my Linux environment is actually a VirtualBox sharing the Windows directory
Makes sense. Thanks for the clarification. In this specific context, the .gitattributes
file by itself won't be enough.
Run the following commands against your repository
$ git config core.eol lf
$ git config core.autocrlf input
As your repository is shared between your Linux and Windows environment, this will update the local config file for both environment. core.eol
will make sure text files bear LF line endings on checkouts. core.autocrlf
will ensure potential CRLF in text files (resulting from a copy/paste operation for instance) will be converted to LF in your repository.
Optionally, you can help Git distinguish what is a text file by creating a .gitattributes
file containing something similar to the following:
# Autodetect text files
* text=auto
# ...Unless the name matches the following
# overriding patterns
# Definitively text files
*.txt text
*.c text
*.h text
# Ensure those won't be messed up with
*.jpg binary
*.data binary
If you decided to create a .gitattributes
file, commit it.
Lastly, ensure git status
mentions "nothing to commit (working directory clean)", then perform the following operation
$ git checkout-index --force --all
This will recreate your files in your working directory, taking into account your config changes and the .gitattributes
file and replacing any potential overlooked CRLF in your text files.
Once this is done, every text file in your working directory WILL bear LF line endings and git status
should still consider the workdir as clean.
To check whether some number n is in the inclusive range denoted by the two number a and b you do either
if a <= n <= b:
print "yes"
else:
print "no"
use the replace >=
and <=
with >
and <
to check whether n
is in the exclusive range denoted by a
and b
(i.e. a
and b
are not themselves members of the range).
Range will produce an arithmetic progression defined by the two (or three) arguments converted to integers. See the documentation. This is not what you want I guess.
public static string NumberToWords(int number)
{
if (number == 0)
return "zero";
if (number < 0)
return "minus " + NumberToWords(Math.Abs(number));
string words = "";
if ((number / 1000000) > 0)
{
words += NumberToWords(number / 1000000) + " million ";
number %= 1000000;
}
if ((number / 1000) > 0)
{
words += NumberToWords(number / 1000) + " thousand ";
number %= 1000;
}
if ((number / 100) > 0)
{
words += NumberToWords(number / 100) + " hundred ";
number %= 100;
}
if (number > 0)
{
if (words != "")
words += "and ";
var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
if (number < 20)
words += unitsMap[number];
else
{
words += tensMap[number / 10];
if ((number % 10) > 0)
words += "-" + unitsMap[number % 10];
}
}
return words;
}
How about this one-liner?
var isAndroid = /(android)/i.test(navigator.userAgent);
The i
modifier is used to perform case-insensitive matching.
Technique taken from Cordova AdMob test project: https://github.com/floatinghotpot/cordova-admob-pro/wiki/00.-How-To-Use-with-PhoneGap-Build
I think you mean to put the rolling of the random a,b,c, etc within the loop:
a = None # initialise
while not (a in winning_numbers):
# keep rolling an a until you get one not in winning_numbers
a = random.randint(1,30)
winning_numbers.append(a)
Otherwise, a
will be generated just once, and if it is in winning_numbers
already, it won't be added. Since the generation of a
is outside the while
(in your code), if a
is already in winning_numbers
then too bad, it won't be re-rolled, and you'll have one less winning number.
That could be what causes your error in if guess[i] == winning_numbers[i]
. (Your winning_numbers
isn't always of length 5).
jQuery lib has to be loaded first. In my case, i was loading bootstrap lib first, also tried tag with target and firing a click trigger. But the main issue was - jquery has to be loaded first.
None of above works for godaddy server centOS 6, apache 2.4, php 5.6
Instead, you should
Install the mbstring PHP Extension with EasyApache
check if you already have it by, putty or ssh
php -m | grep mbstring
[if nothing, means missing mbstring]
Now you need to goto godaddy your account page,
click manager server,
open whm ----- search for apache,
open "easy apache 4"(my case)
Now you need customize currently installed packages,
by
click "customize" button on top line next to "currently installed package..."
search mbstring,
click on/off toggle next to it.
click next, next, .... privision..done.
Now you should have mbstring
by check again at putty(ssh)
php -m | grep mbstring [should see mbstring]
or you can find mbstring at phpinfo() page
I know this isn't a direct answer to your question, but you could also consider using clip-path, as in this question: https://stackoverflow.com/a/18208889/23341.
Use curly brackets and put all the attributes you want to add inside
Example:
$('#objId').attr({
target: 'nw',
title: 'Opens in a new window'
});
Well, when writing it out to file, you do know what class T is, so you can store that in dump
. Then, when reading it back in, you can dynamically call it using reflection.
public JSONObject dump() throws JSONException {
JSONObject result = new JSONObject();
JSONArray a = new JSONArray();
for(T i : items){
a.put(i.dump());
// inside this i.dump(), store "class-name"
}
result.put("items", a);
return result;
}
public void load(JSONObject obj) throws JSONException {
JSONArray arrayItems = obj.getJSONArray("items");
for (int i = 0; i < arrayItems.length(); i++) {
JSONObject item = arrayItems.getJSONObject(i);
String className = item.getString("class-name");
try {
Class<?> clazzy = Class.forName(className);
T newItem = (T) clazzy.newInstance();
newItem.load(obj);
items.add(newItem);
} catch (InstantiationException e) {
// whatever
} catch (IllegalAccessException e) {
// whatever
} catch (ClassNotFoundException e) {
// whatever
}
}
The way I interpreted this question is needing the subtotal value of each group of answers. Subtotaling turns out to be very easy, using PARTITION
:
SUM(COUNT(0)) OVER (PARTITION BY [Grouping]) AS [MY_TOTAL]
This is what my full SQL call looks like:
SELECT MAX(GroupName) [name], MAX(AUX2)[type],
COUNT(0) [count], SUM(COUNT(0)) OVER(PARTITION BY GroupId) AS [total]
FROM [MyView]
WHERE Active=1 AND Type='APP' AND Completed=1
AND [Date] BETWEEN '01/01/2014' AND GETDATE()
AND Id = '5b9xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' AND GroupId IS NOT NULL
GROUP BY AUX2, GroupId
The data returned from this looks like:
name type count total
Training Group 2 Cancelation 1 52
Training Group 2 Completed 41 52
Training Group 2 No Show 6 52
Training Group 2 Rescheduled 4 52
Training Group 3 NULL 4 10535
Training Group 3 Cancelation 857 10535
Training Group 3 Completed 7923 10535
Training Group 3 No Show 292 10535
Training Group 3 Rescheduled 1459 10535
Training Group 4 Cancelation 2 27
Training Group 4 Completed 24 27
Training Group 4 Rescheduled 1 27
The best way to Load JSON Data into Dictionary is You can user the inbuilt json loader.
Below is the sample snippet that can be used.
import json
f = open("data.json")
data = json.load(f))
f.close()
type(data)
print(data[<keyFromTheJsonFile>])
I recently ran into this problem and didn't find any of the answers very relevant so I decided to make a SO account for this.
Solution 1: Convert your .ico
File online there are a lot of site out there
Solution 2: Convert .ico
File in photoshop
If you or your Editor just renamed your image file to *.ico
then it is not going to work.
If you see the image icon from your Windows/OS folder then it is working
Context.getResources().getDimension(int id);
All the former answers seem to be outdated.
conda activate
was introduced in conda
4.4 and 4.6.
conda activate
: The logic and mechanisms underlying environment activation have been reworked. With conda 4.4,conda activate
andconda deactivate
are now the preferred commands for activating and deactivating environments. You’ll find they are much more snappy than thesource activate
andsource deactivate
commands from previous conda versions. Theconda activate
command also has advantages of (1) being universal across all OSes, shells, and platforms, and (2) not having path collisions with scripts from other packages like python virtualenv’s activate script.
Examples
conda create -n venv-name python=3.6
conda activate -n venv-name
conda deactivate
These new sub-commands are available in "Aanconda Prompt" and "Anaconda Powershell Prompt" automatically. To use conda activate
in every shell (normal cmd.exe
and powershell), check expose conda
command in every shell on Windows.
References
Alternatively you could read you csv with header=None
and then add it with df.columns
:
Cov = pd.read_csv("path/to/file.txt", sep='\t', header=None)
Cov.columns = ["Sequence", "Start", "End", "Coverage"]
Data can be transferred in SOAP header (JaxWS) by using @WebParam(header = true):
@WebMethod(operationName = "SendRequest", action = "http://abcd.ru/")
@Oneway
public void sendRequest(
@WebParam(name = "Message", targetNamespace = "http://abcd.ru/", partName = "Message")
Data message,
@WebParam(name = "ServiceHeader", targetNamespace = "http://abcd.ru/", header = true, partName = "ServiceHeader")
Header serviceHeader);
If you want to generate a client with SOAP Headers, you need to use -XadditionalHeaders:
wsimport -keep -Xnocompile -XadditionalHeaders -Xdebug http://12.34.56.78:8080/TestHeaders/somewsdl?wsdl -d /home/evgeny/DEVELOPMENT/JAVA/gen
If don't need @Oneway web service, you can use Holder:
@WebMethod(operationName = "SendRequest", action = "http://abcd.ru/")
public void sendRequest(
@WebParam(name = "Message", targetNamespace = "http://abcd.ru/", partName = "Message")
Data message,
@WebParam(name = "ServiceHeader", targetNamespace = "http://abcd.ru/", header = true, partName = "ServiceHeader")
Holder<Header> serviceHeader);
You can try use in javascript:
window.onload = function() {
alert("let's go!");
}
Its a good practice separate javascript of html
There's talk about interoperability between C and Go when using the gcc Go compiler, gccgo. There are limitations both to the interoperability and the implemented feature set of Go when using gccgo, however (e.g., limited goroutines, no garbage collection).
Many of the other solutions will work, but they all make use of the open-toolchain for the iPhone SDK. So, yes, you can write software for the iPhone on other platforms... BUT...
Since you specify that you want your app to end up on the App Store, then, no, there's not really any way to do this. There's certainly no time effective way to do this. Even if you only value your own time at $20/hr, it will be far more efficient to buy a used intel Mac, and download the free SDK.
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
That's because your hidden fields have duplicate IDs, so jQuery only returns the first in the set. Give them classes instead, like .uid
and grab them via:
var uids = $(".uid").map(function() {
return this.value;
}).get();
Demo: http://jsfiddle.net/karim79/FtcnJ/
EDIT: say your output looks like the following (notice, IDs have changed to classes)
<fieldset><legend>John Smith</legend>
<img src='foo.jpg'/><br>
<a href="#" class="aaf">add as friend</a>
<input name="uid" type="hidden" value='<?php echo $row->uid;?>' class="uid">
</fieldset>
You can target the 'uid' relative to the clicked anchor like this:
$("a.aaf").click(function() {
alert($(this).next('.uid').val());
});
Important: do not have any duplicate IDs. They will cause problems. They are invalid, bad and you should not do it.
A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.
This happened to me because I had moved the following line close to the beginning of the .csproj file:
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets"/>
It needs to be placed after the PropertyGroups that define your Configuration|Platform.
Note that by storing any state from the current ApplicationContext
, or the ApplicationContext
itself in a static variable - for example using the singleton pattern - you will make your tests unstable and unpredictable if you're using Spring-test. This is because Spring-test caches and reuses application contexts in the same JVM. For example:
@ContextConfiguration({"classpath:foo.xml"})
. @ContextConfiguration({"classpath:foo.xml", "classpath:bar.xml})
@ContextConfiguration({"classpath:foo.xml"})
When Test A runs, an ApplicationContext
is created, and any beans implemeting ApplicationContextAware
or autowiring ApplicationContext
might write to the static variable.
When Test B runs the same thing happens, and the static variable now points to Test B's ApplicationContext
When Test C runs, no beans are created as the TestContext
(and herein the ApplicationContext
) from Test A is resused. Now you got a static variable pointing to another ApplicationContext
than the one currently holding the beans for your test.
The easiest answer is number_format()
.
echo "$ ".number_format($value, 2);
If you want your application to be able to work with multiple currencies and locale-aware formatting (1.000,00
for some of us Europeans for example), it becomes a bit more complex.
There is money_format()
but it doesn't work on Windows and relies on setlocale()
, which is rubbish in my opinion, because it requires the installation of (arbitrarily named) locale packages on server side.
If you want to seriously internationalize your application, consider using a full-blown internationalization library like Zend Framework's Zend_Locale and Zend_Currency.
You could also try to add a key mapping witch auto select all the code in file and indent it:
'atom-text-editor':
'ctrl-alt-l': 'auto-indent:apply'
You could iterate through your methods...
for m in [do_smth1, do_smth2]:
try:
m()
except:
pass
Basic :
CREATE TABLE table1 (
columnA INTEGER NOT NULL,
columnB INTEGER NOT NULL,
PRIMARY KEY (columnA, columnB)
);
If your columns are foreign keys of other tables (common case) :
CREATE TABLE table1 (
table2_id INTEGER NOT NULL,
table3_id INTEGER NOT NULL,
FOREIGN KEY (table2_id) REFERENCES table2(id),
FOREIGN KEY (table3_id) REFERENCES table3(id),
PRIMARY KEY (table2_id, table3_id)
);
CREATE TABLE table2 (
id INTEGER NOT NULL,
PRIMARY KEY id
);
CREATE TABLE table3 (
id INTEGER NOT NULL,
PRIMARY KEY id
);
I used postman chrome extension until it became deprecated. Chrome extension also less usable and powerful then native postman application. So, it became not very convenient to use chrome extension. I have found next approach:
Ctrl + 7 to comment a selected text.
Here's some more benchmarks for Docker based memcached server
versus host native memcached server
using Twemperf benchmark tool https://github.com/twitter/twemperf with 5000 connections and 20k connection rate
Connect time overhead for docker based memcached seems to agree with above whitepaper at roughly twice native speed.
Twemperf Docker Memcached
Connection rate: 9817.9 conn/s
Connection time [ms]: avg 341.1 min 73.7 max 396.2 stddev 52.11
Connect time [ms]: avg 55.0 min 1.1 max 103.1 stddev 28.14
Request rate: 83942.7 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 83942.7 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 28.6 min 1.2 max 65.0 stddev 0.01
Response time [ms]: p25 24.0 p50 27.0 p75 29.0
Response time [ms]: p95 58.0 p99 62.0 p999 65.0
Twemperf Centmin Mod Memcached
Connection rate: 11419.3 conn/s
Connection time [ms]: avg 200.5 min 0.6 max 263.2 stddev 73.85
Connect time [ms]: avg 26.2 min 0.0 max 53.5 stddev 14.59
Request rate: 114192.6 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 114192.6 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 17.4 min 0.0 max 28.8 stddev 0.01
Response time [ms]: p25 12.0 p50 20.0 p75 23.0
Response time [ms]: p95 28.0 p99 28.0 p999 29.0
Here's bencmarks using memtier benchmark tool
memtier_benchmark docker Memcached
4 Threads
50 Connections per thread
10000 Requests per thread
Type Ops/sec Hits/sec Misses/sec Latency KB/sec
------------------------------------------------------------------------
Sets 16821.99 --- --- 1.12600 2271.79
Gets 168035.07 159636.00 8399.07 1.12000 23884.00
Totals 184857.06 159636.00 8399.07 1.12100 26155.79
memtier_benchmark Centmin Mod Memcached
4 Threads
50 Connections per thread
10000 Requests per thread
Type Ops/sec Hits/sec Misses/sec Latency KB/sec
------------------------------------------------------------------------
Sets 28468.13 --- --- 0.62300 3844.59
Gets 284368.51 266547.14 17821.36 0.62200 39964.31
Totals 312836.64 266547.14 17821.36 0.62200 43808.90
You'd be much better off using the same array with both lists, and creating angular filters to achieve your goal.
http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters
Rough, untested code follows:
appModule.filter('checked', function() {
return function(input, checked) {
if(!input)return input;
var output = []
for (i in input){
var item = input[i];
if(item.checked == checked)output.push(item);
}
return output
}
});
and the view (i added an "uncheck" button too)
<div id="AddItem">
<h3>Add Item</h3>
<input value="1" type="number" placeholder="1" ng-model="itemAmount">
<input value="" type="text" placeholder="Name of Item" ng-model="itemName">
<br/>
<button ng-click="addItem()">Add to list</button>
</div>
<!-- begin: LIST OF CHECKED ITEMS -->
<div id="CheckedList">
<h3>Checked Items: {{getTotalCheckedItems()}}</h3>
<h4>Checked:</h4>
<table>
<tr ng-repeat="item in items | checked:true" class="item-checked">
<td><b>amount:</b> {{item.amount}} -</td>
<td><b>name:</b> {{item.name}} -</td>
<td>
<i>this item is checked!</i>
<button ng-click="item.checked = false">uncheck item</button>
</td>
</tr>
</table>
</div>
<!-- end: LIST OF CHECKED ITEMS -->
<!-- begin: LIST OF UNCHECKED ITEMS -->
<div id="UncheckedList">
<h3>Unchecked Items: {{getTotalItems()}}</h3>
<h4>Unchecked:</h4>
<table>
<tr ng-repeat="item in items | checked:false" class="item-unchecked">
<td><b>amount:</b> {{item.amount}} -</td>
<td><b>name:</b> {{item.name}} -</td>
<td>
<button ng-click="item.checked = true">check item</button>
</td>
</tr>
</table>
</div>
<!-- end: LIST OF ITEMS -->
Then you dont need the toggle methods etc in your controller
Some systems like Ubuntu, mysql is using by default the UNIX auth_socket plugin.
Basically means that: db_users using it, will be "auth" by the system user credentias. You can see if your root
user is set up like this by doing the following:
$ sudo mysql -u root # I had to use "sudo" since is new installation
mysql> USE mysql;
mysql> SELECT User, Host, plugin FROM mysql.user;
+------------------+-----------------------+
| User | plugin |
+------------------+-----------------------+
| root | auth_socket |
| mysql.sys | mysql_native_password |
| debian-sys-maint | mysql_native_password |
+------------------+-----------------------+
As you can see in the query, the root
user is using the auth_socket
plugin
There are 2 ways to solve this:
mysql_native_password
plugindb_user
with you system_user
(recommended)Option 1:
$ sudo mysql -u root # I had to use "sudo" since is new installation
mysql> USE mysql;
mysql> UPDATE user SET plugin='mysql_native_password' WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> exit;
$ sudo service mysql restart
Option 2: (replace YOUR_SYSTEM_USER with the username you have)
$ sudo mysql -u root # I had to use "sudo" since is new installation
mysql> USE mysql;
mysql> CREATE USER 'YOUR_SYSTEM_USER'@'localhost' IDENTIFIED BY 'YOUR_PASSWD';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'YOUR_SYSTEM_USER'@'localhost';
mysql> UPDATE user SET plugin='auth_socket' WHERE User='YOUR_SYSTEM_USER';
mysql> FLUSH PRIVILEGES;
mysql> exit;
$ sudo service mysql restart
Remember that if you use option #2 you'll have to connect to mysql as your system username (mysql -u YOUR_SYSTEM_USER
)
Note: On some systems (e.g., Debian stretch) 'auth_socket' plugin is called 'unix_socket', so the corresponding SQL command should be: UPDATE user SET plugin='unix_socket' WHERE User='YOUR_SYSTEM_USER';
Update:
from @andy's comment seems that mysql 8.x.x updated/replaced the auth_socket
for caching_sha2_password
I don't have a system setup with mysql 8.x.x to test this, however the steps above should help you to understand the issue. Here's the reply:
One change as of MySQL 8.0.4 is that the new default authentication plugin is 'caching_sha2_password'. The new 'YOUR_SYSTEM_USER' will have this auth plugin and you can login from the bash shell now with "mysql -u YOUR_SYSTEM_USER -p" and provide the password for this user on the prompt. No need for the "UPDATE user SET plugin" step. For the 8.0.4 default auth plugin update see, https://mysqlserverteam.com/mysql-8-0-4-new-default-authentication-plugin-caching_sha2_password/
url-pattern
is used in web.xml
to map your servlet
to specific URL. Please see below xml code, similar code you may find in your web.xml
configuration file.
<servlet>
<servlet-name>AddPhotoServlet</servlet-name> //servlet name
<servlet-class>upload.AddPhotoServlet</servlet-class> //servlet class
</servlet>
<servlet-mapping>
<servlet-name>AddPhotoServlet</servlet-name> //servlet name
<url-pattern>/AddPhotoServlet</url-pattern> //how it should appear
</servlet-mapping>
If you change url-pattern
of AddPhotoServlet
from /AddPhotoServlet
to /MyUrl
. Then, AddPhotoServlet
servlet can be accessible by using /MyUrl
. Good for the security reason, where you want to hide your actual page URL.
Java Servlet url-pattern
Specification:
- A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
- A string beginning with a '*.' prefix is used as an extension mapping.
- A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
- All other strings are used for exact matches only.
Reference : Java Servlet Specification
You may also read this Basics of Java Servlet
Use the -k
option (or --key=POS1[,POS2]
). It can appear multiple times and each key can have global options (such as n
for numeric sort)
In your case, expand columns of that database in the object explorer. Drag the columns in to the query area.
And then just delete one or two columns which you don't want and then run it. I'm open to any suggestions easier than this.
Symfony is smart and knows how to make the find()
by itself :
public function deleteGuestAction(Guest $guest)
{
if (!$guest) {
throw $this->createNotFoundException('No guest found');
}
$em = $this->getDoctrine()->getEntityManager();
$em->remove($guest);
$em->flush();
return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}
To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}
Consider using Universal Image Loader library by Sergey Tarasevich. It comes with:
Universal Image Loader allows detailed cache management for downloaded images, with the following cache configurations:
UsingFreqLimitedMemoryCache
: The least frequently used bitmap is deleted when the cache size limit is exceeded.LRULimitedMemoryCache
: The least recently used bitmap is deleted when the cache size limit is exceeded.FIFOLimitedMemoryCache
: The FIFO rule is used for deletion when the cache size limit is exceeded.LargestLimitedMemoryCache
: The largest bitmap is deleted when the cache size limit is exceeded.LimitedAgeMemoryCache
: The Cached object is deleted when its age exceeds defined value.WeakMemoryCache
: A memory cache with only weak references to bitmaps.A simple usage example:
ImageView imageView = groupView.findViewById(R.id.imageView);
String imageUrl = "http://site.com/image.png";
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
imageLoader.displayImage(imageUrl, imageView);
This example uses the default UsingFreqLimitedMemoryCache
.
Keep it super simple:
jQuery Event Listener Way:
$(window).on('wheel', function(){
whichDirection(event);
});
Vanilla JavaScript Event Listener Way:
if(window.addEventListener){
addEventListener('wheel', whichDirection, false);
} else if (window.attachEvent) {
attachEvent('wheel', whichDirection, false);
}
Function Remains The Same:
function whichDirection(event){
console.log(event + ' WheelEvent has all kinds of good stuff to work with');
var scrollDirection = event.deltaY;
if(scrollDirection === 1){
console.log('meet me at the club, going down', scrollDirection);
} else if(scrollDirection === -1) {
console.log('Going up, on a tuesday', scrollDirection);
}
}
I wrote a more indepth post on it here ???????
This worked for me:
1. Exit Visual Studio
2. Open a command window and navigate to the folder: "%localappdata%\Local\Microsoft\Team Foundation\"
3. Navigate to the sub folders for every version and delete the sub folder "cache" and its contents
4. Restart Visual Studio and connect to TFS.
5. Test the Get Latest Version.
Use the Array.prototype.push
method to append values to the end of an array:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
console.log(arr);
_x000D_
You can use the push()
function to append more than one value to an array in a single call:
// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];
// append multiple values to the array
arr.push("Salut", "Hey");
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
_x000D_
Update
If you want to add the items of one array to another array, you can use firstArray.concat(secondArray)
:
var arr = [
"apple",
"banana",
"cherry"
];
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
_x000D_
Update
Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift
for this purpose.
var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);
_x000D_
It also supports appending multiple values at once just like push
.
Update
Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended, compliant with the spirit of functional programming.
const arr = [
"Hi",
"Hello",
"Bonjour",
];
const newArr = [
...arr,
"Salut",
];
console.log(newArr);
_x000D_
In some websites, XMLHttpRequest
may send you something like <script src="#"></srcipt>
. In that case, try using a HTML document like the script under:
<html>
<body>
<iframe src="website.com"></iframe>
<script src="your_JS"></script>
</body>
</html>
Now you can use JS to get some text out of the HTML, such as getElementbyId
.
But this may not work for some websites with cross-domain blocking.
Also, using the StringBuilder.AppendLine method.
Submit a form that contains an input with value of canvas toDataURL('image/png') e.g
//JAVASCRIPT
var canvas = document.getElementById("canvas");
var url = canvas.toDataUrl('image/png');
Insert the value of the url to your hidden input on form element.
//PHP
$data = $_POST['photo'];
$data = str_replace('data:image/png;base64,', '', $data);
$data = base64_decode($data);
file_put_contents("i". rand(0, 50).".png", $data);
Antonio's answer
CONCAT(REPLACE(FORMAT(number,0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))
is wrong; it may produce incorrect results!
For example, if "number" is 12345.67, the resulting string would be:
'12.346,67'
instead of
'12.345,67'
because FORMAT(number,0) rounds "number" up if fractional part is greater or equal than 0.5 (as it is in my example)!
What you COULD use is
CONCAT(REPLACE(FORMAT(FLOOR(number),0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))
if your MySQL/MariaDB's FORMAT doesn't support "locale_name" (see MindStalker's post - Thx 4 that, pal). Note the FLOOR function I've added.
For OpenSuse Linux, One can simply install the java-binfmt package in the zypper repository as shown below:
sudo zypper in java-binfmt-misc
chmod 755 file.jar
./file.jar
There are multiple schemas for "JUnit" and "xUnit" results.
model/xsd
)Please note that there are several versions of the schema in use by the Jenkins xunit-plugin (the current latest version is junit-10.xsd
which adds support for Erlang/OTP Junit format).
Some testing frameworks as well as "xUnit"-style reporting plugins also use their own secret sauce to generate "xUnit"-style reports, those may not use a particular schema (please read: they try to but the tools may not validate against any one schema). Python unittests in Jenkins? gives a quick comparison of several of these libraries and slight differences between the xml reports generated.
try {
String text = "Hello, Admin sir";// Replace with your message.
String toNumber = "xxxxxxxxxxxx"; // Replace with mobile phone number without +Sign or leading zeros, but with country code
//Suppose your country is India and your phone number is “xxxxxxxxxx”, then you need to send “91xxxxxxxxxx”.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://api.whatsapp.com/send?phone=" + toNumber + "&text=" + text));
context.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.whatsapp")));
}
Checked Exceptions :
The exceptions which are checked by the compiler for smooth execution of the program at runtime are called Checked Exception.
These occur at compile time.
All subclasses of Exception class except RuntimeException are Checked Exception.
Hypothetical Example - Suppose you are leaving your house for the exam, but if you check whether you took your Hall Ticket at home(compile time) then there won't be any problem at Exam Hall(runtime).
Unchecked Exception :
The exceptions which are not checked by the compiler are called Unchecked Exceptions.
These occur at runtime.
If these exceptions are not handled properly, they don’t give compile time error. But the program will be terminated prematurely at runtime.
All subclasses of RunTimeException and Error are unchecked exceptions.
Hypothetical Example - Suppose you are in your exam hall but somehow your school had a fire accident (means at runtime) where you can't do anything at that time but precautions can be made before (compile time).
For the people looking for regular polygons:
function regPolyPath(r,p,ctx){ //Radius, #points, context
//Azurethi was here!
ctx.moveTo(r,0);
for(i=0; i<p+1; i++){
ctx.rotate(2*Math.PI/p);
ctx.lineTo(r,0);
}
ctx.rotate(-2*Math.PI/p);
}
Use:
//Get canvas Context
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.translate(60,60); //Moves the origin to what is currently 60,60
//ctx.rotate(Rotation); //Use this if you want the whole polygon rotated
regPolyPath(40,6,ctx); //Hexagon with radius 40
//ctx.rotate(-Rotation); //remember to 'un-rotate' (or save and restore)
ctx.stroke();
From my understanding, a typical ANSI color code
"\033[{FORMAT_ATTRIBUTE};{FORGROUND_COLOR};{BACKGROUND_COLOR}m{TEXT}\033[{RESET_FORMATE_ATTRIBUTE}m"
is composed of (name and codec)
FORMAT ATTRIBUTE
{ "Default", "0" },
{ "Bold", "1" },
{ "Dim", "2" },
{ "Underlined", "3" },
{ "Blink", "5" },
{ "Reverse", "7" },
{ "Hidden", "8" }
FORGROUND COLOR
{ "Default", "39" },
{ "Black", "30" },
{ "Red", "31" },
{ "Green", "32" },
{ "Yellow", "33" },
{ "Blue", "34" },
{ "Magenta", "35" },
{ "Cyan", "36" },
{ "Light Gray", "37" },
{ "Dark Gray", "90" },
{ "Light Red", "91" },
{ "Light Green", "92" },
{ "Light Yellow", "93" },
{ "Light Blue", "94" },
{ "Light Magenta", "95" },
{ "Light Cyan", "96" },
{ "White", "97" }
BACKGROUND COLOR
{ "Default", "49" },
{ "Black", "40" },
{ "Red", "41" },
{ "Green", "42" },
{ "Yellow", "43" },
{ "Blue", "44" },
{ "Megenta", "45" },
{ "Cyan", "46" },
{ "Light Gray", "47" },
{ "Dark Gray", "100" },
{ "Light Red", "101" },
{ "Light Green", "102" },
{ "Light Yellow", "103" },
{ "Light Blue", "104" },
{ "Light Magenta", "105" },
{ "Light Cyan", "106" },
{ "White", "107" }
TEXT
RESET FORMAT ATTRIBUTE
{ "All", "0" },
{ "Bold", "21" },
{ "Dim", "22" },
{ "Underlined", "24" },
{ "Blink", "25" },
{ "Reverse", "27" },
{ "Hidden", "28" }
With this information, it is easy to colorize a string "I am a banana!" with forground color "Yellow" and background color "Green" like this
"\033[0;33;42mI am a Banana!\033[0m"
Or with a C++ library colorize
auto const& colorized_text = color::rize( "I am a banana!", "Yellow", "Green" );
std::cout << colorized_text << std::endl;
Also you can use
<select ng-change="updateValue(user, oldValue)"
ng-init="oldValue=0"
ng-focus="oldValue=user.id"
ng-model="user.id" ng-options="user.id as user.name for user in users">
</select>
Not exactly for this OP, but for those who encountered 404 and cannot set response content-type
to "application/json"
(any content-type
). One possibility is a server actually responds 406 but explorer (e.g., chrome) prints it as 404.
If you do not customize message converter, spring would use AbstractMessageConverterMethodProcessor.java
. It would run:
List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request, valueType, declaredType);
and if they do not have any overlapping (the same item), it would throw HttpMediaTypeNotAcceptableException
and this finally causes 406. No matter if it is an ajax, or GET/POST, or form action, if the request uri ends with a .html
or any suffix, the requestedMediaTypes
would be "text/[that suffix]", and this conflicts with producibleMediaTypes
, which is usually:
"application/json"
"application/xml"
"text/xml"
"application/*+xml"
"application/json"
"application/*+json"
"application/json"
"application/*+json"
"application/xml"
"text/xml"
"application/*+xml"
"application/xml"
"text/xml"
"application/*+xml"
When I need this kind of functionality in Java, I usually use the Observer pattern. It does imply an extra object, but I think it's a clean way to go, and is a widely understood pattern, which helps with code readability.
The A div can actually be made without :before
or :after
selector but using linear gradient as your first try. The only difference is that you must specify 4 positions. Dark grey from 0 to 50% and ligth grey from 50% to 100% like this:
background: linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%);
As you know, B div is made from a linear gradient having 2 positions like this:
background: linear-gradient(to right, #9c9e9f 0%,#f6f6f6 100%);
For the C div, i use the same kind of gradient as div A ike this:
background: linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%);
But this time i used the :after
selector with a white background like if the second part of your div was smaller. * Please note that I added a better alternative below.
Check this jsfiddle or the snippet below for complete cross-browser code.
div{_x000D_
position:relative;_x000D_
width:80%;_x000D_
height:100px;_x000D_
color:red;_x000D_
text-align:center;_x000D_
line-height:100px;_x000D_
margin-bottom:10px;_x000D_
}_x000D_
_x000D_
.a{_x000D_
background: #9c9e9f; /* Old browsers */_x000D_
background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%); /* FF3.6+ */_x000D_
background: -webkit-gradient(linear, left top, right top, color-stop(0%,#9c9e9f), color-stop(50%,#9c9e9f), color-stop(50%,#f6f6f6), color-stop(100%,#f6f6f6)); /* Chrome,Safari4+ */_x000D_
background: -webkit-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* Chrome10+,Safari5.1+ */_x000D_
background: -o-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* Opera 11.10+ */_x000D_
background: -ms-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* IE10+ */_x000D_
background: linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* W3C */_x000D_
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6',GradientType=1 ); /* IE6-9 */_x000D_
}_x000D_
_x000D_
.b{_x000D_
background: #9c9e9f; /* Old browsers */_x000D_
background: -moz-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%); /* FF3.6+ */_x000D_
background: -webkit-gradient(linear, left top, right top, color-stop(0%,#9c9e9f), color-stop(100%,#f6f6f6)); /* Chrome,Safari4+ */_x000D_
background: -webkit-linear-gradient(left, #9c9e9f 0%,#f6f6f6 100%); /* Chrome10+,Safari5.1+ */_x000D_
background: -o-linear-gradient(left, #9c9e9f 0%,#f6f6f6 100%); /* Opera 11.10+ */_x000D_
background: -ms-linear-gradient(left, #9c9e9f 0%,#f6f6f6 100%); /* IE10+ */_x000D_
background: linear-gradient(to right, #9c9e9f 0%,#f6f6f6 100%); /* W3C */_x000D_
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6',GradientType=1 ); /* IE6-9 */_x000D_
}_x000D_
_x000D_
.c{ _x000D_
background: #9c9e9f; /* Old browsers */_x000D_
background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #33ccff 50%, #33ccff 100%); /* FF3.6+ */_x000D_
background: -webkit-gradient(linear, left top, right top, color-stop(0%,#9c9e9f), color-stop(50%,#9c9e9f), color-stop(50%,#33ccff), color-stop(100%,#33ccff)); /* Chrome,Safari4+ */_x000D_
background: -webkit-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* Chrome10+,Safari5.1+ */_x000D_
background: -o-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* Opera 11.10+ */_x000D_
background: -ms-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* IE10+ */_x000D_
background: linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* W3C */_x000D_
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#33ccff',GradientType=1 ); /* IE6-9 */_x000D_
}_x000D_
.c:after{_x000D_
content:"";_x000D_
position:absolute;_x000D_
right:0;_x000D_
bottom:0;_x000D_
width:50%;_x000D_
height:20%;_x000D_
background-color:white;_x000D_
}
_x000D_
<div class="a">A</div>_x000D_
<div class="b">B</div>_x000D_
<div class="c">C</div>
_x000D_
There is also an alternative for the C div without using a white background to hide the a part of the second section.
Instead, we make the second part transparent and we use the :after
selector to act as a colored background with the desired position and size.
See this jsfiddle or the snippet below for this updated solution.
div {_x000D_
position: relative;_x000D_
width: 80%;_x000D_
height: 100px;_x000D_
color: red;_x000D_
text-align: center;_x000D_
line-height: 100px;_x000D_
margin-bottom: 10px;_x000D_
}_x000D_
_x000D_
.a {_x000D_
background: #9c9e9f;_x000D_
/* Old browsers */_x000D_
background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
/* FF3.6+ */_x000D_
background: -webkit-gradient(linear, left top, right top, color-stop(0%, #9c9e9f), color-stop(50%, #9c9e9f), color-stop(50%, #f6f6f6), color-stop(100%, #f6f6f6));_x000D_
/* Chrome,Safari4+ */_x000D_
background: -webkit-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
/* Chrome10+,Safari5.1+ */_x000D_
background: -o-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
/* Opera 11.10+ */_x000D_
background: -ms-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
/* IE10+ */_x000D_
background: linear-gradient(to right, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
/* W3C */_x000D_
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6', GradientType=1);_x000D_
/* IE6-9 */_x000D_
}_x000D_
_x000D_
.b {_x000D_
background: #9c9e9f;_x000D_
/* Old browsers */_x000D_
background: -moz-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%);_x000D_
/* FF3.6+ */_x000D_
background: -webkit-gradient(linear, left top, right top, color-stop(0%, #9c9e9f), color-stop(100%, #f6f6f6));_x000D_
/* Chrome,Safari4+ */_x000D_
background: -webkit-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%);_x000D_
/* Chrome10+,Safari5.1+ */_x000D_
background: -o-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%);_x000D_
/* Opera 11.10+ */_x000D_
background: -ms-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%);_x000D_
/* IE10+ */_x000D_
background: linear-gradient(to right, #9c9e9f 0%, #f6f6f6 100%);_x000D_
/* W3C */_x000D_
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6', GradientType=1);_x000D_
/* IE6-9 */_x000D_
}_x000D_
_x000D_
.c {_x000D_
background: #9c9e9f;_x000D_
/* Old browsers */_x000D_
background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
/* FF3.6+ */_x000D_
background: -webkit-gradient(linear, left top, right top, color-stop(0%, #9c9e9f), color-stop(50%, #9c9e9f), color-stop(50%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0)));_x000D_
/* Chrome,Safari4+ */_x000D_
background: -webkit-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
/* Chrome10+,Safari5.1+ */_x000D_
background: -o-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
/* Opera 11.10+ */_x000D_
background: -ms-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
/* IE10+ */_x000D_
background: linear-gradient(to right, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
/* W3C */_x000D_
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#ffffff00', GradientType=1);_x000D_
/* IE6-9 */_x000D_
}_x000D_
_x000D_
.c:after {_x000D_
content: "";_x000D_
position: absolute;_x000D_
right: 0;_x000D_
top: 0;_x000D_
width: 50%;_x000D_
height: 80%;_x000D_
background-color: #33ccff;_x000D_
z-index: -1_x000D_
}
_x000D_
<div class="a">A</div>_x000D_
<div class="b">B</div>_x000D_
<div class="c">C</div>
_x000D_
You can use a LENGTH(that_string)
minus the number of characters
you want to remove in the SUBSTRING()
select perhaps or use the TRIM()
function.
// Simplest way
var originalContent = $('select').html();
$('select').change(function() {
$('select').html(originalContent); //Restore Original Content
$('select option[myfilter=1]').remove(); // Filter my options
});
You are better off doing...
<form onsubmit="return isValidForm()" />
If isValidForm()
returns false
, then your form doesn't submit.
You should also probably move your event handler from inline.
document.getElementById('my-form').onsubmit = function() {
return isValidForm();
};
I know this is a bit late, but if this helps anybody, I think you could add a column to your data that calculates if the probability is ">='PivotSheet'$D$2"
(reference a cell on the pivot table
sheet).
Then, add that column to your pivot table and use the new column as a true/false
filter.
You can then change the value stored in the referenced cell to update your probability threshold.
If I understood your question right, this may get you what you wanted. The filter value would be displayed on the sheet with the pivot and can be changed to suit any quick changes to your probability threshold. The T/F Filter can be labeled "Above/At Probability Threshold" or something like that.
I've used this to do something similar. It was handy to have the cell reference on the Pivot table sheet so I could update the value and refresh the pivot to quickly modify the results. The people I did that for couldn't make up their minds on what that threshold should be.
Most of the examples above show how to reuse an existing comparable object in the compareTo function. If you would like to implement your own compareTo when you want to compare two objects of the same class, say an AirlineTicket object that you would like to sort by price(less is ranked first), followed by number of stopover (again, less is ranked first), you would do the following:
class AirlineTicket implements Comparable<Cost>
{
public double cost;
public int stopovers;
public AirlineTicket(double cost, int stopovers)
{
this.cost = cost; this.stopovers = stopovers ;
}
public int compareTo(Cost o)
{
if(this.cost != o.cost)
return Double.compare(this.cost, o.cost); //sorting in ascending order.
if(this.stopovers != o.stopovers)
return this.stopovers - o.stopovers; //again, ascending but swap the two if you want descending
return 0;
}
}
you can use this solution it is working for me
<span th:text="${#objects.nullSafe(doctor?.cabinet?.name,'')}"></span>
There is a new index method called difference
. It returns the original columns, with the columns passed as argument removed.
Here, the result is used to remove columns B
and D
from df
:
df2 = df[df.columns.difference(['B', 'D'])]
Note that it's a set-based method, so duplicate column names will cause issues, and the column order may be changed.
Advantage over drop
: you don't create a copy of the entire dataframe when you only need the list of columns. For instance, in order to drop duplicates on a subset of columns:
# may create a copy of the dataframe
subset = df.drop(['B', 'D'], axis=1).columns
# does not create a copy the dataframe
subset = df.columns.difference(['B', 'D'])
df = df.drop_duplicates(subset=subset)
I'd start by using glob:
from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.gif'): #assuming gif
im=Image.open(filename)
image_list.append(im)
then do what you need to do with your list of images (image_list).
You're missing a GROUP BY clause:
SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id
The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.
With respect to other answers, it's not always there. Sometimes on setup process people forget to select the Web Developer Tools
.
In order to fix that, one should:
Programs and Features
find Visual Studios related version
there, click on it,Change
.
Then the setup window will appear, Web Developer Tools
there and continue to setup.It will download or use the setup media if exist. After the setup windows may restart, and you are ready to have fun with your Web Developer Tools
now.
using that code wil give you a responsive video player with full control
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" width="640" height="480" src="https://www.youtube-nocookie.com/embed/Lw_e0vF1IB4" frameborder="0" allowfullscreen></iframe>
</div>
I had the same problem. So here is the real answer: Mount the system under /proc
.
Here is my command:
mount -o rw,remount /proc /system
It works, and in fact is the only way I can overcome the Read-only System problem.
Ok, Im assuming you want to put the .left inside the container so I suggest you edit your html. The key is the position:absolute
and right:0
#right {
background-color: red;
height: 300px;
width: 300px;
z-index: 999999;
margin-top: 0px;
position: absolute;
right:0;
}
here is the full code: http://jsfiddle.net/T9FJL/
Replace that line with:
$("#someElement").click(function() {
window.location.href = window.location.href;
});
or:
$("#someElement").click(function() {
window.location.reload();
});
Personally, I use Charles for that kind of stuff.
When enabled, it will monitor every network request, displaying extended request details, including support for SSL and various request/reponse format, like JSON, etc...
You can also configure it to sniff only requests to specific servers, not the whole traffic.
It's commercial software, but there is a trial, and IMHO it's definitively a great tool.
What is the difference between a strongly typed language and a statically typed language?
A statically typed language has a type system that is checked at compile time by the implementation (a compiler or interpreter). The type check rejects some programs, and programs that pass the check usually come with some guarantees; for example, the compiler guarantees not to use integer arithmetic instructions on floating-point numbers.
There is no real agreement on what "strongly typed" means, although the most widely used definition in the professional literature is that in a "strongly typed" language, it is not possible for the programmer to work around the restrictions imposed by the type system. This term is almost always used to describe statically typed languages.
The opposite of statically typed is "dynamically typed", which means that
For example, Lua, a dynamically typed language, has a string type, a number type, and a Boolean type, among others. In Lua every value belongs to exactly one type, but this is not a requirement for all dynamically typed languages. In Lua, it is permissible to concatenate two strings, but it is not permissible to concatenate a string and a Boolean.
The opposite of "strongly typed" is "weakly typed", which means you can work around the type system. C is notoriously weakly typed because any pointer type is convertible to any other pointer type simply by casting. Pascal was intended to be strongly typed, but an oversight in the design (untagged variant records) introduced a loophole into the type system, so technically it is weakly typed. Examples of truly strongly typed languages include CLU, Standard ML, and Haskell. Standard ML has in fact undergone several revisions to remove loopholes in the type system that were discovered after the language was widely deployed.
Overall, it turns out to be not that useful to talk about "strong" and "weak". Whether a type system has a loophole is less important than the exact number and nature of the loopholes, how likely they are to come up in practice, and what are the consequences of exploiting a loophole. In practice, it's best to avoid the terms "strong" and "weak" altogether, because
Amateurs often conflate them with "static" and "dynamic".
Apparently "weak typing" is used by some persons to talk about the relative prevalance or absence of implicit conversions.
Professionals can't agree on exactly what the terms mean.
Overall you are unlikely to inform or enlighten your audience.
The sad truth is that when it comes to type systems, "strong" and "weak" don't have a universally agreed on technical meaning. If you want to discuss the relative strength of type systems, it is better to discuss exactly what guarantees are and are not provided. For example, a good question to ask is this: "is every value of a given type (or class) guaranteed to have been created by calling one of that type's constructors?" In C the answer is no. In CLU, F#, and Haskell it is yes. For C++ I am not sure—I would like to know.
By contrast, static typing means that programs are checked before being executed, and a program might be rejected before it starts. Dynamic typing means that the types of values are checked during execution, and a poorly typed operation might cause the program to halt or otherwise signal an error at run time. A primary reason for static typing is to rule out programs that might have such "dynamic type errors".
Does one imply the other?
On a pedantic level, no, because the word "strong" doesn't really mean anything. But in practice, people almost always do one of two things:
They (incorrectly) use "strong" and "weak" to mean "static" and "dynamic", in which case they (incorrectly) are using "strongly typed" and "statically typed" interchangeably.
They use "strong" and "weak" to compare properties of static type systems. It is very rare to hear someone talk about a "strong" or "weak" dynamic type system. Except for FORTH, which doesn't really have any sort of a type system, I can't think of a dynamically typed language where the type system can be subverted. Sort of by definition, those checks are bulit into the execution engine, and every operation gets checked for sanity before being executed.
Either way, if a person calls a language "strongly typed", that person is very likely to be talking about a statically typed language.
**Error Case:**
var handler = function(parameters) {
console.log(parameters);
}
(function() { //IIFE
// some code
})();
Output: TypeError: (intermediate value)(intermediate value) is not a function *How to Fix IT -> because you are missing semi colan(;) to separate expressions;
**Fixed**
var handler = function(parameters) {
console.log(parameters);
}; // <--- Add this semicolon(if you miss that semi colan ..
//error will occurs )
(function() { //IIFE
// some code
})();
why this error comes?? Reason : specific rules for automatic semicolon insertion which is given ES6 stanards
I had this problem. My solution is: change same password of other in windowns. Restart Service (check logon in tab Service SQL).
The code in joerage's answer is inspiring.
Unfortunately, it changes the character casing of the keys and does not handle comments. So I wrote something that should be robust enough to read (only) very dirty INI files and allows to retrieve keys as they are.
It uses some LINQ, a nested case insensitive string dictionary to store sections, keys and values, and read the file in one go.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class IniReader
{
Dictionary<string, Dictionary<string, string>> ini = new Dictionary<string, Dictionary<string, string>>(StringComparer.InvariantCultureIgnoreCase);
public IniReader(string file)
{
var txt = File.ReadAllText(file);
Dictionary<string, string> currentSection = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
ini[""] = currentSection;
foreach(var line in txt.Split(new[]{"\n"}, StringSplitOptions.RemoveEmptyEntries)
.Where(t => !string.IsNullOrWhiteSpace(t))
.Select(t => t.Trim()))
{
if (line.StartsWith(";"))
continue;
if (line.StartsWith("[") && line.EndsWith("]"))
{
currentSection = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
ini[line.Substring(1, line.LastIndexOf("]") - 1)] = currentSection;
continue;
}
var idx = line.IndexOf("=");
if (idx == -1)
currentSection[line] = "";
else
currentSection[line.Substring(0, idx)] = line.Substring(idx + 1);
}
}
public string GetValue(string key)
{
return GetValue(key, "", "");
}
public string GetValue(string key, string section)
{
return GetValue(key, section, "");
}
public string GetValue(string key, string section, string @default)
{
if (!ini.ContainsKey(section))
return @default;
if (!ini[section].ContainsKey(key))
return @default;
return ini[section][key];
}
public string[] GetKeys(string section)
{
if (!ini.ContainsKey(section))
return new string[0];
return ini[section].Keys.ToArray();
}
public string[] GetSections()
{
return ini.Keys.Where(t => t != "").ToArray();
}
}
If you haven't pushed that change yet, git reset --hard HEAD^
Otherwise, reverting the revert is perfectly fine.
Another way is to git checkout HEAD^^ -- .
and then git add -A && git commit
.
Actually you can capture Query strings in MVC in two ways.....
public ActionResult CrazyMVC(string knownQuerystring)
{
// This is the known query string captured by the Controller Action Method parameter above
string myKnownQuerystring = knownQuerystring;
// This is what I call the mysterious "unknown" query string
// It is not known because the Controller isn't capturing it
string myUnknownQuerystring = Request.QueryString["unknownQuerystring"];
return Content(myKnownQuerystring + " - " + myUnknownQuerystring);
}
This would capture both query strings...for example:
/CrazyMVC?knownQuerystring=123&unknownQuerystring=456
Output: 123 - 456
Don't ask me why they designed it that way. Would make more sense if they threw out the whole Controller action system for individual query strings and just returned a captured dynamic list of all strings/encoded file objects for the URL by url-form-encoding so you can easily access them all in one call. Maybe someone here can demonstrate that if its possible?
Makes no sense to me how Controllers capture query strings, but it does mean you have more flexibility to capture query strings than they teach you out of the box. So pick your poison....both work fine.
This works for me:
function getScripts(scripts) {
var prArr = [];
scripts.forEach(function(script) {
(function(script){
prArr .push(new Promise(function(resolve){
$.getScript(script, function () {
resolve();
});
}));
})(script);
});
return Promise.all(prArr, function(){
return true;
});
}
And use it:
var jsarr = ['script1.js','script2.js'];
getScripts(jsarr).then(function(){
...
});
Find:
^[#;].*
Replace with nothing. The ^
indicates the start of a line, the [#;]
is a character class to match either #
or ;
, and .*
matches anything else in the line.
In versions of Notepad++ before 6.0, you won't be able to actually remove the lines due to a limitation in its regex engine; the replacement results in blank lines for each line matched. In other words, this:
# foo ; bar statement;
Will turn into:
statement;
However, the replacement will work in Notepad++ 6.0 if you add \r
, \n
or \r\n
to the end of the pattern, depending on which line ending your file is using, resulting in:
statement;
Move the queue to self instead of as an argument to your functions package
and send
This line:
layout = (LinearLayout) findViewById(R.id.statsviewlayout);
Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:
setContentView(new GraphTemperature(getApplicationContext()));
And i'm guessing that new "graphTemperature" does not set anything with that id.
It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).
The nullpointer will be thrown because the layout you're looking for isn't found, so
layout.addView(buyButton);
Throws that exception.
addition: Now if you want to get that view from an XML, you should use an inflater:
layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);
assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"
A Mutex is a mutually exclusive flag. It acts as a gate keeper to a section of code allowing one thread in and blocking access to all others. This ensures that the code being controled will only be hit by a single thread at a time. Just be sure to release the mutex when you are done. :)
I have the same problem. I avoid it with remove.packages("Package making this confusion")
and it works. In my case, I don't need the second package, so that is not a very good idea.
Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:
class Test {
Dictionary<int,String> entities;
public String getEntity(int code) {
return this.entities[code];
}
}
If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).
You can use \t
to create a tab in a file.
GDB Dashboard
https://github.com/cyrus-and/gdb-dashboard
This GDB configuration uses the official GDB Python API to show us whatever we want whenever GDB stops after for example next
, much like TUI.
However I have found that this implementation is a more robust and configurable alternative to the built-in GDB TUI mode as explained at: gdb split view with code
For example, we can configure GDB Dashboard to show disassembly, source, registers and stack with:
dashboard -layout source assembly registers stack
Here is what it looks like if you enable all available views instead:
Related questions:
There is no language level support for this in MySQL. Here is a work-around involving MySQL information_schema meta-data in 5.0+, but it won't address your issue in 4.0.18.
drop procedure if exists schema_change;
delimiter ';;'
create procedure schema_change() begin
/* delete columns if they exist */
if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column1') then
alter table table1 drop column `column1`;
end if;
if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column2') then
alter table table1 drop column `column2`;
end if;
/* add columns */
alter table table1 add column `column1` varchar(255) NULL;
alter table table1 add column `column2` varchar(255) NULL;
end;;
delimiter ';'
call schema_change();
drop procedure if exists schema_change;
I wrote some more detailed information in a blog post.
also you can use this way. it will change your big drawble fit to your canvas:
Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, yourDrawable);
yourCanvas.drawBitmap(bitmap, 0, 0, yourPaint);
Did you notice your typo, $car2
instead of #car2
?
Anyway, :hidden
seems to be working as expected, try it here.
For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:
while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
n = (3*n + 1) / 2;
if (n % 2 == 0) {
do n /= 2; while (n % 2 == 0);
if (n == 1) break;
}
}
Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:
3n+1 -> ???? 0000 0100
/ 2 -> ???? ?000 0010
/ 2 -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2 -> ???? ???0 0010
/ 2 -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2 -> ???? ???? ?010
/ 2 -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2 -> ???? ???? ???0
/ 2 -> ???? ???? ????
So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:
k = n / 256;
m = n % 256;
switch (m) {
case 0: n = 1 * k + 0; break;
case 1: n = 81 * k + 1; break;
case 2: n = 81 * k + 1; break;
...
case 155: n = 729 * k + 425; break;
...
}
Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.
PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like
static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }
while (n > 128) {
size_t lastBits = n % 256;
n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}
In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.
PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).
We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).
If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.
My R use 1970-01-01:
>as.Date(15103, origin="1970-01-01")
[1] "2011-05-09"
and this matches the calculation from
>as.numeric(as.Date(15103, origin="1970-01-01"))
There are at least two ways to do it:
Use nowrap attribute inside the "td" tag:
<th nowrap="nowrap">Really long column heading</th>
Use non-breakable spaces between your words:
<th>Really long column heading</th>
The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.
The easiest solution would be to close the file after you've read it in, then reopen it for writing.
with open("replayScript.json", "r") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
with open("replayScript.json", "w") as jsonFile:
json.dump(data, jsonFile)
Alternatively, you can use seek()
to move the cursor back to the beginning of the file then start writing, followed by a truncate()
to deal with the case where the new data is smaller than the previous.
with open("replayScript.json", "r+") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
jsonFile.seek(0) # rewind
json.dump(data, jsonFile)
jsonFile.truncate()
Update Oct 2020:
So if you are on this page scratching your head why my favicon is not working , then read along. I tried all the things (which I supposedly thought I was doing right) yet favicon was not showing up on browser tabs.
Here is one line simple cracker code that worked flawlessly:
<link rel="icon" href="https://abcde.neocities.org/bla123.jpg" size="16x16" type="image/jpg">
Notes:
I tested it on Firefox, Chrome, Edge, and opera. OS: Win 10, Mac OSX, ios and Android .Also I did not experience any cashing issues, worked pretty much as soon as I refreshed the page.
Here's a really nice and simple way of doing it with really easy to follow instructions using a custom MultiButtonAttribute:
To summarise, make your submit buttons like this:
<input type="submit" value="Cancel" name="action" />
<input type="submit" value="Create" name="action" />
Your actions like this:
[HttpPost]
[MultiButton(MatchFormKey="action", MatchFormValue="Cancel")]
public ActionResult Cancel()
{
return Content("Cancel clicked");
}
[HttpPost]
[MultiButton(MatchFormKey = "action", MatchFormValue = "Create")]
public ActionResult Create(Person person)
{
return Content("Create clicked");
}
And create this class:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
public string MatchFormKey { get; set; }
public string MatchFormValue { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
return controllerContext.HttpContext.Request[MatchFormKey] != null &&
controllerContext.HttpContext.Request[MatchFormKey] == MatchFormValue;
}
}
In my opinion you should delete this AVD and create new one for API-7. It will work fine if not please let me know I'll send you some more solution.
Regards,
you attach the .onerror handler to the ajax object, why people insist on posting JQuery for responses when vanila works cross platform...
quickie example:
ajax = new XMLHttpRequest();
ajax.open( "POST", "/url/to/handler.php", true );
ajax.onerror = function(){
alert("Oops! Something went wrong...");
}
ajax.send(someWebFormToken );
I would use the translate method without translation table. It deletes the letters in second argument in recent Python versions.
def remove_chars(line):
line7=line[7].translate(None,'abcd')
return line[:7]+[line7]+line[8:]
line= ['ad','da','sdf','asd',
'3424','342sfas','asdfaf','sdfa',
'afase']
print line[7]
line = remove_chars(line)
print line[7]
I don't know if it's a good answer, but I was able to solve this problem by running my application under an AppDomain with an identity of "Local System".
This is a prompt to create a bunch of object, such as sp_help_diagram (?), that do not exist.
This should have nothing to do with the owner of the db.
The foreach
construct is unfortunately not intrinsic to collections but instead external to them. The result is two-fold:
Python does not support a true foreach
on collections directly. An example would be
myList.foreach( a => print(a)).map( lambda x: x*2)
But python does not support it. Partial fixes to this and other missing functionals features in python are provided by various third party libraries including one that I helped author: see https://pypi.org/project/infixpy/
I want to add a "late" answer, because I struggled with change
, keyup
and search
today, and maybe what I found in the end may be useful for others too.
Basically, I have a search-as-type panel, and I just wanted to react properly to the press of the little X (under Chrome and Opera, FF does not implement it), and clear a content pane as a result.
I had this code:
$(some-input).keyup(function() {
// update panel
}
$(some-input).change(function() {
// update panel
}
$(some-input).on("search", function() {
// update panel
}
(They are separate because I wanted to check when and under which circumstances each was called).
It turns out that Chrome and Firefox react differently.
In particular, Firefox treats change
as "every change to the input", while Chrome treats it as "when focus is lost AND the content is changed".
So, on Chrome the "update panel" function was called once, on FF twice for every keystroke (one in keyup
, one in change
)
Additionally, clearing the field with the small X (which is not present under FF) fired the search
event under Chrome: no keyup
, no change
.
The conclusion? Use input
instead:
$(some-input).on("input", function() {
// update panel
}
It works with the same behaviour under all the browsers I tested, reacting at every change in the input content (copy-paste with the mouse, autocompletion and "X" included).
Note that on some devices your code wont work without android:priority="1000" in intent filter:
<receiver android:name=".listener.SmsListener">
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
And here is some optimizations:
public class SmsListener extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
String messageBody = smsMessage.getMessageBody();
}
}
}
}
Note:
The value must be an integer, such as "100". Higher numbers have a higher priority. The default value is 0. The value must be greater than -1000 and less than 1000.
Following code may help in creating directory :
-(void) createDirectory : (NSString *) dirName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Fetch path for document directory
dataPath = (NSMutableString *)[documentsDirectory stringByAppendingPathComponent:dirName];
NSError *error;
if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]) {
NSLog(@"Couldn't create directory error: %@", error);
}
else {
NSLog(@"directory created!");
}
NSLog(@"dataPath : %@ ",dataPath); // Path of folder created
}
Usage :
[self createDirectory:@"MyFolder"];
Result :
directory created!
dataPath : /var/mobile/Applications/BD4B5566-1F11-4723-B54C-F1D0B23CBC/Documents/MyFolder
A lot of answers have been given, based on technical considerations, especially around performance.
According to me, choice between TreeSet
and HashSet
matters.
But I would rather say the choice should be driven by conceptual considerations first.
If, for the objects your need to manipulate, a natural ordering does not make sense, then do not use TreeSet
.
It is a sorted set, since it implements SortedSet
. So it means you need to override function compareTo
, which should be consistent with what returns function equals
. For example if you have a set of objects of a class called Student, then I do not think a TreeSet
would make sense, since there is no natural ordering between students. You can order them by their average grade, okay, but this is not a "natural ordering". Function compareTo
would return 0 not only when two objects represent the same student, but also when two different students have the same grade. For the second case, equals
would return false (unless you decide to make the latter return true when two different students have the same grade, which would make equals
function have a misleading meaning, not to say a wrong meaning.)
Please note this consistency between equals
and compareTo
is optional, but strongly recommended. Otherwise the contract of interface Set
is broken, making your code misleading to other people, thus also possibly leading to unexpected behavior.
This link might be a good source of information regarding this question.
One interesting note: although this isn't available in on the web, if you're using JS in Electron then you can do this.
Using the standard HTML5 file input, you'll receive an extra path
property on selected files, containing the real file path.
Full docs here: https://github.com/electron/electron/blob/master/docs/api/file-object.md
Type in your URL localhost/[name of your folder in htdocs]
You can do this too:
oldIFS="$IFS"
IFS=$'\n' arr=($(<file))
IFS="$oldIFS"
echo "${arr[1]}" # It will print `A Dog`.
Note:
Filename expansion still occurs. For example, if there's a line with a literal *
it will expand to all the files in current folder. So use it only if your file is free of this kind of scenario.
This was the best way for me. You can retrieve all existing files (be it symbolic links or normal):
os.path.lexists(path)
Return True if path refers to an existing path. Returns True for broken symbolic links. Equivalent to exists() on platforms lacking os.lstat().
New in version 2.4.
For TSQL I like to encapsulate case statements in an outer apply. This prevents me from having to have the case statement written twice, allows reference to the case statement by alias in future joins and avoids the need for positional references.
select oa.day,
model.name,
attempt.type,
oa.result
COUNT(*) MyCount
FROM attempt attempt, prod_hw_id prod_hw_id, model model
WHERE time >= '2013-11-06 00:00:00'
AND time < '2013-11-07 00:00:00'
AND attempt.hard_id = prod_hw_id.hard_id
AND prod_hw_id.model_id = model.model_id
OUTER APPLY (
SELECT CURRENT_DATE-1 AS day,
CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END result
) oa
group by oa.day,
model.name,
attempt.type,
oa.result
order by model.name, attempt.type, oa.result;
$ a=(1 2 3 4)
$ echo ${#a[@]}
4
Try this so you allow enough time for the first process to start.. else it will spawn 2 processes because the first one is not still running when you run the second one... This can happen if your computer is too fast..
@echo off
start /d iexplore.exe http://google.com
PING 1.1.1.1 -n 1 -w 2000 >NUL
START /d iexplore.exe blablabla
replace blablabla with another address
Use a for
loop instead of .forEach()
var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false
for(var call of myObj) {
console.log(call)
var a = call['a'], b = call['b']
if(a == null || b == null) {
result = false
break
}
}
Simply put div
inside the td
and set the following styles of div
:
margin-bottom: 20px;
height: 40px;
float: left;
width: 100%;
Here is a much better solution. http://bavotasan.com/2011/html5-placeholder-jquery-fix/ I've adopted it a bit to work only with browsers under IE10
<!DOCTYPE html>
<!--[if lt IE 7]><html class="no-js lt-ie10 lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]><html class="no-js lt-ie10 lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]><html class="no-js lt-ie10 lt-ie9" lang="en"> <![endif]-->
<!--[if IE 9]><html class="no-js lt-ie10" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" lang="en"><!--<![endif]-->
<script>
// Placeholder fix for IE
$('.lt-ie10 [placeholder]').focus(function() {
var i = $(this);
if(i.val() == i.attr('placeholder')) {
i.val('').removeClass('placeholder');
if(i.hasClass('password')) {
i.removeClass('password');
this.type='password';
}
}
}).blur(function() {
var i = $(this);
if(i.val() == '' || i.val() == i.attr('placeholder')) {
if(this.type=='password') {
i.addClass('password');
this.type='text';
}
i.addClass('placeholder').val(i.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
//if($(this).validationEngine('validate')) { // If using validationEngine
$(this).find('[placeholder]').each(function() {
var i = $(this);
if(i.val() == i.attr('placeholder'))
i.val('');
i.removeClass('placeholder');
})
//}
});
</script>
...
</html>
JSON.parse()
is used to convert String to Object.
JSON.stringify()
is used to convert Object to String.
You can refer this too...
<script type="text/javascript">
function ajax_get_json(){
var hr = new XMLHttpRequest();
hr.open("GET", "JSON/mylist.json", true);
hr.setRequestHeader("Content-type", "application/json",true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
/* var return_data = hr.responseText; */
var data=JSON.parse(hr.responseText);
var status=document.getElementById("status");
status.innerHTML = "";
/* status.innerHTML=data.u1.country; */
for(var obj in data)
{
status.innerHTML+=data[obj].uname+" is in "+data[obj].country+"<br/>";
}
}
}
hr.send(null);
status.innerHTML = "requesting...";
}
</script>
Simply, you can use FormCollection
like:
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
// Get Post Params Here
string var1 = collection["var1"];
}
You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:
//Defined in another file
class MyForm
{
public string var1 { get; set; }
}
[HttpPost]
public ActionResult SubmitAction(MyForm form)
{
string var1 = form1.Var1;
}
Calculates the size of the java.sql.ResultSet:
int size = 0;
if (rs != null) {
rs.beforeFirst();
rs.last();
size = rs.getRow();
}
(Source)
const compareNumbers = (a: number, b: number): number => a - b
myArray.sort(compareNumbers)
recursive solution:
function generateRamdomId (seedStr) {
const len = seedStr.length
console.log('possibleStr', seedStr , ' len ', len)
if(len <= 1){
return seedStr
}
const randomValidIndex = Math.floor(Math.random() * len)
const randomChar = seedStr[randomValidIndex]
const chunk1 = seedStr.slice(0, randomValidIndex)
const chunk2 = seedStr.slice(randomValidIndex +1)
const possibleStrWithoutRandomChar = chunk1.concat(chunk2)
return randomChar + generateRamdomId(possibleStrWithoutRandomChar)
}
you can use with the seed you want , dont repeat chars if you dont rea. Example
generateRandomId("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
To disable specific rules for file(s) inside folder(s), you need to use the "overrides"
key of your .eslintrc
config file.
For example, if you want to remove the following rules:
no-use-before-define
max-lines-per-function
For all files inside the following main directory:
/spec
You can add this to your .eslintrc
file...
"overrides": [
{
"files": ["spec/**/*.js"],
"rules": {
"no-use-before-define": ["off"],
"max-lines-per-function": ["off"]
}
}
]
Note that I used **
inside the spec/**/*.js
glob, which means I am looking recursively for all subfolders inside the folder called spec
and selecting all files that ends with js
in order to remove the desired rules from them.
Old thread, I know, but for future reference, the --proxy option is now passed with an "="
Example:
$ sudo pip install --proxy=http://yourproxy:yourport package_name
To reduce cyclomatic complexity use a map:
Map<String,Callable<Object>> map = new HashMap < > ( ) ;
map . put ( "apple" , new Callable<Object> () { public Object call ( method1 ( ) ; return null ; } ) ;
...
map . get ( x ) . call ( ) ;
or polymorphism
You should use val
instead of value
.
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('input[name="testing"]').val('Work!');
});
</script>
There are two ways to hide video tag controls
Remove the controls
attribute from the video tag.
Add the css to the video tag
video::-webkit-media-controls-panel {
display: none !important;
opacity: 1 !important;}
There are already a lot of good responses to this question, but I thought it may be helpful to clarify the case where you would expect the session cookie to be sent because the cookie domain matches, but it is not getting sent because the AJAX request is being made to a different subdomain. In this case, I have a cookie that is assigned to the *.mydomain.com domain, and I am wanting it to be included in an AJAX request to different.mydomain.com". By default, the cookie does not get sent. You do not need to disable HTTPONLY on the session cookie to resolve this issue. You only need to do what wombling suggested (https://stackoverflow.com/a/23660618/545223) and do the following.
1) Add the following to your ajax request.
xhrFields: { withCredentials:true }
2) Add the following to your response headers for resources in the different subdomain.
Access-Control-Allow-Origin : http://original.mydomain.com
Access-Control-Allow-Credentials : true
As has been pointed out ... in a select
box, the .val()
attribute will give you the value of the selected option. If the selected option does not have a value attribute it will default to the display value of the option (which is what the examples on the jQuery documentation of .val
show.
you want to use .text()
of the selected option:
$('#Crd option:selected').text()
<head>
<style>
div.scroll
{
background-color:#00FFFF;
width:40%;
height:200PX;
FLOAT: left;
margin-left: 5%;
padding: 1%;
overflow:scroll;
}
</style>
</head>
<body>
<div class="scroll">You can use the overflow property when you want to have better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better </div>
</body>
</html>
for
or break
.The only case when both do (nearly) the same thing is in the main()
function, as a return from main performs an exit()
.
In most C implementations, main
is a real function called by some startup code that does something like int ret = main(argc, argv); exit(ret);
. The C standard guarantees that something equivalent to this happens if main
returns, however the implementation handles it.
Example with return
:
#include <stdio.h>
void f(){
printf("Executing f\n");
return;
}
int main(){
f();
printf("Back from f\n");
}
If you execute this program it prints:
Executing f Back from f
Another example for exit()
:
#include <stdio.h>
#include <stdlib.h>
void f(){
printf("Executing f\n");
exit(0);
}
int main(){
f();
printf("Back from f\n");
}
If you execute this program it prints:
Executing f
You never get "Back from f". Also notice the #include <stdlib.h>
necessary to call the library function exit()
.
Also notice that the parameter of exit()
is an integer (it's the return status of the process that the launcher process can get; the conventional usage is 0 for success or any other value for an error).
The parameter of the return statement is whatever the return type of the function is. If the function returns void, you can omit the return at the end of the function.
Last point, exit()
come in two flavors _exit()
and exit()
. The difference between the forms is that exit()
(and return from main) calls functions registered using atexit()
or on_exit()
before really terminating the process while _exit()
(from #include <unistd.h>
, or its synonymous _Exit from #include <stdlib.h>
) terminates the process immediately.
Now there are also issues that are specific to C++.
C++ performs much more work than C when it is exiting from functions (return
-ing). Specifically it calls destructors of local objects going out of scope. In most cases programmers won't care much of the state of a program after the processus stopped, hence it wouldn't make much difference: allocated memory will be freed, file ressource closed and so on. But it may matter if your destructor performs IOs. For instance automatic C++ OStream
locally created won't be flushed on a call to exit and you may lose some unflushed data (on the other hand static OStream
will be flushed).
This won't happen if you are using the good old C FILE*
streams. These will be flushed on exit()
. Actually, the rule is the same that for registered exit functions, FILE*
will be flushed on all normal terminations, which includes exit()
, but not calls to _exit()
or abort().
You should also keep in mind that C++ provide a third way to get out of a function: throwing an exception. This way of going out of a function will call destructor. If it is not catched anywhere in the chain of callers, the exception can go up to the main() function and terminate the process.
Destructors of static C++ objects (globals) will be called if you call either return
from main()
or exit()
anywhere in your program. They wont be called if the program is terminated using _exit()
or abort()
. abort()
is mostly useful in debug mode with the purpose to immediately stop the program and get a stack trace (for post mortem analysis). It is usually hidden behind the assert()
macro only active in debug mode.
When is exit() useful ?
exit()
means you want to immediately stops the current process. It can be of some use for error management when we encounter some kind of irrecoverable issue that won't allow for your code to do anything useful anymore. It is often handy when the control flow is complicated and error codes has to be propagated all way up. But be aware that this is bad coding practice. Silently ending the process is in most case the worse behavior and actual error management should be preferred (or in C++ using exceptions).
Direct calls to exit()
are especially bad if done in libraries as it will doom the library user and it should be a library user's choice to implement some kind of error recovery or not. If you want an example of why calling exit()
from a library is bad, it leads for instance people to ask this question.
There is an undisputed legitimate use of exit()
as the way to end a child process started by fork() on Operating Systems supporting it. Going back to the code before fork() is usually a bad idea. This is the rationale explaining why functions of the exec() family will never return to the caller.
A by far easier approach is to set some layer attributes of the view on initialization:
self.layer.masksToBounds = NO;
self.layer.shadowOffset = CGSizeMake(-15, 20);
self.layer.shadowRadius = 5;
self.layer.shadowOpacity = 0.5;
You need to import QuartzCore.
#import <QuartzCore/QuartzCore.h>
In Java 8, you can use streams:
int[] spam = new int[] { 1, 2, 3 };
Arrays.stream(spam)
.boxed()
.collect(Collectors.toList());
For Remove outline for anchor tag
a {outline : none;}
Remove outline from image link
a img {outline : none;}
Remove border from image link
img {border : 0;}
Try this
/.*[^a]$/
The []
denotes a character class, and the ^
inverts the character class to match everything but an a
.
Your regex pattern should have the g modifier:
var pattern = /[somepattern]+/g;
notice the g at the end. it tells the replacer to do a global replace.
Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:
var pattern = /[0-9a-zA-Z]+/g;
a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.
EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):
var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");
But you would need to change your replace function to this:
this.markup = this.markup.replace(pattern, value);
Building off of Nike's answer. Its straightforward to implement the laplacian based method with opencv:
short GetSharpness(char* data, unsigned int width, unsigned int height)
{
// assumes that your image is already in planner yuv or 8 bit greyscale
IplImage* in = cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,1);
IplImage* out = cvCreateImage(cvSize(width,height),IPL_DEPTH_16S,1);
memcpy(in->imageData,data,width*height);
// aperture size of 1 corresponds to the correct matrix
cvLaplace(in, out, 1);
short maxLap = -32767;
short* imgData = (short*)out->imageData;
for(int i =0;i<(out->imageSize/2);i++)
{
if(imgData[i] > maxLap) maxLap = imgData[i];
}
cvReleaseImage(&in);
cvReleaseImage(&out);
return maxLap;
}
Will return a short indicating the maximum sharpness detected, which based on my tests on real world samples, is a pretty good indicator of if a camera is in focus or not. Not surprisingly, normal values are scene dependent but much less so than the FFT method which has to high of a false positive rate to be useful in my application.
Just remember to fix multiple CSS inclusions in a bundle such as:
bundles.Add(new StyleBundle("~/Content/styles/jquery-ui")
.Include("~/Content/css/path1/somestyle1.css", "~/Content/css/path2/somestyle2.css"));
You cannot just add new CssRewriteUrlTransform()
to the end as you can with one CSS file as the method does not support it, so you have to use Include
multiple times:
bundles.Add(new StyleBundle("~/Content/styles/jquery-ui")
.Include("~/Content/css/path1/somestyle1.css", new CssRewriteUrlTransform())
.Include("~/Content/css/path2/somestyle2.css", new CssRewriteUrlTransform()));
As long as ManagementObjectCollection implements IEnumerable<ManagementObject> you can do:
List<ManagementObject> managementList = new List<ManagementObjec>(managementObjects);
If it doesn't, then you are stuck doing it the way that you are doing it.
function isWholeNumber(num) {
return num === Math.round(num);
}
This tutorial gives a simple, yet elegant, solution, which i transcribe:
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion("stringify(double)");
return o.str();
}
...
std::string my_val = stringify(val);
A String in java is merely an object around an array of chars. Hence a
char[]
is identical to an unboxed String with the same characters. By creating a new String from your array of characters
new String(char[])
you are essentially telling the compiler to autobox a String object around your array of characters.
Something like:
>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'
Just put the actual encoding you are using.
I got this solution and it is working for me
if (myNewDT.MyDateTime == null)
{
myNewDT.MyDateTime = DateTime.Now();
}
var _RemoveBtn = document.getElementsByClassName("remove");
for(var i=0 ; i<_RemoveBtn.length ; i++){
_RemoveBtn[i].addEventListener('click',sample,false);
}
function sample(event){
console.log(event.currentTarget.parentNode);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_with_the_button);
final Animation myAnim = AnimationUtils.loadAnimation(this, R.anim.milkshake);
Button myButton = (Button) findViewById(R.id.new_game_btn);
myButton.setAnimation(myAnim);
}
For onClick of the Button
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.startAnimation(myAnim);
}
});
Create the anim folder in res directory
Right click on, res -> New -> Directory
Name the new Directory anim
create a new xml file name it milkshake
milkshake.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="100"
android:fromDegrees="-5"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="10"
android:repeatMode="reverse"
android:toDegrees="5" />
.class {
font-size: clamp(minimum-size, prefered-size, maximum-size)
}
using this you could set it up so prefered and max values are 5vw but the minimum is 15px or something so it won't go over 5vw but if 5vw < 15px it will stick to 15px
If the first item is to be used as a placeholder (empty value) and your select is required
then you can use the :invalid
pseudo-class to target it.
select {_x000D_
-webkit-appearance: menulist-button;_x000D_
color: black;_x000D_
}_x000D_
_x000D_
select:invalid {_x000D_
color: green;_x000D_
}
_x000D_
<select required>_x000D_
<option value="">Item1</option>_x000D_
<option value="Item2">Item2</option>_x000D_
<option value="Item3">Item3</option>_x000D_
</select>
_x000D_
Check if the project having HRESULT: 0x80131040 error is being used/referenced by any project. If yes, kindly check if these project have similar .dll being referenced and the version is the same. If they're are not of same version number, then it is causing the said error.
$('form').serialize() //this produces: "foo=1&bar=xxx&this=hi"
How about this modification on 7daysclean.cmd to take a leap year into account?
It can be done in less than 10 lines of coding!
set /a Leap=0
if (Month GEQ 2 and ((Years%4 EQL 0 and Years%100 NEQ 0) or Years%400 EQL 0)) set /a Leap=day
set /a Months=!_months!+Leap
Edit by Mofi:
The condition above contributed by J.R. evaluates always to false because of invalid syntax.
And Month GEQ 2
is also wrong because adding 86400 seconds for one more day must be done in a leap year only for the months March to December, but not for February.
A working code to take leap day into account - in current year only - in batch file 7daysclean.cmd posted by Jay would be:
set "LeapDaySecs=0"
if %Month% LEQ 2 goto CalcMonths
set /a "LeapRule=Years%%4"
if %LeapRule% NEQ 0 goto CalcMonths
rem The other 2 rules can be ignored up to year 2100.
set /A "LeapDaySecs=day"
:CalcMonths
set /a Months=!_months!+LeapDaySecs
I'd recommend :Rename
from tpope's eunuch for this.
It also includes a bunch of other handy commands.
The Rename command is defined as follows therein currently (check the repo for any updates!):
command! -bar -nargs=1 -bang -complete=file Rename :
\ let s:file = expand('%:p') |
\ setlocal modified |
\ keepalt saveas<bang> <args> |
\ if s:file !=# expand('%:p') |
\ call delete(s:file) |
\ endif |
\ unlet s:file
Global variables are not extern
nor static
by default on C and C++.
When you declare a variable as static
, you are restricting it to the current source file. If you declare it as extern
, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern
keyword) you will get a link error (symbol not found).
Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal
. If you declare it as static
, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal
.
What you can do in C++, that you can't in C, is to declare the variable as const
on the header, like this:
const int varGlobal = 7;
And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define
for constants.
If you need a global variable visible on multiple sources and not const
, declare it as extern
on the header, and then define it, this time without the extern keyword, on a source file:
Header included by multiple files:
extern int varGlobal;
In one of your source files:
int varGlobal = 7;
Yep, the limit is set by the kernel; check out this thread on Stack Overflow for more details: Increasing the maximum number of tcp/ip connections in linux
While you can't yet get Firefox to remove the dropdown arrow (see MatTheCat's post), you can hide your "stylized" background image from showing in Firefox.
-moz-background-position: -9999px -9999px!important;
This will position it out of frame, leaving you with the default select box arrow – while keeping the stylized version in Webkit.
Have you actually downloaded and installed one of the milestone builds from https://jdk7.dev.java.net/ ?
You can have a play with the features, though it's not stable so you shouldn't be releasing software against them.
If you are just getting started with a new project then I would suggest that you use PDO instead of the old odbc_exec()
approach. Here is a simple example:
<?php
$bits = 8 * PHP_INT_SIZE;
echo "(Info: This script is running as $bits-bit.)\r\n\r\n";
$connStr =
'odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .
'Dbq=C:\\Users\\Gord\\Desktop\\foo.accdb;';
$dbh = new PDO($connStr);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql =
"SELECT AgentName FROM Agents " .
"WHERE ID < ? AND AgentName <> ?";
$sth = $dbh->prepare($sql);
// query parameter value(s)
$params = array(
5,
'Homer'
);
$sth->execute($params);
while ($row = $sth->fetch()) {
echo $row['AgentName'] . "\r\n";
}
NOTE: The above approach is sufficient if you do not need to support Unicode characters above U+00FF
. If you do need to support such characters then neither PDO_ODBC
nor the old odbc_
functions will work; you'll need to use the solution described in this answer.
A solution that works for S3 modified from Minkymorgan.
Simply pass the temporary partitioned directory path (with different name than final path) as the srcPath
and single final csv/txt as destPath
Specify also deleteSource
if you want to remove the original directory.
/**
* Merges multiple partitions of spark text file output into single file.
* @param srcPath source directory of partitioned files
* @param dstPath output path of individual path
* @param deleteSource whether or not to delete source directory after merging
* @param spark sparkSession
*/
def mergeTextFiles(srcPath: String, dstPath: String, deleteSource: Boolean): Unit = {
import org.apache.hadoop.fs.FileUtil
import java.net.URI
val config = spark.sparkContext.hadoopConfiguration
val fs: FileSystem = FileSystem.get(new URI(srcPath), config)
FileUtil.copyMerge(
fs, new Path(srcPath), fs, new Path(dstPath), deleteSource, config, null
)
}
It changes the linkage of a function in such a way that the function is callable from C. In practice that means that the function name is not mangled.
I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).
If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::
.
Something along these lines:
create view view1
as
select table1.col1,table2.col1,table3.col3
from table1
inner join
table2
inner join
table3
on
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;
Notice the varchar
typecasting on the table1.col4.
Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.
Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).
What you appear to be looking for is not just a database program, but a database with forms, reports, etc (basically an IDE of sorts). I would recommend trying OpenOffice.org Base, which comes with the office suite. It's free and open source. It's nowhere near as polished as access, but it does pretty much the same things.
Plus, if you know access, it will be at least somewhat familiar.
EDIT: Sorry, failed to read that you are considering OpenOffice.org. With regard to stability, I've had it crash and do some "odd" things when I played with it, but Access has done the same thing. The best way to find out is to play with it a bit and see if it suits you.
Java does not have unsigned types. As already mentioned, incure the overhead of BigInteger or use JNI to access native code.
The only other way I can think of to do it is to enclose each of the rows you need a border around in a nested table. That will make the border easier to do but will potentially creat other layout issues, you'll have to manually set the width on table cells etc.
Your approach may well be the best one depending on your other layout rerquirements and the suggested approach here is just a possible alternative.
<table cellspacing="0">
<tr>
<td>no border</td>
<td>no border here either</td>
</tr>
<tr>
<td>
<table style="border: thin solid black">
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td>three</td>
<td>four</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2">once again no borders</td>
</tr>
<tr>
<td>
<table style="border: thin solid black">
<tr>
<td>hello</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2">world</td>
</tr>
</table>
You're talking about right-clicking on a table and selecting "Edit Top 50 Rows", right?
I tried [Ctl][Enter] and [Alt][Enter], but neither of those works.
Even when I insert data with CR/LF (using a standard INSERT statement), it shows up here in a single line with a rectangle representing the control codes.
Add OSHI dependency via maven:
<dependency>
<groupId>com.github.dblock</groupId>
<artifactId>oshi-core</artifactId>
<version>2.2</version>
</dependency>
Get a battery capacity left in percentage:
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
for (PowerSource pSource : hal.getPowerSources()) {
System.out.println(String.format("%n %s @ %.1f%%", pSource.getName(), pSource.getRemainingCapacity() * 100d));
}
add your script tag on the bottom of the body tag. so that script loads after html content then you won't get such error and add=
You need to initialise bin, e.g.
bin = malloc(1);
bin[0] = '\0';
or use calloc:
bin = calloc(1, 1);
You also have a bug here:
bin = (char *)realloc(bin, sizeof(char) * (sizeof(bin)+1));
this needs to be:
bin = (char *)realloc(bin, sizeof(char) * (strlen(bin)+1));
(i.e. use strlen
, not sizeof
).
And you should increase the size before calling strcat.
And you're not freeing bin, so you have a memory leak.
And you need to convert 0, 1 to '0', '1'.
And you can't strcat a char to a string.
So apart from that, it's close, but the code should probably be more like this (warning, untested !):
int int_to_bin(int k)
{
char *bin;
int tmp;
bin = calloc(1, 1);
while (k > 0)
{
bin = realloc(bin, strlen(bin) + 2);
bin[strlen(bin) - 1] = (k % 2) + '0';
bin[strlen(bin)] = '\0';
k = k / 2;
}
tmp = atoi(bin);
free(bin);
return tmp;
}
Typically, you'd use the NODE_ENV
variable to take special actions when you develop, test and debug your code. For example to produce detailed logging and debug output which you don't want in production. Express itself behaves differently depending on whether NODE_ENV
is set to production
or not. You can see this if you put these lines in an Express app, and then make a HTTP GET request to /error
:
app.get('/error', function(req, res) {
if ('production' !== app.get('env')) {
console.log("Forcing an error!");
}
throw new Error('TestError');
});
app.use(function (req, res, next) {
res.status(501).send("Error!")
})
Note that the latter app.use()
must be last, after all other method handlers!
If you set NODE_ENV
to production
before you start your server, and then send a GET /error
request to it, you should not see the text Forcing an error!
in the console, and the response should not contain a stack trace in the HTML body (which origins from Express).
If, instead, you set NODE_ENV
to something else before starting your server, the opposite should happen.
In Linux, set the environment variable NODE_ENV like this:
export NODE_ENV='value'
Check your startup files on the account used to connect to the remote machine for "echo" statements. For the Bash shell these would be your .bashrc and .bash_profile etc. Edward Thomson is correct in his answer but a specific issue that I have experienced is when there is some boiler-plate printout upon login to a server via ssh. Git will get the first four bytes of that boiler-plate and raise this error. Now in this specific case I'm going to guess that "Unab" is actually the work "Unable..." which probably indicates that there is something else wrong on the Git host.
I got the same warnings when I sudo -i
starting a root shell, @chakrit's solution didn't work for me.
But I found -u
switch of compinit
works, e.g. in your .zshrc/zshenv or where you called compinit
compinit -u
NB: Not recommended for production system
See also http://zsh.sourceforge.net/Doc/Release/Completion-System.html#Initialization
If you had your array like this: #!/bin/bash
Unix[0]='Debian'
Unix[1]="Red Hat"
Unix[2]='Ubuntu'
Unix[3]='Suse'
for i in $(echo ${Unix[@]});
do echo $i;
done
You would get:
Debian
Red
Hat
Ubuntu
Suse
I don't know why but the loop breaks down the spaces and puts them as an individual item, even you surround it with quotes.
To get around this, instead of calling the elements in the array, you call the indexes, which takes the full string thats wrapped in quotes. It must be wrapped in quotes!
#!/bin/bash
Unix[0]='Debian'
Unix[1]='Red Hat'
Unix[2]='Ubuntu'
Unix[3]='Suse'
for i in $(echo ${!Unix[@]});
do echo ${Unix[$i]};
done
Then you'll get:
Debian
Red Hat
Ubuntu
Suse
Following @Sampson's answer, I approached it this way -
HTML:
div
with content
class in each page, which holds the contents of that page. Header and Footer are separated.content
. For example, if I am creating a CONTACT US page, I will put the contents of the page inside <section class="content contact-us"></section>
.<body>
<header>
<div class="nav-menu">
<ul class="parent-nav">
<li><a href="#">Home</a></li>
<li><a href="#">Contact us</a></li>
...
</ul>
</div>
</header>
<section class="content contact-us">
Content for contact us page goes here
</section>
<footer> ... </footer>
</body>
_x000D_
CSS:
active
class, which holds the styling for an active menu..active {
color: red;
text-decoration: none;
}
_x000D_
<body>
<header>
<div class="nav-menu">
<ul class="parent-nav">
<li><a href="#">Home</a></li>
<li><a href="#">Contact us</a></li>
...
</ul>
</div>
</header>
<section class="content contact-us">
Content for contact us page goes here
</section>
<footer> ... </footer>
</body>
_x000D_
JavaScript:
content
class have the same class as menu text (lowercase and without spaces), add active
class to the menu item.var $allMenu = $('.nav-menu > .parent-nav > li > a');
var $currentContent = $('.content');
$allMenu.each(function() {
$singleMenuTitle = $(this).text().replace(/\s+/g, '-').toLowerCase();
if ($currentContent.hasClass($singleMenuTitle)) {
$(this).addClass('active');
}
});
_x000D_
.active {
color: red;
text-decoration: none;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<header>
<div class="nav-menu">
<ul class="parent-nav">
<li><a href="#">Home</a></li>
<li><a href="#">Contact us</a></li>
...
</ul>
</div>
</header>
<section class="content contact-us">
Content for contact us page goes here
</section>
<footer> ... </footer>
</body>
_x000D_
Why I Approached This?
body
tag is in header.php
file which means I cannot write unique class name for every page.It works for me:
$('#yourselect').on("change", function(e) {
// what you would like to happen
});
There are two ways for writing a proper media queries in css. If you are writing media queries for larger device first, then the correct way of writing will be:
@media only screen
and (min-width : 415px){
/* Styles */
}
@media only screen
and (min-width : 769px){
/* Styles */
}
@media only screen
and (min-width : 992px){
/* Styles */
}
But if you are writing media queries for smaller device first, then it would be something like:
@media only screen
and (max-width : 991px){
/* Styles */
}
@media only screen
and (max-width : 768px){
/* Styles */
}
@media only screen
and (max-width : 414px){
/* Styles */
}
this will return first match
@fathers.detect {|f| f["age"] > 35 }
In my case (Mac High Sierra) it was installed at ~/opt/anaconda3.
The problem arises when a different system grabs the $ variable. You have multiple $ variables being used as objects from multiple libraries, resulting in the error.
To solve it, use jQuery.noConflict just before your (function($){
:
jQuery.noConflict();
(function($){
$.fn.pluginbutton = function (options) {
...
You can also check like struct_var == (struct{})
. This does not allow you to compare to nil but it does check if it is initialized or not. Be careful while using this method. If your struct can have zero values for all of its fields you won't have great time.
package main
import "fmt"
type A struct {
Name string
}
func main() {
a := A{"Hello"}
var b A
if a == (A{}) {
fmt.Println("A is empty") // Does not print
}
if b == (A{}) {
fmt.Println("B is empty") // Prints
}
}
The lodash 4.6.1 docs have this as an example for object key equality:
_.uniqWith(objects, _.isEqual);
Option 1: Put this in your procedure to print 'comment' to stdout when it runs.
SELECT 'Comment';
Option 2: Put this in your procedure to print a variable with it to stdout:
declare myvar INT default 0;
SET myvar = 5;
SELECT concat('myvar is ', myvar);
This prints myvar is 5
to stdout when the procedure runs.
Option 3, Create a table with one text column called tmptable
, and push messages to it:
declare myvar INT default 0;
SET myvar = 5;
insert into tmptable select concat('myvar is ', myvar);
You could put the above in a stored procedure, so all you would have to write is this:
CALL log(concat('the value is', myvar));
Which saves a few keystrokes.
Option 4, Log messages to file
select "penguin" as log into outfile '/tmp/result.txt';
There is very heavy restrictions on this command. You can only write the outfile to areas on disk that give the 'others' group create and write permissions. It should work saving it out to /tmp directory.
Also once you write the outfile, you can't overwrite it. This is to prevent crackers from rooting your box just because they have SQL injected your website and can run arbitrary commands in MySQL.
I made the mistake of defining my test like this
class MyTest {
@Test
fun `test name`() = runBlocking {
// something here that isn't Unit
}
}
That resulted in runBlocking
returning something, which meant that the method wasn't void and junit didn't recognize it as a test. That was pretty lame. I explicitly supply a type parameter now to run blocking. It won't stop the pain or get me my two hours back but it will make sure this doesn't happen again.
class MyTest {
@Test
fun `test name`() = runBlocking<Unit> { // Specify Unit
// something here that isn't Unit
}
}
As far as i know %d
means decadic which is number without decimal point. if you want to load double value, use %lf
conversion (long float). for printf your values are wrong for same reason, %d
is used only for integer (and possibly chars if you know what you are doing) numbers.
Example:
double a,b;
printf("--------\n"); //seperate lines
scanf("%lf",&a);
printf("--------\n");
scanf("%lf",&b);
printf("%lf %lf",a,b);
It may not be performance-aware, but I'm using it for 30MB folders and it works flawlessly. Plus, I didn't like all the amount of code and recursion required for such an easy task.
var src = "c:\src";
var dest = "c:\dest";
var cmp = CompressionLevel.NoCompression;
var zip = source_folder + ".zip";
ZipFile.CreateFromDirectory(src, zip, cmp, includeBaseDirectory: false);
ZipFile.ExtractToDirectory(zip, dest_folder);
File.Delete(zip);
Note: ZipFile is available on .NET 4.5+ in the System.IO.Compression namespace
I could not redirect the Perl based solution to a file for some reason so I kept searching and found a bash
only way to do this:
ping www.google.fr | while read pong; do echo "$(date): $pong"; done
Wed Jun 26 13:09:23 CEST 2013: PING www.google.fr (173.194.40.56) 56(84) bytes of data.
Wed Jun 26 13:09:23 CEST 2013: 64 bytes from zrh04s05-in-f24.1e100.net (173.194.40.56): icmp_req=1 ttl=57 time=7.26 ms
Wed Jun 26 13:09:24 CEST 2013: 64 bytes from zrh04s05-in-f24.1e100.net (173.194.40.56): icmp_req=2 ttl=57 time=8.14 ms
The credit goes to https://askubuntu.com/a/137246
My pure CSS implementation based on above with 100% width. Hope it helps!
#wave-container {_x000D_
width: 100%;_x000D_
height: 100px;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
#wave {_x000D_
display: block;_x000D_
position: relative;_x000D_
height: 40px;_x000D_
background: black;_x000D_
}_x000D_
_x000D_
#wave:before {_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
border-radius: 100%;_x000D_
width: 100%;_x000D_
height: 300px;_x000D_
background-color: white;_x000D_
right: -25%;_x000D_
top: 20px_x000D_
}_x000D_
_x000D_
#wave:after {_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
border-radius: 100%;_x000D_
width: 100%;_x000D_
height: 300px;_x000D_
background-color: black;_x000D_
left: -25%;_x000D_
top: -240px;_x000D_
}
_x000D_
<div id="wave-container">_x000D_
<div id="wave">_x000D_
</div>_x000D_
</div>
_x000D_
The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.
Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.
@Dave an updated snippet from http://www.php.net/manual/en/function.strpos.php#107351
function strposa($haystack, $needles=array(), $offset=0) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle, $offset);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}
How to use:
$string = 'Whis string contains word "cheese" and "tea".';
$array = array('burger', 'melon', 'cheese', 'milk');
if (strposa($string, $array, 1)) {
echo 'true';
} else {
echo 'false';
}
will return true
, because of array
"cheese"
.
Update: Improved code with stop when the first of the needles is found:
function strposa($haystack, $needle, $offset=0) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $query) {
if(strpos($haystack, $query, $offset) !== false) return true; // stop on first true result
}
return false;
}
$string = 'Whis string contains word "cheese" and "tea".';
$array = array('burger', 'melon', 'cheese', 'milk');
var_dump(strposa($string, $array)); // will return true, since "cheese" has been found
This is one of the reasons why C++ introduced the new cast style, which includes static_cast
and reinterpret_cast
There's two things you can mean by saying conversion from signed to unsigned, you might mean that you wish the unsigned variable to contain the value of the signed variable modulo the maximum value of your unsigned type + 1. That is if your signed char has a value of -128 then CHAR_MAX+1
is added for a value of 128 and if it has a value of -1, then CHAR_MAX+1
is added for a value of 255, this is what is done by static_cast. On the other hand you might mean to interpret the bit value of the memory referenced by some variable to be interpreted as an unsigned byte, regardless of the signed integer representation used on the system, i.e. if it has bit value 0b10000000
it should evaluate to value 128, and 255 for bit value 0b11111111
, this is accomplished with reinterpret_cast.
Now, for the two's complement representation this happens to be exactly the same thing, since -128 is represented as 0b10000000
and -1 is represented as 0b11111111
and likewise for all in between. However other computers (usually older architectures) may use different signed representation such as sign-and-magnitude or ones' complement. In ones' complement the 0b10000000
bitvalue would not be -128, but -127, so a static cast to unsigned char would make this 129, while a reinterpret_cast would make this 128. Additionally in ones' complement the 0b11111111
bitvalue would not be -1, but -0, (yes this value exists in ones' complement,) and would be converted to a value of 0 with a static_cast, but a value of 255 with a reinterpret_cast. Note that in the case of ones' complement the unsigned value of 128 can actually not be represented in a signed char, since it ranges from -127 to 127, due to the -0 value.
I have to say that the vast majority of computers will be using two's complement making the whole issue moot for just about anywhere your code will ever run. You will likely only ever see systems with anything other than two's complement in very old architectures, think '60s timeframe.
The syntax boils down to the following:
signed char x = -100;
unsigned char y;
y = (unsigned char)x; // C static
y = *(unsigned char*)(&x); // C reinterpret
y = static_cast<unsigned char>(x); // C++ static
y = reinterpret_cast<unsigned char&>(x); // C++ reinterpret
To do this in a nice C++ way with arrays:
jbyte memory_buffer[nr_pixels];
unsigned char* pixels = reinterpret_cast<unsigned char*>(memory_buffer);
or the C way:
unsigned char* pixels = (unsigned char*)memory_buffer;
var data = new { studentId = 1, StudentName = "abc" };
Or value is present
var data = new { studentId, StudentName };
Simply translating the "old for loop way" into streams:
private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) {
int subLength = prefix.length();
return input.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().substring(subLength),
entry -> AttributeType.GetByName(entry.getValue())));
}
See this MSDN article and an example usage here on Stack Overflow.
Let's say that you have the following Linq/POCO class:
public class Color
{
public int ColorId { get; set; }
public string Name { get; set; }
}
And let's say that you have the following model:
public class PageModel
{
public int MyColorId { get; set; }
}
And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:
public static IEnumerable<Color> Colors = new List<Color> {
new Color {
ColorId = 1,
Name = "Red"
},
new Color {
ColorId = 2,
Name = "Blue"
}
};
In your view, you can create a drop down list like so:
<%= Html.DropDownListFor(n => n.MyColorId,
new SelectList(Colors, "ColorId", "Name")) %>
For moment.js at Vue 3
npm install moment --save
Then in any component
import moment from 'moment'
...
export default {
created: function () {
this.moment = moment;
},
...
<div class="comment-line">
{{moment(new Date()).format('DD.MM.YYYY [ ] HH:mm')}}
</div>
<?php
$currentpage = $_SERVER['REQUEST_URI'];
$eep=explode('/',$currentpage);
$ln=$eep[1];
if (in_array("en", $eep))
{
$lan='en';
}
if (in_array("es", $eep))
{
$lan='es';
}
?>
function NumValidate(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
alert('Only Number ');
return false;
} return true;
} function NumValidateWithDecimal(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (!(charCode == 8 || charCode == 46 || charCode == 110 || charCode == 13 || charCode == 9) && (charCode < 48 || charCode > 57)) {
alert('Only Number With desimal e.g.: 0.0');
return false;
}
else {
return true;
} } function onlyAlphabets(e) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode == 46) || (charCode == 32))
return true;
else
alert("Only text And White Space And . Allow");
return false;
}
catch (err) {
alert(err.Description);
}} function checkAlphaNumeric(e) {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode == 32) || (charCode >= 97 && charCode <= 122)) {
return true;
} else {
alert('Only Text And Number');
return false;
}}
To make this work in Safari I found adding !important to the webkit adjustment forces the spin button to be hidden.
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
/* display: none; <- Crashes Chrome on hover */
-webkit-appearance: none !important;
margin: 0; /* <-- Apparently some margin are still there even though it's hidden */
}
I am still having trouble working out a solution for Opera as well.
Short answer:
ALTER SCHEMA new_schema TRANSFER old_schema.table_name
I can confirm that the data in the table remains intact, which is probably quite important :)
Long answer as per MSDN docs,
ALTER SCHEMA schema_name
TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]
If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.