May I suggest the jQuery Media Plugin? Provides embed code for all kinds of video, not just WMV and does browser detection, keeping all that messy switch/case statements out of your templates.
Have a try with this:
setVolumeControlStream(AudioManager.STREAM_MUSIC);
Following the steps mentioned above for =>3.0 for Debug mode
urlpatterns = [
...
]
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And also the part that caught me out, the above static URL only worked in my main project urls.py file. I was first attempting to add to my app, and wondering why I couldn't see the images.
Lastly make sure you set the following:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I'm not sure, what you mean as the 'mobile width'. But in each case, the CSS @media
can be used for hiding elements in the screen width basis. See some example:
<div id="my-content"></div>
...and:
@media screen and (min-width: 0px) and (max-width: 400px) {
#my-content { display: block; } /* show it on small screens */
}
@media screen and (min-width: 401px) and (max-width: 1024px) {
#my-content { display: none; } /* hide it elsewhere */
}
Some truly mobile detection is kind of hard programming and rather difficult. Eventually see the: http://detectmobilebrowsers.com/ or other similar sources.
For batch processing with files in folder aiming for 190 VBR and file extension = .mp3 instead of .ac3.mp3 you can use the following code
Change .ac3 to whatever the source audio format is.
for f in *.ac3 ; do ffmpeg -i "$f" -acodec libmp3lame -q:a 2 "${f%.*}.mp3"; done
Your function would work like this:
CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;
END
$$ LANGUAGE plpgsql;
Call:
SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.
The aggregate function count()
returns bigint
, but you had rowcount
defined as integer
, so you need an explicit cast ::int
to make this work
I use dollar quoting to avoid quoting hell.
However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.
Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)
The query itself seems rather odd, btw. But that's beside the point here.
here after a simple solution using sscanf
:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char str[256]="ab234cid*(s349*(20kd";
char tmp[256];
int main()
{
int x;
tmp[0]='\0';
while (sscanf(str,"%[^0123456789]%s",tmp,str)>1||sscanf(str,"%d%s",&x,str))
{
if (tmp[0]=='\0')
{
printf("%d\r\n",x);
}
tmp[0]='\0';
}
}
Pandas version 0.21 has changed the drop
method slightly to include both the index
and columns
parameters to match the signature of the rename
and reindex
methods.
df.drop(columns=['column_a', 'column_c'])
Personally, I prefer using the axis
parameter to denote columns or index because it is the predominant keyword parameter used in nearly all pandas methods. But, now you have some added choices in version 0.21.
It is also possible to place the MySQL data directory in a tmpfs in thus speeding up the database write and read calls. It might not be the most efficient way to do this but sometimes you can't just change the storage engine.
Here is my fstab entry for my MySQL data directory
none /opt/mysql/server-5.6/data tmpfs defaults,size=1000M,uid=999,gid=1000,mode=0700 0 0
You may also want to take a look at the innodb_flush_log_at_trx_commit=2 setting. Maybe this will speedup your MySQL sufficently.
innodb_flush_log_at_trx_commit changes the mysql disk flush behaviour. When set to 2 it will only flush the buffer every second. By default each insert will cause a flush and thus cause more IO load.
In Python 3.x and 2.7, you can simply do this:
>>> '${:,.2f}'.format(1234.5)
'$1,234.50'
The :,
adds a comma as a thousands separator, and the .2f
limits the string to two decimal places (or adds enough zeroes to get to 2 decimal places, as the case may be) at the end.
You can use HTML5 <figcaption>
:
<figure>
<img src="img.jpg" alt="my img"/>
<figcaption> Your text </figcaption>
</figure>
I will answer the question even though it has been a long time since it was thrown, just in case someone else get to it.
Tested on Android Studio ONLY (but I guess it could work for Eclipse as well) :
Check your build/source/r folder. In there, you should find some directories labelled under the name of your gradle build name (default : debug). Verify that the name of the package associated with R is the one you want.
I know this trick solves the problem of switching namespace, because Android Studio (or Gradle I don't know who is responsible for that) seems not to regenerate it in that case.
I haven't tried it when importing a project from Eclipse though.
Modify your Jquery in following way:
$.ajax({
url: someurl,
contentType: 'application/json',
data: JSONObject,
headers: { 'Access-Control-Allow-Origin': '*' }, //add this line
dataType: 'json',
type: 'POST',
success: function (Data) {....}
});
If you want to change anything else instead of 'default', then just add these additional lines to your Vagrantfile:
config.vm.define "tendo" do |tendo|
end
Where "tendo" will be the name that will appear instead of default
The manual for GNU Make gives a clear definition for all
in its list of standard targets.
If the author of the Makefile is following that convention then the target all
should:
make
should do the same as make all
.To achieve 1 all
is typically defined as a .PHONY
target that depends on the executable(s) that form the entire program:
.PHONY : all
all : executable
To achieve 2 all
should either be the first target defined in the make file or be assigned as the default goal:
.DEFAULT_GOAL := all
A solution that nobody mentioned is use white-space: nowrap
for the table and add overflow-x
to the wrapper.
(http://jsfiddle.net/xc7jLuyx/11/)
CSS
.wrapper { overflow-x: auto; }
.wrapper table { white-space: nowrap }
HTML
<div class="wrapper">
<table></table>
</div>
This is an ideal scenario if you don't want rows with multiple lines.
To add break lines you need to use <br/>
.
var tds = document.getElementById("ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a").getElementsByTagName("td");
time = tds[0].firstChild.value;
address = tds[3].firstChild.value;
You can't use UIImagePickerController
, but you can use a custom image picker. I think ELCImagePickerController
is the best option, but here are some other libraries you could use:
Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection
Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker
Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.
If your object could contain any key/value pairs, you could declare an interface called keyable
like :
interface keyable {
[key: string]: any
}
then use it as follows :
let countryProviders: keyable[];
or
let countryProviders: Array<keyable>;
select
id,
case
when report_type = 'P'
then amount
when report_type = 'N'
then -amount
else null
end
from table
You can try max-height: 70px; See if that works.
You can get value by using id for that element in onclick function
function dosomething(){
var buttonValue = document.getElementById('buttonId').value;
}
Use Diagrams
| Show Diagram...
from the context menu of a package. Invoking it on the project root will show module dependencies diagram.
If you need multiple packages, you can drag & drop them to the already opened diagram for the first package and press e to expand it.
Note: This feature is available in the Ultimate Edition, not the free Community Edition.
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
As loganfsmyth already stated in his answer, you need to purge git history because the files continue to exist there even after deleting them from the repo. Official GitHub docs recommend BFG which I find easier to use than filter-branch
:
Download BFG from their website. Make sure you have java installed, then create a mirror clone and purge history. Make sure to replace YOUR_FILE_NAME
with the name of the file you'd like to delete:
git clone --mirror git://example.com/some-big-repo.git
java -jar bfg.jar --delete-files YOUR_FILE_NAME some-big-repo.git
cd some-big-repo.git
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push
Same as above but use --delete-folders
java -jar bfg.jar --delete-folders YOUR_FOLDER_NAME some-big-repo.git
BFG also allows for even fancier options (see docs) like these:
Remove all files bigger than 100M from history:
java -jar bfg.jar --strip-blobs-bigger-than 100M some-big-repo.git
When running BFG, be careful that both YOUR_FILE_NAME
and YOUR_FOLDER_NAME
are indeed just file/folder names. They're not paths, so something like foo/bar.jpg
will not work! Instead all files/folders with the specified name will be removed from repo history, no matter which path or branch they existed.
For those of you using Django 1.6 or newer, note that execute_manager was removed. There is a solution posted in the second SO answer here.
You can also use ng-template, I think that would be more efficient while run time :)
<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
<div>2</div>
</ng-template>
Cheers
Please try adding the double quotes git commit -m "initial commit". This will solve your problem.
This one disables all bogus verbs and only allows GET and POST
<system.webServer>
<security>
<requestFiltering>
<verbs allowUnlisted="false">
<clear/>
<add verb="GET" allowed="true"/>
<add verb="POST" allowed="true"/>
</verbs>
</requestFiltering>
</security>
</system.webServer>
Git doesn't think in terms of file versions. A version in git is a snapshot of the entire tree.
Given this, what you really want is a tree that has the latest content of most files, but with the contents of one file the same as it was 5 commits ago. This will take the form of a new commit on top of the old ones, and the latest version of the tree will have what you want.
I don't know if there's a one-liner that will revert a single file to the contents of 5 commits ago, but the lo-fi solution should work: checkout master~5
, copy the file somewhere else, checkout master
, copy the file back, then commit.
Adding on to the one mentioned by @abarnert
a better one is to catch the exception
import subprocess
try:
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)
#print('py2 said:', py2output)
print "here"
except subprocess.CalledProcessError as e:
print "Calledprocerr"
this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting
python: can't open file 'py2.py': [Errno 2] No such file or directory
Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script
From book :
Choose a Random Row Using an Offset
Still another technique that avoids problems found in the preceding alternatives is to count the rows in the data set and return a random number between 0 and the count. Then use this number as an offset when querying the data set
$rand = "SELECT ROUND(RAND() * (SELECT COUNT(*) FROM Bugs))";
$offset = $pdo->query($rand)->fetch(PDO::FETCH_ASSOC);
$sql = "SELECT * FROM Bugs LIMIT 1 OFFSET :offset";
$stmt = $pdo->prepare($sql);
$stmt->execute( $offset );
$rand_bug = $stmt->fetch();
Use this solution when you can’t assume contiguous key values and you need to make sure each row has an even chance of being selected.
No, there isn't any equivalent of async/await in Java - or even in C# before v5.
It's a fairly complex language feature to build a state machine behind the scenes.
There's relatively little language support for asynchrony/concurrency in Java, but the java.util.concurrent
package contains a lot of useful classes around this. (Not quite equivalent to the Task Parallel Library, but the closest approximation to it.)
IF you have done everything above and still nothing worked for you then try adding $(inherited)
in Framework search path of your target's build setting.
I can't think of a specific example when it is good to run explicit GC.
In general, running explicit GC can actually cause more harm than good, because an explicit gc will trigger a full collection, which takes significantly longer as it goes through every object. If this explicit gc ends up being called repeatedly it could easily lead to a slow application as a lot of time is spent running full GCs.
Alternatively if going over the heap with a heap analyzer and you suspect a library component to be calling explicit GC's you can turn it off adding: gc=-XX:+DisableExplicitGC to the JVM parameters.
You can also use this:
DF[paste0("stu",c(2,3,5,9)), ]
You can use echo and prefix "\033", simple:
Artisan::command('mycommand', function () {
echo "\033======== Start ========\n";
});
And change color text:
if (App::environment() === 'production') {
echo "\033[0;33m======== WARNING ========\033[0m\n";
}
If you're using Angular 1, I would recommend using Angular's built-in method:
angular.isDefined(value);
reference : https://docs.angularjs.org/api/ng/function/angular.isDefined
You have to export
it from your NgModule
:
@NgModule({
declarations: [TaskCardComponent],
exports: [TaskCardComponent],
imports: [MdCardModule],
providers: []
})
export class TaskModule{}
The LoggerFactory class is msising according to the error message:
java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory
Apparently, the slf4j.jar
file is not getting loaded for some reason.
None of the previous suggestions worked for me in jQuery 1.7.2 because I'm trying to set the selected index of the list based on the value from a textbox, and some text values are contained in multiple options. I ended up using the following:
$('#mySelect option:contains(' + value + ')').each(function(){
if ($(this).text() == value) {
$(this).attr('selected', 'selected');
return false;
}
return true;
});
Summary:
Consider this script, called funcdemo
:
#!/bin/bash
[ $# = 0 ] && exhort "write nastygram"
exhort(){
echo "Please, please do not forget to $*"
}
[ $# != 0 ] && exhort "write begging letter"
In use:
$ funcdemo
./funcdemo: line 3: exhort: command not found
$ funcdemo 1
Please, please do not forget to write begging letter
$
Note the potential for a missing function to lie undiscovered for a long time (think 'by a customer at the most critical wrong moment'). It only matters whether the function exists when it is executed, the same as it only matters whether any other command exists when you try to execute it. Indeed, until it goes to execute the command, the shell neither knows nor cares whether it is an external command or a function.
They are saved in YOUR_APP.exe.config
, the file is saved in the same folder with YOUR_APP.exe
file, <userSettings>
section:
<userSettings>
<ShowGitlabIssues.Properties.Settings>
<setting name="SavedUserName" serializeAs="String">
<value />
</setting>
<setting name="SavedPassword" serializeAs="String">
<value />
</setting>
<setting name="CheckSave" serializeAs="String">
<value>False</value>
</setting>
</ShowGitlabIssues.Properties.Settings>
</userSettings>
here is cs code:
public void LoadInfoLogin()
{
if (Properties.Settings.Default.CheckSave)// chkRemember.Checked)
{
txtUsername.Text = Properties.Settings.Default.SaveUserName;
txtPassword.Text = Properties.Settings.Default.SavePassword;
chkRemember.Checked = true;
}
...
IMHO the method UserForm_Initialize should remain private bacause it is event handler for Initialize event of the UserForm.
This event handler is called when new instance of the UserForm is created. In this even handler u can initialize the private members of UserForm1 class.
Example:
Standard module code:
Option Explicit
Public Sub Main()
Dim myUserForm As UserForm1
Set myUserForm = New UserForm1
myUserForm.Show
End Sub
User form code:
Option Explicit
Private m_initializationDate As Date
Private Sub UserForm_Initialize()
m_initializationDate = VBA.DateTime.Date
MsgBox "Hi from UserForm_Initialize event handler.", vbInformation
End Sub
This answer should be more of a comment against Dawn Song's comment earlier, but since I don't have enough reputation, I'm going to write it as an answer.
According to the forum page
https://forums.developer.apple.com/thread/11313
"In general, you should never just delete the CoreSimulator/Devices directory yourself. If you really absolutely must, you need to make sure that the service is not runnign while you do that. eg:"
# Quit Xcode.app, Simulator.app, etc
sudo killall -9 com.apple.CoreSimulator.CoreSimulatorService
rm -rf ~/Library/*/CoreSimulator
I definitely ran into this issue after deleting and reinstalling Xcode.
You might encounter a problem trying to connect the build to a simulator device. The thread also answers what to do in that case,
gem install snapshot
fastlane snapshot reset_simulators
It really depends on your definition of special characters. I find that a whitelist rather than a blacklist is the best approach in most situations:
tmp = Regex.Replace(n, "[^0-9a-zA-Z]+", "");
You should be careful with your current approach because the following two items will be converted to the same string and will therefore be indistinguishable:
"TRA-12:123"
"TRA-121:23"
For an easy copy-paste template I use this Perl snippet:
PATH=`echo $PATH | perl -pe s:/path/to/be/excluded::`
This way you don't need to escape the slashes for the substitute operator.
The only way it worked for me for arduino nano 33 iot is via pressing the reset button on the board continuously many time then press uoplad!
use: tag.id ; tag#class
in the tag variables in your css.
Howabout Bugzilla. Open source and what Mozilla uses.
Not naturally, no... However, a googling of the thing gave this: http://phpjs.org/functions/isset:454
if you have a string of date, then you should try this.
const FORMAT = "YYYY ddd MMM DD HH:mm";
const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300
const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019
or try this :
const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);
The standard Pinterest button code (which you can generate here), is an <a>
tag wrapping an <img>
of the Pinterest button.
If you don't include the pinit.js
script on your page, this <a>
tag will work "as-is". You could improve the experience by registering your own click handler on these tags that opens a new window with appropriate dimensions, or at least adding target="_blank"
to the tag to make it open clicks in a new window.
The tag syntax would look like:
<a href="http://pinterest.com/pin/create/button/?url={URI-encoded URL of the page to pin}&media={URI-encoded URL of the image to pin}&description={optional URI-encoded description}" class="pin-it-button" count-layout="horizontal">
<img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" />
</a>
If using the JavaScript versions of sharing buttons are ruining your page load times, you can improve your site by using asynchronous loading methods. For an example of doing this with the Pinterest button, check out my GitHub Pinterest button project with an improved HTML5 syntax.
Go to this file in: WampFolder\apps\phpmyadmin[phpmyadmin version]\config.inc.php
Usually wamp is in your main hard drive folder C:\wamp\
You will see something like:
$cfg['Servers'][$i]['user'] = 'YOUR USER NAME IS HERE';
$cfg['Servers'][$i]['password'] = 'AND YOU PASSWORD IS HERE';
Try using the password and username that you have on that file.
Biginteger
is an immutable class.
You need to explicitly assign value of your output to sum like this:
sum = sum.add(BigInteger.valueof(i));
From docs.python.org:
This example shows how to remove a directory tree on Windows where some of the files have their read-only bit set. It uses the onerror callback to clear the readonly bit and reattempt the remove. Any subsequent failure will propagate.
import os, stat import shutil def remove_readonly(func, path, _): "Clear the readonly bit and reattempt the removal" os.chmod(path, stat.S_IWRITE) func(path) shutil.rmtree(directory, onerror=remove_readonly)
In case it helps someone, I had a similar issue and the error was because of two reasons:
Not using the app's namespace before the url name
{% url 'app_name:url_name' %}
Missing single quotes around the url name (as pointed out here by Charlie)
Just use the FORMAT function (works on SQL Server 2012 or newer):
SELECT FORMAT(EmployeeID, '000000')
FROM dbo.RequestItems
WHERE ID=0
Reference: http://msdn.microsoft.com/en-us/library/hh213505.aspx
You'd need to wrap the two headings in a div
tag, and have that div tag use a style that does clear: both
. e.g:
<div style="clear: both">
<h2 style="float: left">Heading 1</h2>
<h3 style="float: right">Heading 2</h3>
</div>
<hr />
Having the hr
after the div
tag will ensure that it is pushed beneath both headers.
Or something very similar to that. Hope this helps.
As many have suggested, JRE v1.7 and above has File.toPath();
File yourFile = ...;
Path yourPath = yourFile.toPath();
On Oracle's jdk 1.7 documentation which is also mentioned in other posts above, the following equivalent code is described in the description for toPath() method, which may work for JRE v1.6;
File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());
To me it sounds like the simplest way to expose your git repository on the server (which seems to be a Windows machine) would be to share it as a network resource.
Right click the folder "MY_GIT_REPOSITORY" and select "Sharing". This will give you the ability to share your git repository as a network resource on your local network. Make sure you give the correct users the ability to write to that share (will be needed when you and your co-workers push to the repository).
The URL for the remote that you want to configure would probably end up looking something like
file://\\\\189.14.666.666\MY_GIT_REPOSITORY
If you wish to use any other protocol (e.g. HTTP, SSH) you'll have to install additional server software that includes servers for these protocols. In lieu of these the file sharing method is probably the easiest in your case right now.
If you want to do this with XML not programmatically you can use on your TextView:
android:autoLink="web"
android:linksClickable="true"
None of the above worked.
The solution was to copy the project locally (from the network drive).
Bookmarking this URL should give you a full-screen compose window, without any distractions:
https://mail.google.com/mail/?view=cm&fs=1&tf=1
Additionally, if you want to be future-proof (see for instance how other URLs in this question stopped working) you can bookmark a link to:
mailto:
It will open your default email client and you probably already have Gmail configured for that purpose.
This is so simple if on windows...
In the folder where you have youtube-dl.exe
goto https://www.gyan.dev/ffmpeg/builds/
download the ffmpeg-git-full.7z file the download link is https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-full.7z
Open that zip file and move the ffmpeg.exe file to the same folder where youtube-dl.exe is
Example "blahblah.7z / whatevertherootfolderis / bin / ffmpeg.exe"
youtube-dl.exe -x --audio-format mp3 -o %(title)s.%(ext)s https://www.youtube.com/watch?v=wyPKRcBTsFQ
I have had excellent success with a technique which resembles the X macros pointed to by @RolandXu. We made heavy use of the stringize operator, too. The technique mitigates the maintenance nightmare when you have an application domain where items appear both as strings and as numerical tokens.
It comes in particularily handy when machine readable documentation is available so that the macro X(...) lines can be auto-generated. A new documentation would immediately result in a consistent program update covering the strings, enums and the dictionaries translating between them in both directions. (We were dealing with PCL6 tokens).
And while the preprocessor code looks pretty ugly, all those technicalities can be hidden in the header files which never have to be touched again, and neither do the source files. Everything is type safe. The only thing that changes is a text file containing all the X(...) lines, and that is possibly auto generated.
I have a wrapper project (pyscreenshot) for scrot, imagemagick, pyqt, wx and pygtk. If you have one of them, you can use it. All solutions are included from this discussion.
Install:
easy_install pyscreenshot
Example:
import pyscreenshot as ImageGrab
# fullscreen
im=ImageGrab.grab()
im.show()
# part of the screen
im=ImageGrab.grab(bbox=(10,10,500,500))
im.show()
# to file
ImageGrab.grab_to_file('im.png')
The standard Python libraries don't include any tzinfo classes (but see pep 431). I can only guess at the reasons. Personally I think it was a mistake not to include a tzinfo class for UTC, because that one is uncontroversial enough to have a standard implementation.
Edit: Although there's no implementation in the library, there is one given as an example in the tzinfo
documentation.
from datetime import timedelta, tzinfo
ZERO = timedelta(0)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
To use it, to get the current time as an aware datetime object:
from datetime import datetime
now = datetime.now(utc)
There is datetime.timezone.utc
in Python 3.2+:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
I have cuDNN 8.0 and none of the suggestions above worked for me. The desired information was in /usr/include/cudnn_version.h
, so
cat /usr/include/cudnn_version.h | grep CUDNN_MAJOR -A 2
did the trick.
I'm late to this party, but for any future C folks on Windows, Visual Studio targets C90 instead of C99, which is what you'd get on *nix. I am currently targeting C99 on Windows by using Sublime Text 2 in tandem with Cygwin.
Really fast, really easy:
srand(time(NULL)); // Seed the time
int finalNum = rand()%(max-min+1)+min; // Generate the number, assign to variable.
And that is it. However, this is biased towards the lower end, but if you are using C++ TR1/C++11 you can do it using the random
header to avoid that bias like so:
#include <random>
std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max); // uniform, unbiased
int r = gen(rng);
But you can also remove the bias in normal C++ like this:
int rangeRandomAlg2 (int min, int max){
int n = max - min + 1;
int remainder = RAND_MAX % n;
int x;
do{
x = rand();
}while (x >= RAND_MAX - remainder);
return min + x % n;
}
and that was gotten from this post.
for android studio 3.1
If you want your default android studio change, just follow bellow steps:
first
go to C:\Program Files\Android\Android Studio\plugins\android\lib\templates\activities\common\root\res\layout
i.e. the file directory where you have installed android studio.
then
copy simple.xml from another place just for backup
after that
open simple.xml file and replace it's code as bellow
<?xml version="1.0" encoding="utf-8"
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}">
</RelativeLayout>
but if you just want to change this project layout, just go to activity_main.xml and then go to text and post upper code to there
You can also just search on sites like Tucows and CNET, they have it there too.
If you use the library underscore you can write like this
var unionArr = _.union([34,35,45,48,49], [48,55]);_x000D_
console.log(unionArr);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
_x000D_
This answers is to add an alternative for those VIM users like I that prefers to do everything within the editor.
Tpope came up with this great plugin for VIM called fugitive. Once installed you can run :Gstatus
to check the files that have conflict and :Gdiff
to open Git in a 3 ways merge.
Once in the 3-ways merge, fugitive will let you get the changes of any of the branches you are merging in the following fashion:
:diffget //2
, get changes from original (HEAD) branch: :diffget //3
, get changes from merging branch: Once you are finished merging the file, type :Gwrite
in the merged buffer.
Vimcasts released a great video explaining in detail this steps.
To complement the AmitD answer:
Just copy/pasted your program and had this output:
Error!
Enter first num:
.... infinite times ....
As you can see, the instruction:
n1 = input.nextInt();
Is continuously throwing the Exception when your double number is entered, and that's because your stream is not cleared. To fix it, follow the AmitD answer.
coord_flip()
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
qplot(cut, carat, data = diamonds, geom = "boxplot") +
coord_flip()
str_wrap()
# wrap text to no more than 15 spaces
library(stringr)
diamonds$cut2 <- str_wrap(diamonds$cut, width = 15)
qplot(cut2, carat, data = diamonds, geom = "boxplot") +
coord_flip()
In Ch 3.9 of R for Data Science, Wickham and Grolemund speak to this exact question:
coord_flip()
switches the x and y axes. This is useful (for example), if you want horizontal boxplots. It’s also useful for long labels: it’s hard to get them to fit without overlapping on the x-axis.
Reason for the error:
Column
expands to the maximum size in main axis direction (vertical axis), and so does the ListView
.
Solutions
So, you need to constrain the height of the ListView
. There are many ways of doing it, you can choose that best suits your need.
If you want to allow ListView
to take up all remaining space inside Column
use Expanded
.
Column(
children: <Widget>[
Expanded(
child: ListView(...),
)
],
)
If you want to limit your ListView
to certain height
, you can use SizedBox
.
Column(
children: <Widget>[
SizedBox(
height: 200, // constrain height
child: ListView(),
)
],
)
If your ListView
is small, you may try shrinkWrap
property on it.
Column(
children: <Widget>[
ListView(
shrinkWrap: true, // use it
)
],
)
Only when you can use ECMAScript 6 or transpilers.
Features:
Code:
function clone(target, source){
for(let key in source){
// Use getOwnPropertyDescriptor instead of source[key] to prevent from trigering setter/getter.
let descriptor = Object.getOwnPropertyDescriptor(source, key);
if(descriptor.value instanceof String){
target[key] = new String(descriptor.value);
}
else if(descriptor.value instanceof Array){
target[key] = clone([], descriptor.value);
}
else if(descriptor.value instanceof Object){
let prototype = Reflect.getPrototypeOf(descriptor.value);
let cloneObject = clone({}, descriptor.value);
Reflect.setPrototypeOf(cloneObject, prototype);
target[key] = cloneObject;
}
else {
Object.defineProperty(target, key, descriptor);
}
}
let prototype = Reflect.getPrototypeOf(source);
Reflect.setPrototypeOf(target, prototype);
return target;
}
GIMP ( Graphic Image Manipulation Program) does a pretty good job... http://www.makeuseof.com/tag/create-image-map-gimp/
The width attribute of <td>
is deprecated in HTML 5.
Use CSS. e.g.
<td style="width:100px">
in detail, like this:
<table >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td style="width:70%">January</td>
<td style="width:30%">$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
In Microsoft Excel Office 2007 try installing "Web Service Reference Tool" plugin. And use the WSDL and add the web-services. And use following code in module to fetch the necessary data from the web-service.
Sub Demo()
Dim XDoc As MSXML2.DOMDocument
Dim xEmpDetails As MSXML2.IXMLDOMNode
Dim xParent As MSXML2.IXMLDOMNode
Dim xChild As MSXML2.IXMLDOMNode
Dim query As String
Dim Col, Row As Integer
Dim objWS As New clsws_GlobalWeather
Set XDoc = New MSXML2.DOMDocument
XDoc.async = False
XDoc.validateOnParse = False
query = objWS.wsm_GetCitiesByCountry("india")
If Not XDoc.LoadXML(query) Then 'strXML is the string with XML'
Err.Raise XDoc.parseError.ErrorCode, , XDoc.parseError.reason
End If
XDoc.LoadXML (query)
Set xEmpDetails = XDoc.DocumentElement
Set xParent = xEmpDetails.FirstChild
Worksheets("Sheet3").Cells(1, 1).Value = "Country"
Worksheets("Sheet3").Cells(1, 1).Interior.Color = RGB(65, 105, 225)
Worksheets("Sheet3").Cells(1, 2).Value = "City"
Worksheets("Sheet3").Cells(1, 2).Interior.Color = RGB(65, 105, 225)
Row = 2
Col = 1
For Each xParent In xEmpDetails.ChildNodes
For Each xChild In xParent.ChildNodes
Worksheets("Sheet3").Cells(Row, Col).Value = xChild.Text
Col = Col + 1
Next xChild
Row = Row + 1
Col = 1
Next xParent
End Sub
You need to tell the query what value to pick for the other columns, MIN
or MAX
seem like suitable choices.
SELECT
U.NAME, MIN(P.PIC_ID)
FROM
USERS U,
PICTURES P,
POSTINGS P1
WHERE
U.EMAIL_ID = P1.EMAIL_ID AND
P1.PIC_ID = P.PIC_ID AND
P.CAPTION LIKE '%car%'
GROUP BY
U.NAME;
void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
{
TextBox txt = (TextBox)sender;
var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
string str = txt.Text + e.Text.ToString();
int cntPrc = 0;
if (str.Contains('.'))
{
string[] tokens = str.Split('.');
if (tokens.Count() > 0)
{
string result = tokens[1];
char[] prc = result.ToCharArray();
cntPrc = prc.Count();
}
}
if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
for centos, just zlib didn't solve the problem.I did
sudo yum install zlib-devel.i686
Resource is a RESTful subset of Endpoint.
An endpoint by itself is the location where a service can be accessed:
https://www.google.com # Serves HTML
8.8.8.8 # Serves DNS
/services/service.asmx # Serves an ASP.NET Web Service
A resource refers to one or more nouns being served, represented in namespaced fashion, because it is easy for humans to comprehend:
/api/users/johnny # Look up johnny from a users collection.
/v2/books/1234 # Get book with ID 1234 in API v2 schema.
All of the above could be considered service endpoints, but only the bottom group would be considered resources, RESTfully speaking. The top group is not expressive regarding the content it provides.
A REST request is like a sentence composed of nouns (resources) and verbs (HTTP methods):
GET
(method) the user named johnny
(resource).DELETE
(method) the book with id 1234
(resource).Endpoint typically refers to a service, but resource could mean a lot of things. Here are some examples of resource that are dependent on the context they're used in.
Something that can be used to help you:
The library was a valuable resource, and he frequently made use of it.
Resources are natural substances such as water and wood which are valuable in supporting life:
[ pl ] The earth has limited resources, and if we don’t recycle them we use them up.
Resources are also things of value such as money or possessions that you can use when you need them:
[ pl ] The government doesn’t have the resources to hire the number of teachers needed.
The term resource by definition has a lot of nuance. It all depends on the context its used in.
Consider the easy, lightweight Java library EasyFlow. From their docs:
With EasyFlow you can:
- implement complex logic but keep your code simple and clean
- handle asynchronous calls with ease and elegance
- avoid concurrency by using event-driven programming approach
- avoid StackOverflow error by avoiding recursion
- simplify design, programming and testing of complex java applications
The dot character means match any character, so .*
means zero or more occurrences of any character. You probably mean to use .*
rather than just *
.
to pass many options you can pass a object to a @Input decorator with custom data in a single line.
In the template
<li *ngFor = 'let opt of currentQuestion.options'
[selectable] = 'opt'
[myOptions] ="{first: opt.val1, second: opt.val2}" // these are your multiple parameters
(selectedOption) = 'onOptionSelection($event)' >
{{opt.option}}
</li>
so in Directive class
@Directive({
selector: '[selectable]'
})
export class SelectableDirective{
private el: HTMLElement;
@Input('selectable') option:any;
@Input('myOptions') data;
//do something with data.first
...
// do something with data.second
}
working in my code.
private FragmentSampleBinding dataBiding;
private SampleListAdapter mAdapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
dataBiding = DataBindingUtil.inflate(inflater, R.layout.fragment_sample, null, false);
return mView = dataBiding.getRoot();
}
To get last inserted id in codeigniter
After executing insert query just use one function called insert_id()
on database, it will return last inserted id
Ex:
$this->db->insert('mytable',$data);
echo $this->db->insert_id(); //returns last inserted id
in one line
echo $this->db->insert('mytable',$data)->insert_id();
In plist add ----
View controller-based status bar appearance --- NO
In each viewController write
- (void) viewDidLayoutSubviews
{
CGRect viewBounds = self.view.bounds;
CGFloat topBarOffset = 20.0;
viewBounds.origin.y = -topBarOffset;
self.view.bounds = viewBounds;
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];//for status bar style
}
For status bar issue in iOS 7 but target should be 5.1 and above for the app
You probably want to check the length of the string first and do something like this:
if (!myStr.empty())
{
char lastChar = *myStr.rbegin();
}
Analytics! This avoids having to access the table twice:
SELECT DISTINCT
FIRST_VALUE(date_col) OVER (ORDER BY value_col DESC, date_col ASC),
FIRST_VALUE(value_col) OVER (ORDER BY value_col DESC, date_col ASC)
FROM mytable;
Open your php.ini file use CNTRL+F to search for the following settings which may be the culprit:
Make sure to save a copy of the php.ini prior to making changes. You will want to adjust the settings to accommodate your file size, and increase input and/or execution time.
Remember to restart your services after making changes.
Warning! There may be some unforeseen drawbacks if you adjust these settings too liberally. I am not expert enough to know this for sure.
You should always avoid using system()
because
You should use CreateProcess().
You can use Createprocess() to just start up an .exe and creating a new process for it. The application will run independent from the calling application.
Here's an example I used in one of my projects:
#include <windows.h>
VOID startup(LPCTSTR lpApplicationName)
{
// additional information
STARTUPINFO si;
PROCESS_INFORMATION pi;
// set the size of the structures
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
// start the program up
CreateProcess( lpApplicationName, // the path
argv[1], // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi // Pointer to PROCESS_INFORMATION structure (removed extra parentheses)
);
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
EDIT: The error you are getting is because you need to specify the path of the .exe file not just the name. Openfile.exe probably doesn't exist.
I use the method above to set the map boundaries, then, instead of resetting the zoom level, I just calculate the average LAT and average LON and set the center point to that location. I add up all the lat values into latTotal and all the lon values into lontotal and then divide by the number of markers. I then set the map center point to those average values.
latCenter = latTotal / markercount; lonCenter = lontotal / markercount;
Thank you first
Use overflow:auto
it works for me.
horizontal scroll bar disappears.
I tried all the listed solutions above but nothing worked. This is what worked for me.
Absolute XPath: It is the direct way to find the element, but the disadvantage of the absolute XPath is that if there are any changes made in the path of the element then that XPath gets failed.
The key characteristic of XPath is that it begins with the single forward slash(/) ,which means you can select the element from the root node.
Below is the example of an absolute xpath.
/html/body/div[1]/section/div/div[2]/div/form/div[2]/input[3]
Relative Xpath: Relative Xpath starts from the middle of HTML DOM structure. It starts with double forward slash (//). It can search elements anywhere on the webpage, means no need to write a long xpath and you can start from the middle of HTML DOM structure. Relative Xpath is always preferred as it is not a complete path from the root element.
Below is the example of a relative XPath.
//input[@name=’email’]
I can come up with 2 ways to achieve it.
The first one is to remove novalidate
to enable the browser's validation.
Second, you can disable the save
button when the form is not valid like this
<input ng-disabled="!frmRegister.$valid" type="submit" value="Save" />
Hope it helps.
You can't, but you can use BETWEEN
SELECT job FROM mytable WHERE id BETWEEN 10 AND 15
Note that BETWEEN
is inclusive, and will include items with both id 10 and 15.
If you do not want inclusion, you'll have to fall back to using the >
and <
operators.
SELECT job FROM mytable WHERE id > 10 AND id < 15
If removing \0 from the end of string is impossible, you can add your own character for each string you encode, and remove it on decode.
In Java, byte
(N=8) and int
(N=32) are represented by the 2s-complement shown above.
From the equation, a7 is negative for byte
but positive for int
.
coef: a7 a6 a5 a4 a3 a2 a1 a0
Binary: 1 0 0 0 0 1 0 0
----------------------------------------------
int: 128 + 0 + 0 + 0 + 0 + 4 + 0 + 0 = 132
byte: -128 + 0 + 0 + 0 + 0 + 4 + 0 + 0 = -124
I was having a text something like:
Forgot Password? Reset here.
To implement this the easy way I used the existing android:textStyle="bold"
<LinearLayout
android:id="@+id/forgotPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="all"
android:linksClickable="false"
android:selectAllOnFocus="false"
android:text="Forgot password? "
android:textAlignment="center"
android:textColor="@android:color/white"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="all"
android:linksClickable="false"
android:selectAllOnFocus="false"
android:text="Reset here"
android:textAlignment="center"
android:textColor="@android:color/white"
android:textStyle="bold" />
</LinearLayout>
Maybe it helps someone
I imagine this like that:
<html>
<head>
<script>
var frame_loaded = 0;
function setFrameLoaded()
{
frame_loaded = 1;
alert("Iframe is loaded");
}
$('#click').click(function(){
if(frame_loaded == 1)
console.log('iframe loaded')
} else {
console.log('iframe not loaded')
}
})
</script>
</head>
<button id='click'>click me</button>
<iframe id='MainPopupIframe' onload='setFrameLoaded();' src='http://...' />...</iframe>
Previous answers have covered the use of git rebase -i
to edit the commit that you want to split, and committing it in parts.
This works well when splitting the files into different commits, but if you want to break apart changes to the individual files, there's more you need to know.
Having got to the commit you want to split, using rebase -i
and marking it for edit
, you have two options.
After using git reset HEAD~
, go through the patches individually using git add -p
to select the ones you want in each commit
Edit the working copy to remove the changes you do not want; commit that interim state; and then pull back the full commit for the next round.
Option 2 is useful if you're splitting a large commit, as it lets you check that the interim versions build and run properly as part of the merge. This proceeds as follows.
After using rebase -i
and edit
ing the commit, use
git reset --soft HEAD~
to undo the commit, but leave the committed files in the index. You can also do a mixed reset by omitting --soft, depending on how close to the final result your initial commit is going to be. The only difference is whether you start with all the changes staged or with them all unstaged.
Now go in and edit the code. You can remove changes, delete added files, and do whatever you want to construct the first commit of the series you're looking for. You can also build it, run it, and confirm that you have a consistent set of source.
Once you're happy, stage/unstage the files as needed (I like to use git gui
for this), and commit the changes through the UI or the command line
git commit
That's the first commit done. Now you want to restore your working copy to the state it had after the commit you are splitting, so that you can take more of the changes for your next commit. To find the sha1 of the commit you're editing, use git status
. In the first few lines of the status you'll see the rebase command that is currently executing, in which you can find the sha1 of your original commit:
$ git status
interactive rebase in progress; onto be83b41
Last commands done (3 commands done):
pick 4847406 US135756: add debugging to the file download code
e 65dfb6a US135756: write data and download from remote
(see more in file .git/rebase-merge/done)
...
In this case, the commit I'm editing has sha1 65dfb6a
. Knowing that, I can check out the content of that commit over my working directory using the form of git checkout
which takes both a commit and a file location. Here I use .
as the file location to replace the whole working copy:
git checkout 65dfb6a .
Don't miss the dot on the end!
This will check out, and stage, the files as they were after the commit you're editing, but relative to the previous commit you made, so any changes you already committed won't be part of the commit.
You can either go ahead now and commit it as-is to finish the split, or go around again, deleting some parts of the commit before making another interim commit.
If you want to reuse the original commit message for one or more commits, you can use it straight from the rebase's working files:
git commit --file .git/rebase-merge/message
Finally, once you've committed all the changes,
git rebase --continue
will carry on and complete the rebase operation.
A bit late for the party, but this regular expression helped me to validate email type input in the client side. Though, we should always do verification in server side also.
<input type="email" pattern="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$">
You can find more regex of all kinds here.
There would be a filename mentioned after Command failed due to signal: Segmentation fault: 11 . Atleast in my case it was. With Swift upgrade to 2.0 some of the core properties were changes to optional. On not handling it appropriately it threw that error. Handling the optional well dismissed the error. In my case it was due to not handling :
if let scheduledNotifications = UIApplication.sharedApplication().scheduledLocalNotifications as [UILocalNotification]?{
}
Good Luck!
Basically, when your FROM clause lists tables like so:
SELECT * FROM
tableA, tableB, tableC
the result is a cross product of all the rows in tables A, B, C. Then you apply the restriction WHERE tableA.id = tableB.a_id
which will throw away a huge number of rows, then further ... AND tableB.id = tableC.b_id
and you should then get only those rows you are really interested in.
DBMSs know how to optimise this SQL so that the performance difference to writing this using JOINs is negligible (if any). Using the JOIN notation makes the SQL statement more readable (IMHO, not using joins turns the statement into a mess). Using the cross product, you need to provide join criteria in the WHERE clause, and that's the problem with the notation. You are crowding your WHERE clause with stuff like
tableA.id = tableB.a_id
AND tableB.id = tableC.b_id
which is only used to restrict the cross product. WHERE clause should only contain RESTRICTIONS to the resultset. If you mix table join criteria with resultset restrictions, you (and others) will find your query harder to read. You should definitely use JOINs and keep the FROM clause a FROM clause, and the WHERE clause a WHERE clause.
Frank's answer is good but Firestore introduced array-contains
recently that makes it easier to do AND queries.
You can create a filters
field to add you filters. You can add as many values as you need. For example to filter by comedy and Jack Nicholson you can add the value comedy_Jack Nicholson
but if you also you want to by comedy and 2014 you can add the value comedy_2014
without creating more fields.
{
"movies": {
"movie1": {
"genre": "comedy",
"name": "As good as it gets",
"lead": "Jack Nicholson",
"year": 2014,
"filters": [
"comedy_Jack Nicholson",
"comedy_2014"
]
}
}
}
with open ("test.txt","w")as fp:
for line in list12:
fp.write(line+"\n")
Simply cleaning the project solved it for me.
My project is a C++ application (not a shared library). I randomly got this error after a lot of successful builds.
I've been testing this myself, and looking at all the answers on this post and I don't think they answer this question very well. I experimented myself in order to get a good answer (code below). You CAN fire either event with both ActionListener and ItemListener 100% of the time when a state is changed in either a radio button or a check box, or any other kind of Swing item I'm assuming since it is type Object. The ONLY difference I can tell between these two listeners is the type of Event Object that gets returned with the listener is different. AND you get a better event type with a checkbox using an ItemListener as opposed to an ActionListener.
The return types of an ActionEvent and an ItemEvent will have different methods stored that may be used when an Event Type gets fired. In the code below the comments show the difference in .get methods for each Class returned Event type.
The code below sets up a simple JPanel with JRadioButtons, JCheckBoxes, and a JLabel display that changes based on button configs. I set all the RadioButtons and CheckBoxes up with both an Action Listener and an Item Listener. Then I wrote the Listener classes below with ActionListener fully commented because I tested it first in this experiment. You will notice that if you add this panel to a frame and display, all radiobuttons and checkboxes always fire regardless of the Listener type, just comment out the methods in one and try the other and vice versa.
Return Type into the implemented methods is the MAIN difference between the two. Both Listeners fire events the same way. Explained a little better in comment above is the reason a checkbox should use an ItemListener over ActionListener due to the Event type that is returned.
package EventHandledClasses;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RadioButtonsAndCheckBoxesTest extends JPanel{
JLabel display;
String funny, serious, political;
JCheckBox bold,italic;
JRadioButton funnyQuote, seriousQuote, politicalQuote;
ButtonGroup quotes;
public RadioButtonsAndCheckBoxesTest(){
funny = "You are not ugly, you were just born... different";
serious = "Recommend powdered soap in prison!";
political = "Trump can eat a little Bernie, but will choke on his Birdie";
display = new JLabel(funny);
Font defaultFont = new Font("Ariel",Font.PLAIN,20);
display.setFont(defaultFont);
bold = new JCheckBox("Bold",false);
bold.setOpaque(false);
italic = new JCheckBox("Italic",false);
italic.setOpaque(false);
//Color itemBackground =
funnyQuote = new JRadioButton("Funny",true);
funnyQuote.setOpaque(false);
seriousQuote = new JRadioButton("Serious");
seriousQuote.setOpaque(false);
politicalQuote = new JRadioButton("Political");
politicalQuote.setOpaque(false);
quotes = new ButtonGroup();
quotes.add(funnyQuote);
quotes.add(seriousQuote);
quotes.add(politicalQuote);
JPanel primary = new JPanel();
primary.setPreferredSize(new Dimension(550, 100));
Dimension standard = new Dimension(500, 30);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setPreferredSize(standard);
radioButtonsPanel.setBackground(Color.green);
radioButtonsPanel.add(funnyQuote);
radioButtonsPanel.add(seriousQuote);
radioButtonsPanel.add(politicalQuote);
JPanel checkBoxPanel = new JPanel();
checkBoxPanel.setPreferredSize(standard);
checkBoxPanel.setBackground(Color.green);
checkBoxPanel.add(bold);
checkBoxPanel.add(italic);
primary.add(display);
primary.add(radioButtonsPanel);
primary.add(checkBoxPanel);
//Add Action Listener To test Radio Buttons
funnyQuote.addActionListener(new ActionListen());
seriousQuote.addActionListener(new ActionListen());
politicalQuote.addActionListener(new ActionListen());
//Add Item Listener to test Radio Buttons
funnyQuote.addItemListener(new ItemListen());
seriousQuote.addItemListener(new ItemListen());
politicalQuote.addItemListener(new ItemListen());
//Add Action Listener to test Check Boxes
bold.addActionListener(new ActionListen());
italic.addActionListener(new ActionListen());
//Add Item Listener to test Check Boxes
bold.addItemListener(new ItemListen());
italic.addItemListener(new ItemListen());
//adds primary JPanel to this JPanel Object
add(primary);
}
private class ActionListen implements ActionListener{
public void actionPerformed(ActionEvent e) {
/*
Different Get Methods from ItemEvent
e.getWhen()
e.getModifiers()
e.getActionCommand()*/
/*int font=Font.PLAIN;
if(bold.isSelected()){
font += Font.BOLD;
}
if(italic.isSelected()){
font += Font.ITALIC;
}
display.setFont(new Font("Ariel",font,20));
if(funnyQuote.isSelected()){
display.setText(funny);
}
if(seriousQuote.isSelected()){
display.setText(serious);
}
if(politicalQuote.isSelected()){
display.setText(political);
}*/
}
}
private class ItemListen implements ItemListener {
public void itemStateChanged(ItemEvent arg0) {
/*
Different Get Methods from ActionEvent
arg0.getItemSelectable()
arg0.getStateChange()
arg0.getItem()*/
int font=Font.PLAIN;
if(bold.isSelected()){
font += Font.BOLD;
}
if(italic.isSelected()){
font += Font.ITALIC;
}
display.setFont(new Font("Ariel",font,20));
if(funnyQuote.isSelected()){
display.setText(funny);
}
if(seriousQuote.isSelected()){
display.setText(serious);
}
if(politicalQuote.isSelected()){
display.setText(political);
}
}
}
}
You need just to delete your older connector and download new version (mysql-connector-java-5.1.46)
Another way to do this (in modern browsers) is with a negative spread box-shadow. Check out this updated fiddle: http://jsfiddle.net/WuZat/290/
box-shadow: 0px 24px 3px -24px magenta;
I think the safest and most compatible way is the accepted answer above, though. Just thought I'd share another technique.
If you want date and time separate then use below expressions: Date and Time Expression
Expression1 for current date : =formatdatetime(today) its return date is = 11/15/2016
Expression2 for current time : =CDate(Now).ToString("hh:mm tt") its return time is = 3:44 PM
This report printed on Expression1 at Expression2
Output will be : Output of Both Expression
This report printed on 11/15/2016 at 3:44 PM
Since Ansible 2.5 the with_*
constructs are deprecated, and loop
syntax should be used. A simple practical example:
- name: Copy CA files
copy:
src: '{{item}}'
dest: '/etc/pki/ca-trust/source/anchors'
owner: root
group: root
mode: 0644
loop:
- symantec-private.crt
- verisignclass3g2.crt
I am from Angular as well and trying out React, as of now, one recommended(?) way seems to be using High-Order Components:
A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.
Let's say you have input
and textarea
and like to apply the same validation logic:
const Input = (props) => (
<input type="text"
style={props.style}
onChange={props.onChange} />
)
const TextArea = (props) => (
<textarea rows="3"
style={props.style}
onChange={props.onChange} >
</textarea>
)
Then write a HOC that does validate and style wrapped component:
function withValidator(WrappedComponent) {
return class extends React.Component {
constructor(props) {
super(props)
this.validateAndStyle = this.validateAndStyle.bind(this)
this.state = {
style: {}
}
}
validateAndStyle(e) {
const value = e.target.value
const valid = value && value.length > 3 // shared logic here
const style = valid ? {} : { border: '2px solid red' }
console.log(value, valid)
this.setState({
style: style
})
}
render() {
return <WrappedComponent
onChange={this.validateAndStyle}
style={this.state.style}
{...this.props} />
}
}
}
Now those HOCs share the same validating behavior:
const InputWithValidator = withValidator(Input)
const TextAreaWithValidator = withValidator(TextArea)
render((
<div>
<InputWithValidator />
<TextAreaWithValidator />
</div>
), document.getElementById('root'));
I created a simple demo.
Edit: Another demo is using props to pass an array of functions so that you can share logic composed by multiple validating functions across HOC
s like:
<InputWithValidator validators={[validator1,validator2]} />
<TextAreaWithValidator validators={[validator1,validator2]} />
Edit2: React 16.8+ provides a new feature, Hook, another nice way to share logic.
const Input = (props) => {
const inputValidation = useInputValidation()
return (
<input type="text"
{...inputValidation} />
)
}
function useInputValidation() {
const [value, setValue] = useState('')
const [style, setStyle] = useState({})
function handleChange(e) {
const value = e.target.value
setValue(value)
const valid = value && value.length > 3 // shared logic here
const style = valid ? {} : { border: '2px solid red' }
console.log(value, valid)
setStyle(style)
}
return {
value,
style,
onChange: handleChange
}
}
https://stackblitz.com/edit/react-shared-validation-logic-using-hook?file=index.js
This error also occurs if the branch you're trying to sync has been deleted.
git status
won't tell you that, but you'll get a "no such ref was fetched" message if you try git pull
.
android:focusedByDefault="true"
In Windows 10, it's still 8191 characters...at least on my machine.
It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.
Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.
echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat
testbat.bat
HashMap<String, Object> map1 = new HashMap<String, Object>();
Map<String, Object> map2 = new HashMap<String, Object>();
First of all Map
is an interface it has different implementation like - HashMap
, TreeHashMap
, LinkedHashMap
etc. Interface works like a super class for the implementing class. So according to OOP's rule any concrete class that implements Map
is a Map
also. That means we can assign/put any HashMap
type variable to a Map
type variable without any type of casting.
In this case we can assign map1
to map2
without any casting or any losing of data -
map2 = map1
There is a great implementation of NavigationDrawer
that follows the Google Material Design Guidelines (and compatible down to API 10) - The MaterialDrawer library (link to GitHub). As of time of writing, May 2017, it's actively supported.
It's available in Maven Central repo. Gradle dependency setup:
compile 'com.mikepenz:materialdrawer:5.9.1'
Maven dependency setup:
<dependency>
<groupId>com.mikepenz</groupId>
<artifactId>materialdrawer</artifactId>
<version>5.9.1</version>
</dependency>
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;
"referencedColumnName" property is the name of the column in the table that you are making reference with the column you are anotating. Or in a short manner: it's the column referenced in the destination table. Imagine something like this: cars and persons. One person can have many cars but one car belongs only to one person (sorry, I don't like anyone else driving my car).
Table Person
name char(64) primary key
age intTable Car
car_registration char(32) primary key
car_brand (char 64)
car_model (char64)
owner_name char(64) foreign key references Person(name)
When you implement classes you will have something like
class Person{
...
}
class Car{
...
@ManyToOne
@JoinColumn([column]name="owner_name", referencedColumnName="name")
private Person owner;
}
EDIT: as @searchengine27 has commented, columnName
does not exist as a field in persistence section of Java7 docs. I can't remember where I took this property from, but I remember using it, that's why I'm leaving it in my example.
To find the name of the current user within an Oracle session, use the USER
function.
Note that the owner of the constraint, the owner of the table containing the foreign key, and the owner of the referenced table may all be different. It sounds like it’s the table owner you’re interested in, in which case this should be close to what you want:
select Constraint_Name
from All_Constraints
where Table_Name = 'WHICHEVER_TABLE'
and Constraint_Type = 'R' and Owner = User;
Identify the hash of the commit, using git log
, then use git revert <commit>
to create a new commit that removes these changes. In a way, git revert
is the converse of git cherry-pick
-- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.
The state should be managed in the parent component. You can transfer the open
value to the child component by adding a property.
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
open: false
};
this.toggleChildMenu = this.toggleChildMenu.bind(this);
}
toggleChildMenu() {
this.setState(state => ({
open: !state.open
}));
}
render() {
return (
<div>
<button onClick={this.toggleChildMenu}>
Toggle Menu from Parent
</button>
<ChildComponent open={this.state.open} />
</div>
);
}
}
class ChildComponent extends Component {
render() {
return (
<Drawer open={this.props.open}/>
);
}
}
First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties
. In a WAR, WEB-INF/classes
is a classpath entry, so it will work just fine.
After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:
<context:property-placeholder location="classpath:config/properties/database.properties"/>
Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties
:
<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>
There's usually not any reason to define them separately, though.
Since JQuery 1.6, always use .prop() Read why here: http://api.jquery.com/prop/
if($('input').prop('readonly')){ }
.prop() can also be used to set the property
$('input').prop('readonly',true);
$('input').prop('readonly',false);
I found out why this happening.
After looking at my settings on my wamp, i did not check http headers, since activated this, it now works.
Thank you everyone for trying to solve this. :)
The width of the button is defined by the button text. So if you want to define the width of the button you can use a defined width by using pixel in the css or if you want to by responsive use a percentage value.
As said in the documentation:
Must: The clause (query) must appear in matching documents.
Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.
In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.
Since you want your results to satisfy all the queries, you should use must.
You can indeed use filters inside a boolean query.
The s///
command in sed
allows you to use other characters instead of /
as the delimiter, as in
sed 's#"http://www\.fubar\.com"#URL_FUBAR#g'
or
sed 's,"http://www\.fubar\.com",URL_FUBAR,g'
The double quotes are not a problem. For matching single quotes, switch the two types of quotes around. Note that a single quoted string may not contain single quotes (not even escaped ones).
The dots need to be escaped if sed
is to interpret them as literal dots and not as the regular expression pattern .
which matches any one character.
All the above solutions are good, but I like @Steve's and @bejota's the best as they do not involve fancy calls and are universal.
By universal I mean that works with any type of axes including GeoAxes
. For example, it you have projected axes for mapping:
projection = cartopy.crs.UTM(zone='17N')
ax = plt.axes(projection=projection)
im = ax.imshow(np.arange(200).reshape((20, 10)))
a call to
cax = divider.append_axes("right", size=width, pad=pad)
will fail with: KeyException: map_projection
Therefore, the only universal way of dealing colorbar size with all types of axes is:
ax.colorbar(im, fraction=0.046, pad=0.04)
Work with fraction from 0.035 to 0.046 to get your best size. However, the values for the fraction and paddig will need to be adjusted to get the best fit for your plot and will differ depending if the orientation of the colorbar is in vertical position or horizontal.
For browser compatibility you can use this code. This method returns browser name and version :
private string GetBrowserNameWithVersion
{
var userAgent = Request.UserAgent;
var browserWithVersion = "";
if (userAgent.IndexOf("Edge") > -1)
{
//Edge
browserWithVersion = "Edge Browser Version : " + userAgent.Split(new string[] { "Edge/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Chrome") > -1)
{
//Chrome
browserWithVersion = "Chrome Browser Version : " + userAgent.Split(new string[] { "Chrome/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Safari") > -1)
{
//Safari
browserWithVersion = "Safari Browser Version : " + userAgent.Split(new string[] { "Safari/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Firefox") > -1)
{
//Firefox
browserWithVersion = "Firefox Browser Version : " + userAgent.Split(new string[] { "Firefox/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("rv") > -1)
{
//IE11
browserWithVersion = "Internet Explorer Browser Version : " + userAgent.Split(new string[] { "rv:" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("MSIE") > -1)
{
//IE6-10
browserWithVersion = "Internet Explorer Browser Version : " + userAgent.Split(new string[] { "MSIE" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Other") > -1)
{
//Other
browserWithVersion = "Other Browser Version : " + userAgent.Split(new string[] { "Other" }, StringSplitOptions.None)[1].Split('.')[0];
}
return browserWithVersion;
}
Local variables don't have a default value.
They have to be definitely assigned before you use them. It reduces the chance of using a variable you think you've given a sensible value to, when actually it's got some default value.
If you're putting a <meta> tag in your css files, you're doing something wrong. The <meta> tag belongs in your html files, and tells the browser how the html is encoded, it doesn't say anything about the css, which is a separate file. You could conceivably have completely different encodings for your html and css, although I can't imagine this would be a good idea.
A null pointer exception is an indicator that you are using an object without initializing it.
For example, below is a student class which will use it in our code.
public class Student {
private int id;
public int getId() {
return this.id;
}
public setId(int newId) {
this.id = newId;
}
}
The below code gives you a null pointer exception.
public class School {
Student student;
public School() {
try {
student.getId();
}
catch(Exception e) {
System.out.println("Null pointer exception");
}
}
}
Because you are using student
, but you forgot to initialize it like in the
correct code shown below:
public class School {
Student student;
public School() {
try {
student = new Student();
student.setId(12);
student.getId();
}
catch(Exception e) {
System.out.println("Null pointer exception");
}
}
}
I'm not familiar with either of these books, but the second is closer to current reality. The first may be discussing a specific processor.
Processors have been made with quite a variety of word sizes, not always a multiple of 8.
The 8086 and 8087 processors used 16 bit words, and it's likely this is the machine the first author was writing about.
More recent processors commonly use 32 or 64 bit words.
In the 50's and 60's there were machines with words sizes that seem quite strange to us now, such as 4, 9 and 36. Since about the 70's word size has commonly been a power of 2 and a multiple of 8.
It's been a moment that this question is asked, but this doesn't mean that we can't share other answers in 2020. Here is an awesome plugin with jquery:jQuery Lazy
The basic usage of Lazy:
HTML
<!-- load background images of other element types -->
<div class="lazy" data-src="path/to/image.jpg"></div>
enter code here
JS
$('.lazy').Lazy({
// your configuration goes here
scrollDirection: 'vertical',
effect: 'fadeIn',
visibleOnly: true,
onError: function(element) {
console.log('error loading ' + element.data('src'));
}
});
and your background images are lazy loading. That's all!
To see real examples and more details check this link lazy-doc.
use this style
@"server=.\sqlexpress;"
Maybe more simple;
var top = window.pageYOffset || document.documentElement.scrollTop,
left = window.pageXOffset || document.documentElement.scrollLeft;
Credits: so.dom.js#L492
Use a JSON parser, like JSON.NET
string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();
var seconds = new Date().getTime() / 1000;
....will give you the seconds since midnight, 1 Jan 1970
Often you need to put more into the manifest than what you get with the -e
switch, and in that case, the syntax is:
jar -cvfm myJar.jar myManifest.txt myApp.class
Which reads: "create verbose jarFilename manifestFilename", followed by the files you want to include.
Note that the name of the manifest file you supply can be anything, as jar
will automatically rename it and put it into the right place within the jar file.
Problem is that check weather you have closed all the streams or not if opened close the streams and delete,rename..etc the file this is worked for me
I agree with all the above unless:
sys.argv[1]
was something like Chicken\d{2}-\d{2}An\s*important\s*anchor
sys.argv[1] = "Chicken\d{2}-\d{2}An\s*important\s*anchor"
you would not want to use re.escape
, because in that case you would like it to behave like a regex
TEXTO = sys.argv[1]
if re.search(r"\b(?<=\w)" + TEXTO + "\b(?!\w)", subject, re.IGNORECASE):
# Successful match
else:
# Match attempt failed
Snapshot simply means depending on your configuration Maven will check latest changes on a special dependency. Snapshot is unstable because it is under development but if on a special project needs to has a latest changes you must configure your dependency version to snapshot version. This scenario occurs in big organizations with multiple products that these products related to each other very closely.
To be more precise the shebang #!
, when it is the first two bytes of an executable (x
mode) file, is interpreted by the execve(2) system call (which execute programs). But POSIX specification for execve
don't mention the shebang.
It must be followed by a file path of an interpreter executable (which BTW could even be relative, but most often is absolute).
A nice trick (or perhaps not so nice one) to find an interpreter (e.g. python
) in the user's $PATH
is to use the env
program (always at /usr/bin/env
on all Linux) like e.g.
#!/usr/bin/env python
Any ELF executable can be an interpreter. You could even use #!/bin/cat
or #!/bin/true
if you wanted to! (but that would be often useless)
On Kotlin you can set width and height of any view directly using their virtual properties:
someView.layoutParams.width = 100
someView.layoutParams.height = 200
As the other answers state, Angular doesn't provide this functionality. jQuery does however, and if you have loaded jQuery as well as Angular, you can use
jQuery.each ( array, function ( index, value) {
if(condition) return false; // this will cause a break in the iteration
})
Try executing 'mysql' or 'mysql -- version' without quotes on terminal. it will prompt version otherwise Command Not Found
The /configuration/config.ini
file should contain org.eclipse.core.runtime@start
in the commaseparated osgi.bundles
property. Here is the default osgi.bundles
property, maybe it was (accidently) changed during some upgrade:
osgi.bundles=org.eclipse.equinox.common@2:start,org.eclipse.update.configurator@3:start,org.eclipse.core.runtime@start
You can if necessary override it by setting it as VM argument in /eclipse.ini
:
-Dosgi.bundles=org.eclipse.equinox.common@2:start,org.eclipse.update.configurator@3:start,org.eclipse.core.runtime@start
You can use Reference Assistant extension from the Visual Studio extension gallery.
Used and works for Visual Studio 2010.
To simply subtract one day from todays date:
Select DATEADD(day,-1,GETDATE())
(original post used -7 and was incorrect)
I had to insert date at the beginning of the lines of a log file and it's done like below:
DATE=$(date +"%Y-%m-%d")
awk '{ print "'"$DATE"'", $0; }' /path_to_log_file/log_file.log
It can be redirect to another file to save
function add(){
var first=parseFloat($("#first").val());
var second=parseFloat($("#second").val());
$("#result").val(+(first+second).toFixed(2));
}
I recommend using the os module to avoid trouble in cross-platform. (windows,linux,mac)
Cause if the directory doesn't exists, it will return an exception.
import os
filepath = os.path.join('c:/your/full/path', 'filename')
if not os.path.exists('c:/your/full/path'):
os.makedirs('c:/your/full/path')
f = open(filepath, "a")
If this will be a function for a system or something, you can improve it by adding try/except for error control.
jQlite (angular's "jQuery" port) doesn't support lookup by classes.
One solution would be to include jQuery in your app.
Another is using QuerySelector
or QuerySelectorAll
:
link: function(scope, element, attrs) {
console.log(element[0].querySelector('.list-scrollable'))
}
We use the first item in the element
array, which is the HTML element. element.eq(0)
would yield the same.
In a Python 2 program that I used for many years there was this line:
ocd[i].namn=unicode(a[:b], 'utf-8')
This did not work in Python 3.
However, the program turned out to work with:
ocd[i].namn=a[:b]
I don't remember why I put unicode there in the first place, but I think it was because the name can contains Swedish letters åäöÅÄÖ. But even they work without "unicode".
Use the following code it worked for me:
# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]
# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()
while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.
=COUNTIF() Is the function you are looking for
In a column adjacent to Worksheet1 column A:
=countif(worksheet2!B:B,worksheet1!A3)
This will search worksheet 2 ALL of column B for whatever you have in cell A3
See the MS Office reference for =COUNTIF(range,criteria) here!
I know that there have already been some good answers, but I came across this question with a Google Search and I wish someone would have pointed out this online checking tool...
http://www.tormus.com/tools/div_checker
You just throw in a URL and it will show you the entire map of the page. Very useful for a quick debug like I needed.
if your SQL query is like this
SELECT col-1, col-2 FROM tableName WHERE col-1=apple,col-2=mango
GROUPBY col-3 HAVING Count(col-4) > 5 ORDERBY col-2 DESC LIMIT 15;
Then for query() method, we can do as:-
String table = "tableName";
String[] columns = {"col-1", "col-2"};
String selection = "col-1 =? AND col-2=?";
String[] selectionArgs = {"apple","mango"};
String groupBy =col-3;
String having =" COUNT(col-4) > 5";
String orderBy = "col-2 DESC";
String limit = "15";
query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.
Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.
You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.
The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.
You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.
Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.
But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).
You should provide @2x images for the Retina Macbook Pro and future Retina Macs.
I used this library here: https://github.com/pleerock/class-transformer
<script lang="ts">
import { plainToClass } from 'class-transformer';
</script>
Implementation:
private async getClassTypeValue() {
const value = await plainToClass(ProductNewsItem, JSON.parse(response.data));
}
Sometimes you will have to parse the JSON values for plainToClass to understand that it is a JSON formatted data
In this case a relatively simple GROUP BY
can work, but in general, when there are additional columns where you can't order by but you want them from the particular row which they are associated with, you can either join back to the detail using all the parts of the key or use OVER()
:
Runnable example (Wofkflow20 error in original data corrected)
;WITH partitioned AS (
SELECT company
,workflow
,date
,other_columns
,ROW_NUMBER() OVER(PARTITION BY company, workflow
ORDER BY date) AS seq
FROM workflowTable
)
SELECT *
FROM partitioned WHERE seq = 1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#top, #bottom {
height: 100px;
width: 100%;
position: relative;
}
#container {
overflow: hidden;
position: relative;
width: 100%;
}
#container .left {
height: 550px;
width: 55%;
position: relative;
float: left;
background-color: #3399FF;
}
#container .right {
height: 100%;
position: absolute;
right: 0;
left: 55%;
bottom: 0px;
top: 0px;
background-color: #3366CC;
}
</style>
</head>
<body>
<div id="top"></div>
<div id="container">
<div class="left"></div>
<div class="right"></div>
</div>
<div id="bottom"></div>
</body>
</html>
nvarchar with preprocessing to standardize them as much as possible. You'll probably want to extract extensions and store them in another field.
This is what I'm teaching my students tomorrow. After years of looking at this stuff... ie all of the documentation above http://www.cpearson.com/excel/errorhandling.htm comes to mind as an excellent one...
I hope this summarizes it for others. There is an Err
object and an active (or inactive) ErrorHandler
. Both need to be handled and reset for new errors.
Paste this into a workbook and step through it with F8.
Sub ErrorHandlingDemonstration()
On Error GoTo ErrorHandler
'this will error
Debug.Print (1 / 0)
'this will also error
dummy = Application.WorksheetFunction.VLookup("not gonna find me", Range("A1:B2"), 2, True)
'silly error
Dummy2 = "string" * 50
Exit Sub
zeroDivisionErrorBlock:
maybeWe = "did some cleanup on variables that shouldnt have been divided!"
' moves the code execution to the line AFTER the one that errored
Resume Next
vlookupFailedErrorBlock:
maybeThisTime = "we made sure the value we were looking for was in the range!"
' moves the code execution to the line AFTER the one that errored
Resume Next
catchAllUnhandledErrors:
MsgBox(thisErrorsDescription)
Exit Sub
ErrorHandler:
thisErrorsNumberBeforeReset = Err.Number
thisErrorsDescription = Err.Description
'this will reset the error object and error handling
On Error GoTo 0
'this will tell vba where to go for new errors, ie the new ErrorHandler that was previous just reset!
On Error GoTo ErrorHandler
' 11 is the err.number for division by 0
If thisErrorsNumberBeforeReset = 11 Then
GoTo zeroDivisionErrorBlock
' 1004 is the err.number for vlookup failing
ElseIf thisErrorsNumberBeforeReset = 1004 Then
GoTo vlookupFailedErrorBlock
Else
GoTo catchAllUnhandledErrors
End If
End Sub
To add to the accepted answer iptables
solution, I had to run two more commands on the host to open it to the outside world.
HOST> iptables -t nat -A DOCKER -p tcp --dport 443 -j DNAT --to-destination 172.17.0.2:443
HOST> iptables -t nat -A POSTROUTING -j MASQUERADE -p tcp --source 172.17.0.2 --destination 172.17.0.2 --dport https
HOST> iptables -A DOCKER -j ACCEPT -p tcp --destination 172.17.0.2 --dport https
Note: I was opening port https (443), my docker internal IP was 172.17.0.2
Note 2: These rules and temporrary and will only last until the container is restarted
Don't about the code but you can figure it out like this way :
Go into the 'window' tab then preferences->java->Installed JREs. You can add your own JRE(1.7 or 1.5 etc) also.
For changing the compliance level window->preferences->java->compiler. C Change the compliance level.
give width as 0dp to make sure its size is exactly as per its weight this will make sure that even if content of child views get bigger, they'll still be limited to exactly half(according to is weight)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="click me"
android:layout_weight="0.5"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Hello World"
android:layout_weight="0.5"/>
</LinearLayout>
Press Ctrl+C
When you start the server it mentions this in the startup text.
this is how:
/**
* Get a web file (HTML, XHTML, XML, image, etc.) from a URL. Return an
* array containing the HTTP server response header fields and content.
*/
function get_web_page( $url )
{
$user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';
$options = array(
CURLOPT_CUSTOMREQUEST =>"GET", //set request type post or get
CURLOPT_POST =>false, //set to GET
CURLOPT_USERAGENT => $user_agent, //set user agent
CURLOPT_COOKIEFILE =>"cookie.txt", //set cookie file
CURLOPT_COOKIEJAR =>"cookie.txt", //set cookie jar
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
Example
//Read a web page and check for errors:
$result = get_web_page( $url );
if ( $result['errno'] != 0 )
... error: bad url, timeout, redirect loop ...
if ( $result['http_code'] != 200 )
... error: no page, no permissions, no service ...
$page = $result['content'];
You shouldn't use the third one because its wrong. "String" takes 7 bytes, not 5.
The first one is a pointer (can be reassigned to a different address), the other two are declared as arrays, and cannot be reassigned to different memory locations (but their content may change, use const
to avoid that).
Here is the code:-
telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
deviceId = telephonyManager.getDeviceId();
Log.d(TAG, "getDeviceId() " + deviceId);
phoneType = telephonyManager.getPhoneType();
Log.d(TAG, "getPhoneType () " + phoneType);
Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".
If you're only interested in seeing the currently deleted files, you can use this:
git ls-files --deleted
if you then want to remove them (in case you deleted them not using "git rm") pipe that result to xargs git rm
git ls-files --deleted | xargs git rm
Press Shift + 4 ("$") on the first line, then Shift + j ("J").
And if you want help, go into vi, and then press F1.
You should consult the documentation of whatever library is throwing the exception, to see how to get an error message out of its exceptions.
Alternatively, a good way to debug this kind of thing is to say:
except Exception, e:
print dir(e)
to see what properties e
has - you'll probably find it has a message
property or similar.
Exact way I fixed this based on feedback above since I couldn't get it to work at first:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/list"
>
</ListView>
MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addPreferencesFromResource(R.xml.preferences);
preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:key="upgradecategory"
android:title="Upgrade" >
<Preference
android:key="download"
android:title="Get OnCall Pager Pro"
android:summary="Touch to download the Pro Version!" />
</PreferenceCategory>
</PreferenceScreen>
The acepted Answer is very detailed and correct in most of the cases.
I just want to add that i was getting an error while attempting to load a JSON text file encoded with UTF8, i had a well formatted JSON but the 'json_decode' always returned me with NULL, it was due the BOM mark.
To solve it, i made this PHP function:
function load_utf8_file($filePath)
{
$response = null;
try
{
if (file_exists($filePath)) {
$text = file_get_contents($filePath);
$response = preg_replace("/^\xEF\xBB\xBF/", '', $text);
}
} catch (Exception $e) {
echo 'ERROR: ', $e->getMessage(), "\n";
}
finally{ }
return $response;
}
Then i use it like this to load a JSON file and get a value from it:
$str = load_utf8_file('appconfig.json');
$json = json_decode($str, true);
//print_r($json);
echo $json['prod']['deploy']['hostname'];
Before User Shift + = or Shift - , you have to first set the key map as mentioned below
I worked on this same issue and I am sure I have found out the exact reason for it.
Neither BindingResult nor plain target object for bean name 'command' available as request attribute
If your successView property value (name of jsp page) is the same as your input page name, then second value of ModelAndView constructor must be match with the commandName of the input page.
E.g.
index.jsp
<html>
<body>
<table>
<tr><td><a href="Login.html">Login</a></td></tr>
</table>
</body>
</html>
dispatcher-servlet.xml
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/Login.html">
<ref bean="userController"/>
</entry>
</map>
</property>
</bean>
<bean id="userController" class="controller.AddCountryFormController">
<property name="commandName"><value>country</value></property>
<property name="commandClass"><value>controller.Country</value></property>
<property name="formView"><value>countryForm</value></property>
<property name="successView"><value>countryForm</value></property>
</bean>
AddCountryFormController.java
package controller;
import javax.servlet.http.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class AddCountryFormController extends SimpleFormController
{
public AddCountryFormController(){
setCommandName("Country.class");
}
protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command,BindException errors){
Country country=(Country)command;
System.out.println("calling onsubmit method !!!!!");
return new ModelAndView(getSuccessView(),"country",country);
}
}
Country.java
package controller;
public class Country
{
private String countryName;
public void setCountryName(String value){
countryName=value;
}
public String getCountryName(){
return countryName;
}
}
countryForm.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
<form:form commandName="country" method="POST" >
<table>
<tr><td><form:input path="countryName"/></td></tr>
<tr><td><input type="submit" value="Save"/></td></tr>
</table>
</form:form>
</body>
<html>
Input page commandName="country"
ModelAndView Constructor as return new ModelAndView(getSuccessView(),"country",country);
Means inputpage commandName==ModeAndView(,"commandName",)
You will get all the class in below array
event.target.classList
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
Either move the xyz.h file somewhere else so the preprocessor can find it, or else change the #include
statement so the preprocessor finds it where it already is.
Where the preprocessor looks for included files is described here. One solution is to put the xyz.h file in a folder where the preprocessor is going to find it while following that search pattern.
Alternatively you can change the #include statement so that the preprocessor can find it. You tell us the xyz.cxx file is is in the 'code' folder but you don't tell us where you've put the xyz.h file. Let's say your file structure looks like this...
<some folder>\xyz.h
<some folder>\code\xyz.cxx
In that case the #include statement in xyz.cxx should look something like this..
#include "..\xyz.h"
On the other hand let's say your file structure looks like this...
<some folder>\include\xyz.h
<some folder>\code\xyz.cxx
In that case the #include statement in xyz.cxx should look something like this..
#include "..\include\xyz.h"
Update: On the other other hand as @In silico points out in the comments, if you are using #include <xyz.h>
you should probably change it to #include "xyz.h"
The best solution I've been able to find consists of these steps:
mvn-repo
to host your maven artifacts.mvn-repo
as a maven repository.There are several benefits to using this approach:
mvn-repo
, much like github pages are kept in a separate branch called gh-pages
(if you use github pages)gh-pages
if you're using them.mvn deploy
as you normally wouldThe typical way you deploy artifacts to a remote maven repo is to use mvn deploy
, so let's patch into that mechanism for this solution.
First, tell maven to deploy artifacts to a temporary staging location inside your target directory. Add this to your pom.xml
:
<distributionManagement>
<repository>
<id>internal.repo</id>
<name>Temporary Staging Repository</name>
<url>file://${project.build.directory}/mvn-repo</url>
</repository>
</distributionManagement>
<plugins>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.1</version>
<configuration>
<altDeploymentRepository>internal.repo::default::file://${project.build.directory}/mvn-repo</altDeploymentRepository>
</configuration>
</plugin>
</plugins>
Now try running mvn clean deploy
. You'll see that it deployed your maven repository to target/mvn-repo
. The next step is to get it to upload that directory to GitHub.
Add your authentication information to ~/.m2/settings.xml
so that the github site-maven-plugin
can push to GitHub:
<!-- NOTE: MAKE SURE THAT settings.xml IS NOT WORLD READABLE! -->
<settings>
<servers>
<server>
<id>github</id>
<username>YOUR-USERNAME</username>
<password>YOUR-PASSWORD</password>
</server>
</servers>
</settings>
(As noted, please make sure to chmod 700 settings.xml
to ensure no one can read your password in the file. If someone knows how to make site-maven-plugin prompt for a password instead of requiring it in a config file, let me know.)
Then tell the GitHub site-maven-plugin
about the new server you just configured by adding the following to your pom:
<properties>
<!-- github server corresponds to entry in ~/.m2/settings.xml -->
<github.global.server>github</github.global.server>
</properties>
Finally, configure the site-maven-plugin
to upload from your temporary staging repo to your mvn-repo
branch on Github:
<build>
<plugins>
<plugin>
<groupId>com.github.github</groupId>
<artifactId>site-maven-plugin</artifactId>
<version>0.11</version>
<configuration>
<message>Maven artifacts for ${project.version}</message> <!-- git commit message -->
<noJekyll>true</noJekyll> <!-- disable webpage processing -->
<outputDirectory>${project.build.directory}/mvn-repo</outputDirectory> <!-- matches distribution management repository url above -->
<branch>refs/heads/mvn-repo</branch> <!-- remote branch name -->
<includes><include>**/*</include></includes>
<repositoryName>YOUR-REPOSITORY-NAME</repositoryName> <!-- github repo name -->
<repositoryOwner>YOUR-GITHUB-USERNAME</repositoryOwner> <!-- github username -->
</configuration>
<executions>
<!-- run site-maven-plugin's 'site' target as part of the build's normal 'deploy' phase -->
<execution>
<goals>
<goal>site</goal>
</goals>
<phase>deploy</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
The mvn-repo
branch does not need to exist, it will be created for you.
Now run mvn clean deploy
again. You should see maven-deploy-plugin "upload" the files to your local staging repository in the target directory, then site-maven-plugin committing those files and pushing them to the server.
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building DaoCore 1.3-SNAPSHOT
[INFO] ------------------------------------------------------------------------
...
[INFO] --- maven-deploy-plugin:2.5:deploy (default-deploy) @ greendao ---
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.jar (77 KB at 2936.9 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.pom (3 KB at 1402.3 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/maven-metadata.xml (768 B at 150.0 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/maven-metadata.xml (282 B at 91.8 KB/sec)
[INFO]
[INFO] --- site-maven-plugin:0.7:site (default) @ greendao ---
[INFO] Creating 24 blobs
[INFO] Creating tree with 25 blob entries
[INFO] Creating commit with SHA-1: 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] Updating reference refs/heads/mvn-repo from ab7afb9a228bf33d9e04db39d178f96a7a225593 to 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.595s
[INFO] Finished at: Sun Dec 23 11:23:03 MST 2012
[INFO] Final Memory: 9M/81M
[INFO] ------------------------------------------------------------------------
Visit github.com in your browser, select the mvn-repo
branch, and verify that all your binaries are now there.
Congratulations!
You can now deploy your maven artifacts to a poor man's public repo simply by running mvn clean deploy
.
There's one more step you'll want to take, which is to configure any poms that depend on your pom to know where your repository is. Add the following snippet to any project's pom that depends on your project:
<repositories>
<repository>
<id>YOUR-PROJECT-NAME-mvn-repo</id>
<url>https://github.com/YOUR-USERNAME/YOUR-PROJECT-NAME/raw/mvn-repo/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
</repositories>
Now any project that requires your jar files will automatically download them from your github maven repository.
Edit: to avoid the problem mentioned in the comments ('Error creating commit: Invalid request. For 'properties/name', nil is not a string.'), make sure you state a name in your profile on github.
This tool saved me a lot, since I have no Admin permission on my machine and already had nodejs installed. For some reason the configuration on my network does not give me access to other machines just pointing the IP on the browser.
# Using a local.dev vhost
$ browser-sync start --proxy
# Using a local.dev vhost with PORT
$ browser-sync start --proxy local.dev:8001
# Using a localhost address
$ browser-sync start --proxy localhost:8001
# Using a localhost address in a sub-dir
$ browser-sync start --proxy localhost:8080/site1
As the table owner you need to grant SELECT access on the underlying tables to the user you are running the SELECT statement as.
grant SELECT on TABLE_NAME to READ_USERNAME;
I found a short comparison from MSDN
The .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:
System.Timers.Timer
, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
System.Threading.Timer
, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
System.Windows.Forms.Timer
, a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment.
System.Web.UI.Timer
, an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
$()
means: "first evaluate this, and then evaluate the rest of the line".
Ex :
echo $(pwd)/myFile.txt
will be interpreted as
echo /my/path/myFile.txt
On the other hand ${}
expands a variable.
Ex:
MY_VAR=toto
echo ${MY_VAR}/myFile.txt
will be interpreted as
echo toto/myFile.txt
Why can't I use it as
bash$ while ((i=0;i<10;i++)); do echo $i; done
I'm afraid the answer is just that the bash syntax for while
just isn't the same as the syntax for for
.
In November 2019, I am seeking a way to create a (hypothetical) onparse
EventListener
for <elements>
which don't take onload
.
The (hypothetical) onparse
EventListener
must be able to listen for when an element is parsed.
I was pretty happy with the Second Attempt below, but it just struck me that I can make the code shorter and simpler, by creating a tailor-made event:
let parseEvent = new Event('parse');
This is the best solution yet.
The example below:
parse
Event
window.onload
or any time) which:
data-onparse
parse
EventListener
to each of those elementsparse
Event
to each of those elements to execute the Callback
Working Example:
// Create (homemade) parse event_x000D_
let parseEvent = new Event('parse');_x000D_
_x000D_
// Create Initialising Function which can be run at any time_x000D_
const initialiseParseableElements = () => {_x000D_
_x000D_
// Get all the elements which need to respond to an onparse event_x000D_
let elementsWithParseEventListener = document.querySelectorAll('[data-onparse]');_x000D_
_x000D_
// Attach Event Listeners and Dispatch Events_x000D_
elementsWithParseEventListener.forEach((elementWithParseEventListener) => {_x000D_
_x000D_
elementWithParseEventListener.addEventListener('parse', updateParseEventTarget, false);_x000D_
elementWithParseEventListener.dataset.onparsed = elementWithParseEventListener.dataset.onparse;_x000D_
elementWithParseEventListener.removeAttribute('data-onparse');_x000D_
elementWithParseEventListener.dispatchEvent(parseEvent);_x000D_
});_x000D_
}_x000D_
_x000D_
// Callback function for the Parse Event Listener_x000D_
const updateParseEventTarget = (e) => {_x000D_
_x000D_
switch (e.target.dataset.onparsed) {_x000D_
_x000D_
case ('update-1') : e.target.textContent = 'My First Updated Heading'; break;_x000D_
case ('update-2') : e.target.textContent = 'My Second Updated Heading'; break;_x000D_
case ('update-3') : e.target.textContent = 'My Third Updated Heading'; break;_x000D_
case ('run-oQuickReply.swap()') : e.target.innerHTML = 'This <code><div></code> is now loaded and the function <code>oQuickReply.swap()</code> will run...'; break;_x000D_
}_x000D_
}_x000D_
_x000D_
// Run Initialising Function_x000D_
initialiseParseableElements();_x000D_
_x000D_
let dynamicHeading = document.createElement('h3');_x000D_
dynamicHeading.textContent = 'Heading Text';_x000D_
dynamicHeading.dataset.onparse = 'update-3';_x000D_
_x000D_
setTimeout(() => {_x000D_
_x000D_
// Add new element to page after time delay_x000D_
document.body.appendChild(dynamicHeading);_x000D_
_x000D_
// Re-run Initialising Function_x000D_
initialiseParseableElements();_x000D_
_x000D_
}, 3000);
_x000D_
div {_x000D_
width: 300px;_x000D_
height: 40px;_x000D_
padding: 12px;_x000D_
border: 1px solid rgb(191, 191, 191);_x000D_
}_x000D_
_x000D_
h3 {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
}
_x000D_
<h2 data-onparse="update-1">My Heading</h2>_x000D_
<h2 data-onparse="update-2">My Heading</h2>_x000D_
<div data-onparse="run-oQuickReply.swap()">_x000D_
This div hasn't yet loaded and nothing will happen._x000D_
</div>
_x000D_
The First Attempt below (based on @JohnWilliams
' brilliant Empty Image Hack) used a hardcoded <img />
and worked.
I thought it ought to be possible to remove the hardcoded <img />
entirely and only dynamically insert it after detecting, in an element which needed to fire an onparse
event, an attribute like:
data-onparse="run-oQuickReply.swap()"
It turns out, this works very well indeed.
The example below:
data-onparse
<img src />
and appends it to the document, immediately after each of those elementsonerror
EventListener
when the rendering engine parses each <img src />
Callback
and removes that dynamically generated <img src />
from the documentWorking Example:
// Get all the elements which need to respond to an onparse event_x000D_
let elementsWithParseEventListener = document.querySelectorAll('[data-onparse]');_x000D_
_x000D_
// Dynamically create and position an empty <img> after each of those elements _x000D_
elementsWithParseEventListener.forEach((elementWithParseEventListener) => {_x000D_
_x000D_
let emptyImage = document.createElement('img');_x000D_
emptyImage.src = '';_x000D_
elementWithParseEventListener.parentNode.insertBefore(emptyImage, elementWithParseEventListener.nextElementSibling);_x000D_
});_x000D_
_x000D_
// Get all the empty images_x000D_
let parseEventTriggers = document.querySelectorAll('img[src=""]');_x000D_
_x000D_
// Callback function for the EventListener below_x000D_
const updateParseEventTarget = (e) => {_x000D_
_x000D_
let parseEventTarget = e.target.previousElementSibling;_x000D_
_x000D_
switch (parseEventTarget.dataset.onparse) {_x000D_
_x000D_
case ('update-1') : parseEventTarget.textContent = 'My First Updated Heading'; break;_x000D_
case ('update-2') : parseEventTarget.textContent = 'My Second Updated Heading'; break;_x000D_
case ('run-oQuickReply.swap()') : parseEventTarget.innerHTML = 'This <code><div></code> is now loaded and the function <code>oQuickReply.swap()</code> will run...'; break;_x000D_
}_x000D_
_x000D_
// Remove empty image_x000D_
e.target.remove();_x000D_
}_x000D_
_x000D_
// Add onerror EventListener to all the empty images_x000D_
parseEventTriggers.forEach((parseEventTrigger) => {_x000D_
_x000D_
parseEventTrigger.addEventListener('error', updateParseEventTarget, false);_x000D_
_x000D_
});
_x000D_
div {_x000D_
width: 300px;_x000D_
height: 40px;_x000D_
padding: 12px;_x000D_
border: 1px solid rgb(191, 191, 191);_x000D_
}
_x000D_
<h2 data-onparse="update-1">My Heading</h2>_x000D_
<h2 data-onparse="update-2">My Heading</h2>_x000D_
<div data-onparse="run-oQuickReply.swap()">_x000D_
This div hasn't yet loaded and nothing will happen._x000D_
</div>
_x000D_
I can build on @JohnWilliams
' <img src>
hack (on this page, from 2017) - which is, so far, the best approach I have come across.
The example below:
onerror
EventListener
when the rendering engine parses <img src />
Callback
and removes the <img src />
from the documentWorking Example:
let myHeadingLoadEventTrigger = document.getElementById('my-heading-load-event-trigger');_x000D_
_x000D_
const updateHeading = (e) => {_x000D_
_x000D_
let myHeading = e.target.previousElementSibling;_x000D_
_x000D_
if (true) { // <= CONDITION HERE_x000D_
_x000D_
myHeading.textContent = 'My Updated Heading';_x000D_
}_x000D_
_x000D_
// Modern alternative to document.body.removeChild(e.target);_x000D_
e.target.remove();_x000D_
}_x000D_
_x000D_
myHeadingLoadEventTrigger.addEventListener('error', updateHeading, false);
_x000D_
<h2>My Heading</h2>_x000D_
<img id="my-heading-load-event-trigger" src />
_x000D_
I use this and it works fine
#/bin/bash
/usr/bin/python python python_script.py
Use p{width}
column specifier: e.g. \begin{tabular}{ l p{10cm} }
will put column's content into 10cm-wide parbox, and the text will be properly broken to several lines, like in normal paragraph.
You can also use tabular*
environment to specify width for the entire table.
I would suggest to end java.exe
or javaw.exe
process from task manager and try again. This will not end the entire eclipse application but will free the port.
This is a bit late but I know it will help someone:
If you are using datetimepicker
make sure you include the right CSS and JS files. datetimepicker
uses(Take note of their names);
and
On the above question asked by @mindfreak,The main problem is due to the imported files.
You could achieve this with an extra <span>
:
HTML
<h2><span>Featured products</span></h2>
<h2><span>Here is a very long h2, and as you can see the line get too wide</span></h2>
CSS
h2 {
position: relative;
}
h2 span {
background-color: white;
padding-right: 10px;
}
h2:after {
content:"";
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 0.5em;
border-top: 1px solid black;
z-index: -1;
}
http://jsfiddle.net/myajouri/pkm5r/
Another solution without the extra <span>
but requires an overflow: hidden
on the <h2>
:
h2 {
overflow: hidden;
}
h2:after {
content:"";
display: inline-block;
height: 0.5em;
vertical-align: bottom;
width: 100%;
margin-right: -100%;
margin-left: 10px;
border-top: 1px solid black;
}
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for numbers in lists:
for numbers2 in numbers:
results.append(numbers2)
return results
print flatten(n)
Output: n = [1,2,3,4,5,6,7,8,9]
As per the DOM structure you can use below code:
var x = document.getElementById('mySelect');
var txt = "";
var val = "";
for (var i = 0; i < x.length; i++) {
txt +=x[i].text + ",";
val +=x[i].value + ",";
}
For those who searches for an answer without parsing and loosing milliseconds,
given dt_obj
is a datetime:
python3 only, elegant
int(dt_obj.timestamp() * 1000)
both python2 and python3 compatible:
import time
int(time.mktime(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000)