I had the same issue, and by Running "exec sp_updatestats" the issue solved and works now
Although this is the accepted answer, toto_tico's answer below is better :)
Try making the onclick js use 'return' to ensure the desired return value gets used...
<button type="button" value="click me" onclick="return check_me();" />
Unless you are sorting strings in an accent-free English only, you probably want to use a Collator
. It will correctly sort diacritical marks, can ignore case and other language-specific stuff:
Collections.sort(countries, Collator.getInstance(new Locale(languageCode)));
You can set the collator strength, see the javadoc.
Here is an example for Slovak where Š
should go after S
, but in UTF Š
is somewhere after Z
:
List<String> countries = Arrays.asList("Slovensko", "Švédsko", "Turecko");
Collections.sort(countries);
System.out.println(countries); // outputs [Slovensko, Turecko, Švédsko]
Collections.sort(countries, Collator.getInstance(new Locale("sk")));
System.out.println(countries); // outputs [Slovensko, Švédsko, Turecko]
Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:
sudo apt install vlc ffmpeg
In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.
I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.
You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:
ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'
For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:
ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554
You almost have it, you just left out 0 and forgot the quantifier.
word.matches("^[0-9,;]+$")
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
Factory
and Service
is a just wrapper of a provider
.
Factory
Factory
can return anything which can be a class(constructor function)
, instance of class
, string
, number
or boolean
. If you return a constructor
function, you can instantiate in your controller.
myApp.factory('myFactory', function () {
// any logic here..
// Return any thing. Here it is object
return {
name: 'Joe'
}
}
Service
Service does not need to return anything. But you have to assign everything in this
variable. Because service will create instance by default and use that as a base object.
myApp.service('myService', function () {
// any logic here..
this.name = 'Joe';
}
Actual angularjs code behind the service
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
It just a wrapper around the factory
. If you return something from service
, then it will behave like Factory
.
IMPORTANT
: The return result from Factory and Service will be cache and same will be returned for all controllers.
When should i use them?
Factory
is mostly preferable in all cases. It can be used when you have constructor
function which needs to be instantiated in different controllers.
Service
is a kind of Singleton
Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application.
Eg: Authenticated user details.
For further understanding, read
http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html
http://viralpatel.net/blogs/angularjs-service-factory-tutorial/
The following snippet might help you:
select SUBSTR(ENDDTTM,1, 9), extract(DAY FROM (ENDDTTM)), ENDDTTM, BEGINDTTM, (ENDDTTM - BEGINDTTM),substr(BEGINDTTM, 1,15), substr((ENDDTTM - BEGINDTTM), 12, 8),
round((substr((ENDDTTM - BEGINDTTM), 12, 2)* 3600 + substr((ENDDTTM - BEGINDTTM), 15, 2)*60 + substr((ENDDTTM - BEGINDTTM), 18, 2)),2) as seconds,
round((substr((ENDDTTM - BEGINDTTM), 12, 2)* 60 + substr((ENDDTTM - BEGINDTTM), 15, 2) + substr((ENDDTTM - BEGINDTTM), 18, 2)/60 ), 2)as minutes,
round((substr((ENDDTTM - BEGINDTTM), 12, 2) + substr((ENDDTTM - BEGINDTTM), 15, 2)/60 + substr((ENDDTTM - BEGINDTTM), 18, 2)/3600 ),2) as hours
The directory or a file in it is locked and cannot be deleted. Find the culprit who locks it and see if you can eliminate it.
from datetime import datetime, timedelta
from dateutil import parser
def getDateRange(begin, end):
""" """
beginDate = parser.parse(begin)
endDate = parser.parse(end)
delta = endDate-beginDate
numdays = delta.days + 1
dayList = [datetime.strftime(beginDate + timedelta(days=x), '%Y%m%d') for x in range(0, numdays)]
return dayList
its too simple, you can just type "cache:" before the URL of the page. for example
if you want to check the last webcache of this page simply type on URL bar cache:http://stackoverflow.com/questions/4560400/how-can-i-get-the-google-cache-age-of-any-url-or-web-page
this will show you the last webcache of the page.see here:
But remember, the caching of a webpage will only show if the page is already indexed on search engine(Google). for this you need to check the meta robot tag of that page.
No internal means, AFAIK. Use this: memset(c, 0, length);
If you want to ensure that your cleanup process finishes I would add on to Matt J's answer by using a SIG_IGN so that further SIGINT
are ignored which will prevent your cleanup from being interrupted.
import signal
import sys
def signal_handler(signum, frame):
signal.signal(signum, signal.SIG_IGN) # ignore additional signals
cleanup() # give your process a chance to clean up
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler) # register the signal with the signal handler first
do_stuff()
The canonical way to get an interactive shell with docker-compose is to use:
docker-compose run --rm myapp
You can set stdin_open: true, tty: true
, however that won't actually give you a proper shell with up
, because logs are being streamed from all the containers.
You can also use
docker exec -ti <container name> /bin/bash
to get a shell on a running container.
The right approach is to use setImageViewUri()
(slower) or the setImageViewBitmap()
and recreating RemoteView
s every time you update the notification.
you can also try
var query = from p in list
where p.Age > 18
select p;
<div class="bs-example">
<button class="btn btn-success btn-lg" type="button">Active</button>
<button class="btn btn-success disabled" type="button">Disabled</button>
</div>
it is because of using web address, You can not use http to write data. don't use : http:// or https:// in your location for upload files or save data or somting like that. instead of of using $_SERVER["HTTP_REFERER"] use $_SERVER["DOCUMENT_ROOT"]. for example :
wrong :
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["HTTP_REFERER"].'/uploads/images/1.jpg')
correct:
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["DOCUMENT_ROOT"].'/uploads/images/1.jpg')
You can use any of the libraries listed here (like Pyxlreader that is based on JExcelApi, or xlwt), plus COM automation to use Excel itself for the reading of the files, but for that you are introducing Office as a dependency of your software, which might not be always an option.
SVG 1.2 Tiny has viewport-fill I'm not sure how widely implemented this property is though as most browsers are targetting SVG 1.1 at this time. Opera implements it FWIW.
A more cross-browser solution currently would be to stick a <rect>
element with width and height of 100% and fill="red" as the first child of the <svg>
element, for example:
<rect width="100%" height="100%" fill="red"/>
Print simply prints out the structure to your output device (normally the console). Nothing more. To return it from your function, you would do:
def autoparts():
parts_dict = {}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
return parts_dict
Why return? Well if you don't, that dictionary dies (gets garbage collected) and is no longer accessible as soon as this function call ends. If you return the value, you can do other stuff with it. Such as:
my_auto_parts = autoparts()
print(my_auto_parts['engine'])
See what happened? autoparts() was called and it returned the parts_dict and we stored it into the my_auto_parts variable. Now we can use this variable to access the dictionary object and it continues to live even though the function call is over. We then printed out the object in the dictionary with the key 'engine'.
For a good tutorial, check out dive into python. It's free and very easy to follow.
Since I already had migrations folder, I restarted Visual Studio and ran Update-Database -verbose in package manager console. That worked for me
If you're using PHP you can funnel your request to Node scripts via shell_exec, passing arguments to scripts as JSON strings in the command line. Example call:
<?php
shell_exec("node nodeScript.js"); // without arguments
shell_exec("node nodeScript.js '{[your JSON here]}'"); //with arguments
?>
The caveat is you need to be very careful about handling user data when it goes anywhere near a command line. Example nightmare:
<?php
$evilUserData = "'; [malicious commands here];";
shell_exec("node nodeScript.js '{$evilUserData}'");
?>
You could subtract the current time stamp from 12 AM of the same day.
Using current timestamp:
moment().valueOf() - moment().startOf('day').valueOf()
Using arbitrary day:
moment(someDate).valueOf() - moment(someDate).startOf('day').valueOf()
Here's a paper on how these numbers (or similar ones) were derived:
When an <option>
isn't given a value=""
, the text becomes its value
, so you can just use .val()
on the <select>
to set by value, like this:
var text1 = 'Monkey';
$("#mySelect1").val(text1);
var text2 = 'Mushroom pie';
$("#mySelect2").val(text2);
You can test it out here, if the example is not what you're after and they actually have a value, use the <option>
element's .text
property to .filter()
, like this:
var text1 = 'Monkey';
$("#mySelect1 option").filter(function() {
return this.text == text1;
}).attr('selected', true);
var text2 = 'Mushroom pie';
$("#mySelect2 option").filter(function() {
return this.text == text2;
}).attr('selected', true);?
Try this code:
function logErr($data){
$logPath = __DIR__. "/../logs/logs.txt";
$mode = (!file_exists($logPath)) ? 'w':'a';
$logfile = fopen($logPath, $mode);
fwrite($logfile, "\r\n". $data);
fclose($logfile);
}
I always use it like this, and it works...
Another way to remove all transitions is with the unset
keyword:
a.tags {
transition: unset;
}
In the case of transition
, unset
is equivalent to initial
, since transition
is not an inherited property:
a.tags {
transition: initial;
}
A reader who knows about unset
and initial
can tell that these solutions are correct immediately, without having to think about the specific syntax of transition
.
select persons.personsid,name,info.id,address
-> from persons
-> inner join persons on info.infoid = info.info.id;
I know this already has a marked answer, but I feel I have an improvement to it.
The marked answer is a bit misleading. He set a width to the button, which is not necessary, and set widths are not "responsive". To his defense, he mentions in a comment below it, that the width is not necessary and just an example.
One thing not mentioned here, is that the words may break in the middle of a word and look messed up.
My solution, forces the break to happen between words, a nice word wrap.
.btn-responsive {
white-space: normal !important;
word-wrap: break-word;
}
<a href="#" class="btn btn-primary btn-responsive">Click Here</a>
The initial question has been posted quite some time ago and in the meantime Debian has made huge headway in the area of multiarch support.
Multiarch is a great achievement for cross compilation!
In a nutshell the following steps are required to leverage multiarch for Raspbian Jessie cross compilation:
Since this is a lot of work I have automated the above setup. You can read about it here:
This works for me:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title> Fullscreen Div </title>
<style>
.test{
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
z-index: 10;
}
</style>
</head>
<body>
<div class='test'>Some text</div>
</body>
</html>
For this, I use FLAG_ACTIVITY_CLEAR_TOP
flag for starting Intent
(without FLAG_ACTIVITY_NEW_TASK
)
and launchMode = "singleTask"
in manifest for launched activity.
Seems like it works as I need - activity does not restart and all other activities are closed.
A simpler approach relies on redirection from the page LOGIN_REDIRECT_URL. The key thing to realize is that the user information is automatically included in the request.
Suppose:
LOGIN_REDIRECT_URL = '/profiles/home'
and you have configured a urlpattern:
(r'^profiles/home', home),
Then, all you need to write for the view home()
is:
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
@login_required
def home(request):
return HttpResponseRedirect(
reverse(NAME_OF_PROFILE_VIEW,
args=[request.user.username]))
where NAME_OF_PROFILE_VIEW
is the name of the callback that you are using. With django-profiles, NAME_OF_PROFILE_VIEW
can be 'profiles_profile_detail'.
public OnClickListener moreListener = new OnClickListener() {
@Override
public void onClick(View v) {
adapter.add("aaaa")
}
}
For those, who want to use Shell.Application.Namespace.Folder.CopyHere() and want to hide progress bars while copying, or use more options, the documentation is here:
https://docs.microsoft.com/en-us/windows/desktop/shell/folder-copyhere
To use powershell and hide progress bars and disable confirmations you can use code like this:
# We should create folder before using it for shell operations as it is required
New-Item -ItemType directory -Path "C:\destinationDir" -Force
$shell = New-Object -ComObject Shell.Application
$zip = $shell.Namespace("C:\archive.zip")
$items = $zip.items()
$shell.Namespace("C:\destinationDir").CopyHere($items, 1556)
Limitations of use of Shell.Application on windows core versions:
https://docs.microsoft.com/en-us/windows-server/administration/server-core/what-is-server-core
On windows core versions, by default the Microsoft-Windows-Server-Shell-Package is not installed, so shell.applicaton will not work.
note: Extracting archives this way will take a long time and can slow down windows gui
The correct method is #2. You used the section tag to define a section of your document. From the specs http://www.w3.org/TR/html5/sections.html:
The section element is not a generic container element. When an element is needed for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead
Its quite simple but not easy to discover --- Go here to read more. its from the official microsoft website
Step 1 - Click the cell or range of the source sheet (that contains the data you want to link to)
Step 2 Press Ctrl+C, or go to the Home tab, and in the Clipboard group, click Copy Button image .
Step 3
Clipboard group on the Home
tab
Step 4 Press Ctrl+V, or go to the Home tab, in the Clipboard group, click Paste Link Button. By default, the Paste Options Button image button appears when you paste copied data.
Step 5 Click the Paste Options button, and then click Paste Link .
If you are testing for properties that are on the object itself (not a part of its prototype chain) you can use .hasOwnProperty()
:
if (x.hasOwnProperty('y')) {
// ......
}
You can use the in
operator to test for properties that are inherited as well.
if ('y' in x) {
// ......
}
If you are looking for a simple alternative, this can be done using a loop:
for i in $(find -name 'file_*' -follow -type f); do
zcat $i | agrep -dEOE 'grep'
done
or, more general and easy to understand form:
for i in $(YOUR_FIND_COMMAND); do
YOUR_EXEC_COMMAND_AND_PIPES
done
and replace any {} by $i in YOUR_EXEC_COMMAND_AND_PIPES
The LogManager
class determines which log4j config to use in a static block which runs when the class is loaded. There are three options intended for end-users:
log4j.defaultInitOverride
to false, it will not configure log4j at all.Specify the path to the configuration file manually yourself and override the classpath search. You can specify the location of the configuration file directly by using the following argument to java
:
-Dlog4j.configuration=<path to properties file>
in your test runner configuration.
Allow log4j to scan the classpath for a log4j config file during your test. (the default)
See also the online documentation.
This is because you have the following code:
class JSONDeserializer
{
Value JSONDeserializer::ParseValue(TDR type, const json_string& valueString);
};
This is not valid C++ but Visual Studio seems to accept it. You need to change it to the following code to be able to compile it with a standard compliant compiler (gcc is more compliant to the standard on this point).
class JSONDeserializer
{
Value ParseValue(TDR type, const json_string& valueString);
};
The error come from the fact that JSONDeserializer::ParseValue
is a qualified name (a name with a namespace qualification), and such a name is forbidden as a method name in a class.
For swift
var label = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 50))
label.textAlignment = .left
label.text = "This is a Label"
self.view.addSubview(label)
Take the pyc file to a windows machine. Use any Hex editor to open this pyc file. I used freeware 'HexEdit'. Now read hex value of first two bytes. In my case, these were 03 f3.
Open calc and convert its display mode to Programmer (Scientific in XP) to see Hex and Decimal conversion. Select "Hex" from Radio button. Enter values as second byte first and then the first byte i.e f303 Now click on "Dec" (Decimal) radio button. The value displayed is one which is correspond to the magic number aka version of python.
So, considering the table provided in earlier reply
The best way to do it From Android O preview release is this way
1.)Right-click the res folder and go to New > Android resource directory. The New
Resource Directory window appears.
2.)In the Resource type list, select font, and then click OK.
3.)Add your font files in the font folder.The folder structure below generates R.font.dancing_script, R.font.la_la, and R.font.ba_ba.
4.)Double-click a font file to preview the file's fonts in the editor.
Next we must create a font family
1.)Right-click the font folder and go to New > Font resource file. The New Resource File window appears.
2.)Enter the file name, and then click OK. The new font resource XML opens in the editor.
3.)Enclose each font file, style, and weight attribute in the font tag element. The following XML illustrates adding font-related attributes in the font resource XML:
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
android:fontStyle="normal"
android:fontWeight="400"
android:font="@font/hey_regular" />
<font
android:fontStyle="italic"
android:fontWeight="400"
android:font="@font/hey_bababa" />
</font-family>
Adding fonts to a TextView:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
**android:fontFamily="@font/ba_ba"**/>
As from the documentation
all the steps are correct.
I realize this is an old question, but I use a much simpler way. Typically I just grab the list that I need, either by query or copying an existing list or whatever, then remove the duplicates. We will assume for this answer that your list is already in column C, row 4, as per the original question. This method works for whatever size list you have and you can select header yes or no.
Dim rng as range
Range("C4").Select
Set rng = Range(Selection, Selection.End(xlDown))
rng.RemoveDuplicates Columns:=1, Header:=xlYes
I do wonder if perhaps you should iterate over the exploded HTTP_X_FORWARDED_FOR in reverse order, since my experience has been that the user's IP address ends up at the end of the comma-separated list, so starting at the start of the header, you're more likely to get the ip address of one of the proxies returned, which could potentially still allow session hijacking as many users may come through that proxy.
You can do this. Adapt it to your situation:
for l in Nlist:
for item in l:
print item
In this case, it doesn't matter as there is no content between the two div
s.
Either one will get the browser to scroll down to it.
The a
element will look like:
<a href="mypageName.html#buttonOne">buttonOne</a>
Or:
<a href="mypageName.html#linkedinB">linkedinB</a>
I came here and followed above answer. But mismatch in the Order of data type caused an error. The below description from another answer will come handy.
Are the results above the same as the sequence of columns in your table? because oracle is strict in column orders. this example below produces an error:
create table test1_1790 (
col_a varchar2(30),
col_b number,
col_c date);
create table test2_1790 (
col_a varchar2(30),
col_c date,
col_b number);
select * from test1_1790
union all
select * from test2_1790;
ORA-01790: expression must have same datatype as corresponding expression
As you see the root cause of the error is in the mismatching column ordering that is implied by the use of * as column list specifier. This type of errors can be easily avoided by entering the column list explicitly:
select col_a, col_b, col_c from test1_1790 union all select col_a, col_b, col_c from test2_1790; A more frequent scenario for this error is when you inadvertently swap (or shift) two or more columns in the SELECT list:
select col_a, col_b, col_c from test1_1790
union all
select col_a, col_c, col_b from test2_1790;
OR if the above does not solve your problem, how about creating an ALIAS in the columns like this: (the query is not the same as yours but the point here is how to add alias in the column.)
SELECT id_table_a,
desc_table_a,
table_b.id_user as iUserID,
table_c.field as iField
UNION
SELECT id_table_a,
desc_table_a,
table_c.id_user as iUserID,
table_c.field as iField
As a general rule, always use the more readable code and only refactor if performance is an issue. In this specific case, most recent JDK's will actually optimize the code into the StringBuilder version in any case.
You usually only really need to do it manually if you are doing string concatenation in a loop or in some complex code that the compiler can't easily optimize.
The below actually works very well.
private void networkInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
var _open = false;
FormCollection fc = Application.OpenForms;
foreach (Form frm in fc)
{
if (frm.Name == "FormBrowseNetworkInformation")
{
_open = true;
frm.Select();
break;
}
}
if (_open == false)
{
var formBrowseNetworkInformation = new FormBrowseNetworkInformation();
formBrowseNetworkInformation.Show();
}
}
Just remove the .value
, like this:
function(arrayP){
for(var i = 0; i < arrayP.length; i++){
alert(arrayP[i]); //no .value here
}
}
Sure you can pass an array, but to get the element at that position, use only arrayName[index]
, the .value
would be getting the value
property off an object at that position in the array - which for things like strings, numbers, etc doesn't exist. For example, "myString".value
would also be undefined
.
There is no direct way. You either export XML and then right an XSLT to format it properly (this is the hard way). An easier way is to write multiple reports with no explicit page breaks so each exports into one sheet only in excel and then write a script that would merge for you. Either way it requires a postprocessing step.
In the iOS Dev Center developer navigate to "Certificates, Identifiers & Profiles > iOS Apps > Identifiers > App IDs"
Find the app id you wish to delete, highlight it and select "Settings". At the bottom of the resulting screen there is a "Delete" button.
Previously the only way to do this was to use a Safari & Chrome extension written by Simon Whitaker
It gives you an "Active" checkbox next to all your App IDs and allows you to relabel them to alter how they appear in the App ID drop-down when creating new provisioning profiles.
I'm not sure what you're trying to do, but here's something to consider: c();
won't do anything. c
is an instance of the class checkbox
and not a method to be called. So consider this:
public class FirstWindow extends JFrame { public FirstWindow() { checkbox c = new checkbox(); c.yourMethod(yourParameters); // call the method you made in checkbox } } public class checkbox extends JFrame { public checkbox(yourParameters) { // this is the constructor method used to initialize instance variables } public void yourMethod() // doesn't have to be void { // put your code here } }
Well, you're getting a java.lang.NoClassDefFoundError
. In your pom.xml
, hibernate-core
version is 3.3.2.GA
and declared after hibernate-entitymanager
, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final
from hibernate-entitymanager
.
You're using spring-boot
as parent, so no need to declare version of some dependencies, since they are managed by spring-boot
.
Also, hibernate-commons-annotations
is inherited from hibernate-entitymanager
and hibernate-annotations
is an old version of hibernate-commons-annotations
, you can remove both.
Finally, your pom.xml
can look like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
<artifactId>TrafficSpyService</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cloud-connectors</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>codehaus</id>
<url>http://repository.codehaus.org/org/codehaus</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
Let me know if you have a problem.
Just to add to the conversation, I have found a more elegant way to change the color of the box plot by iterating over the dictionary of the object itself
import numpy as np
import matplotlib.pyplot as plt
def color_box(bp, color):
# Define the elements to color. You can also add medians, fliers and means
elements = ['boxes','caps','whiskers']
# Iterate over each of the elements changing the color
for elem in elements:
[plt.setp(bp[elem][idx], color=color) for idx in xrange(len(bp[elem]))]
return
a = np.random.uniform(0,10,[100,5])
bp = plt.boxplot(a)
color_box(bp, 'red')
Cheers!
You're using an array of objects. Can you use a two dimensional array instead?
http://www.datatables.net/examples/data_sources/js_array.html
See this jsfiddle: http://jsfiddle.net/QhYse/
I used an array like this and it worked fine:
var data = [
["UpdateBootProfile","PASS","00:00:00",[]] ,
["NRB Boot","PASS","00:00:50.5000000",[{"TestName":"TOTAL_TURN_ON_TIME","Result":"PASS","Value":"50.5","LowerLimit":"NaN","UpperLimit":"NaN","ComparisonType":"nctLOG","Units":"SECONDS"}]] ,
["NvMgrCommit","PASS","00:00:00",[]] ,
["SyncNvToEFS","PASS","00:00:01.2500000",[]]
];
Edit to include array of objects
There's a possible solution from this question: jQuery DataTables fnrender with objects
This jsfiddle http://jsfiddle.net/j2C7j/ uses an array of objects. To not get the error I had to pad it with 3 blank values - less than optimal, I know. You may find a better way with fnRender, please post if you do.
var data = [
["","","", {"Name":"UpdateBootProfile","Result":"PASS","ExecutionTime":"00:00:00","Measurement":[]} ]
];
$(function() {
var testsTable = $('#tests').dataTable({
bJQueryUI: true,
aaData: data,
aoColumns: [
{ mData: 'Name', "fnRender": function( oObj ) { return oObj.aData[3].Name}},
{ mData: 'Result' ,"fnRender": function( oObj ) { return oObj.aData[3].Result }},
{ mData: 'ExecutionTime',"fnRender": function( oObj ) { return oObj.aData[3].ExecutionTime } }
]
});
});
As the official specification says, "one or more different sets of data are combined in a single body". So when photos and music are handled as multipart messages as mentioned in the question, probably there is some plain text metadata associated as well, thus making the request containing different types of data (binary, text), which implies the usage of multipart.
For an unknow reason, the accepted answer partially works when I send email to my gmail address. I have the attachement but not the text of the email.
If you want both attachment and text try this based on the accepted answer :
Properties props = new java.util.Properties();
props.put("mail.smtp.host", "yourHost");
props.put("mail.smtp.port", "yourHostPort");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Session session = Session.getDefaultInstance(props, null);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password");
}
});
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(mailFrom));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
msg.setSubject("your subject");
Multipart multipart = new MimeMultipart();
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText("your text");
MimeBodyPart attachmentBodyPart= new MimeBodyPart();
DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"
multipart.addBodyPart(textBodyPart); // add the text part
multipart.addBodyPart(attachmentBodyPart); // add the attachement part
msg.setContent(multipart);
Transport.send(msg);
} catch (MessagingException e) {
LOGGER.log(Level.SEVERE,"Error while sending email",e);
}
Update :
If you want to send a mail as an html content formated you have to do
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setContent(content, "text/html");
So basically setText
is for raw text and will be well display on every server email including gmail, setContent
is more for an html template and if you content is formatted as html it will maybe also works in gmail
CREATE EVENT test_event_03
ON SCHEDULE EVERY 1 MINUTE
STARTS CURRENT_TIMESTAMP
ENDS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
INSERT INTO messages(message,created_at)
VALUES('Test MySQL recurring Event',NOW());
Well there is a more easy way to do this
drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.open_drawer, R.string.close_drawer);
arrow = drawerToggle.getDrawerArrowDrawable();
And then
arrow.setColor(getResources().getColor(R.color.blue);
The code could be cleaner, but this seems to do the trick for different locales.
import java.math.BigDecimal;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class Main
{
public static void main(String[] args)
{
final BigDecimal numberA;
final BigDecimal numberB;
numberA = stringToBigDecimal("1,000,000,000.999999999999999", Locale.CANADA);
numberB = stringToBigDecimal("1.000.000.000,999999999999999", Locale.GERMANY);
System.out.println(numberA);
System.out.println(numberB);
}
private static BigDecimal stringToBigDecimal(final String formattedString,
final Locale locale)
{
final DecimalFormatSymbols symbols;
final char groupSeparatorChar;
final String groupSeparator;
final char decimalSeparatorChar;
final String decimalSeparator;
String fixedString;
final BigDecimal number;
symbols = new DecimalFormatSymbols(locale);
groupSeparatorChar = symbols.getGroupingSeparator();
decimalSeparatorChar = symbols.getDecimalSeparator();
if(groupSeparatorChar == '.')
{
groupSeparator = "\\" + groupSeparatorChar;
}
else
{
groupSeparator = Character.toString(groupSeparatorChar);
}
if(decimalSeparatorChar == '.')
{
decimalSeparator = "\\" + decimalSeparatorChar;
}
else
{
decimalSeparator = Character.toString(decimalSeparatorChar);
}
fixedString = formattedString.replaceAll(groupSeparator , "");
fixedString = fixedString.replaceAll(decimalSeparator , ".");
number = new BigDecimal(fixedString);
return (number);
}
}
/* Design Pattern "table-data gateway" */
class Gateway
{
protected $connection = null;
public function __construct()
{
$this->connection = new PDO("mysql:host=localhost; dbname=db_users", 'root', '');
}
public function loadAll()
{
$sql = 'SELECT * FROM users';
$rows = $this->connection->query($sql);
return $rows;
}
public function loadById($id)
{
$sql = 'SELECT * FROM users WHERE user_id = ' . (int) $id;
$result = $this->connection->query($sql);
return $result->fetch(PDO::FETCH_ASSOC);
// http://php.net/manual/en/pdostatement.fetch.php //
}
}
/* Print all row with column 'user_id' only */
$gateway = new Gateway();
$users = $gateway->loadAll();
$no = 1;
foreach ($users as $key => $value) {
echo $no . '. ' . $key . ' => ' . $value['user_id'] . '<br />';
$no++;
}
/* Print user_id = 1 with all column */
$user = $gateway->loadById(1);
$no = 1;
foreach ($user as $key => $value) {
echo $no . '. ' . $key . ' => ' . $value . '<br />';
$no++;
}
/* Print user_id = 1 with column 'email and password' */
$user = $gateway->loadById(1);
echo $user['email'];
echo $user['password'];
If you don't prefer the sticky bottom effect i would put it in viewDidLoad()
https://stackoverflow.com/a/38176479/4127670
Inversion of control is a design paradigm with the goal of giving more control to the targeted components of your application, the ones getting the work done.
Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time which class will be used to provide that functionality.
There are several basic techniques to implement inversion of control. These are:
Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.
Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.
Like docs say:
When the command line does not specify where to push with the
<repository>
argument,branch.*.remote
configuration for the current branch is consulted to determine where to push. If the configuration is missing, it defaults to origin.
NSArray *array = [mutableArray copy];
Copy
makes immutable copies. This is quite useful because Apple can make various optimizations. For example sending copy
to a immutable array only retains the object and returns self
.
If you don't use garbage collection or ARC remember that -copy
retains the object.
For background images, make sure to use url()
node.backgroundImage = 'url(' + e.target.result + ')';
I had a dir full of files including some that were named invoice no-product no.pdf and wanted to sort these by product no, so...
get-childitem *.pdf | sort-object -property @{expression={$\_.name.substring($\_.name.indexof("-")+1)}}
Note that in the absence of a -
this sorts by $_.name
It seems daft, but I think when you use the same bind variable twice you have to set it twice:
cmd.Parameters.Add("VarA", "24");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarC", "1234");
cmd.Parameters.Add("VarC", "1234");
Certainly that's true with Native Dynamic SQL in PL/SQL:
SQL> begin
2 execute immediate 'select * from emp where ename=:name and ename=:name'
3 using 'KING';
4 end;
5 /
begin
*
ERROR at line 1:
ORA-01008: not all variables bound
SQL> begin
2 execute immediate 'select * from emp where ename=:name and ename=:name'
3 using 'KING', 'KING';
4 end;
5 /
PL/SQL procedure successfully completed.
You can use DecimalFormat, but please also note that it is not a good idea to use double in these situations, rather use BigDecimal
I'm pretty sure it's similar to Laravel template, this is how I did mine.
<link rel="stylesheet" href="/folder/stylesheets/stylesheet.css" />
Referred: CSS file pathing problem
As stated, unit tests are designed to run without interaction.
However, you can debug unit tests, just like any other code. The easiest way is to use the Debug button in the Test Results tab.
Being able to debug means being able to use breakpoints. Being able to use breakpoints, then, means being able to use Tracepoints, which I find extremely useful in every day debugging.
Essentially, Tracepoints allow you to write to the Output window (or, more accurately, to standard output). Optionally, you can continue to run, or you can stop like a regular breakpoint. This gives you the "functionality" you are asking for, without the need to rebuild your code, or fill it up with debug information.
Simply add a breakpoint, and then right-click on that breakpoint. Select the "When Hit..." option:
Which brings up the dialog:
A few things to note:
See the documentation for more details.
count=0
with open ('filename.txt','rb') as f:
for line in f:
count+=1
print count
No. There is no such method in the standard Java SE class library.
The designers' view is that it is not needed in Java, since the language removes the need for an application1 to know about how much space needs to be reserved for a primitive value, an object or an array with a given number of elements.
You might think that a sizeof operator would be useful for people that need to know how much space their data structures take. However you can also get this information and more, simply and reliably using a Java memory profiler, so there is no need for a sizeof method.
Previous commenters made the point that sizeof(someType)
would be more readable than 4
. If you accept that readability argument, then the remedy is in your hands. Simply define a class like this ...
public class PrimitiveSizes {
public static int sizeof(byte b) { return 1; }
public static int sizeof(short s) { return 2; }
// etcetera
}
... and statically import it ...
import static PrimitiveSizes.*;
Or define some named constants; e.g.
public static final int SIZE_OF_INT = 4;
Or (Java 8 and later) use the Integer.BYTES
constant, and so on.
Why haven't the Java designers implemented this in standard libraries? My guess is that:
There is also the issue that the next demand would be for a sizeof(Object o)
method, which is fraught with technical difficulties.
The key word in the above is "they"!
1 - A programmer may need to know in order to design space efficient data structures. However, I can't imagine why that information would be needed in application code at runtime via a method call.
I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?
Basically, you use the /B
and /C
options:
START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1
try this:
declare @i tinyint = 0,
@count tinyint,
@id int,
@name varchar(max)
select @count = count(*) from table
while (@i < @count)
begin
select @id = id, @name = name from table
order by nr asc offset @i rows fetch next 1 rows only
exec stored_proc @varName = @id, @otherVarName = 'test', @varForName = @name
set @i = @i + 1
end
I found the perfect way to Ignore files in TFS like SVN does.
First of all, select the file that you want to ignore (e.g. the Web.config).
Now go to the menu tab and select:
File Source control > Advanced > Exclude web.config from source control
... and boom; your file is permanently excluded from source control.
I was facing the same problem because
System.Net.Http.Formatting
version written inside webconfig was 5.0.3 but inside the bin folder the library System.Net.Http.Formatting dll version was 4.0.2
so I just replaced with the same given inside bin
just do this clean project and build
In my opinion, jQuery's animate
is a bit overused, compared to the CSS3 transition
, which performs such animation on any 2D or 3D property. Also I'm afraid, that leaving it to the browser and by forgetting the layer called JavaScript could lead to spare CPU juice - specially, when you wish to blast with the animations. Thus, I like to have animations where the style definitions are, since you define functionality with JavaScript. The more presentation you inject into JavaScript, the more problems you'll face later on.
All you have to do is to use addClass
to the element you wish to animate, where you set a class that has CSS transition
properties. You just "activate" the animation, which stays implemented on the pure presentation layer.
.js
// with jQuery
$("#element").addClass("Animate");
// without jQuery library
document.getElementById("element").className += "Animate";
One could easly remove a class with jQuery, or remove a class without library.
.css
#element{
color : white;
}
#element.Animate{
transition : .4s linear;
color : red;
/**
* Not that ugly as the JavaScript approach.
* Easy to maintain, the most portable solution.
*/
-webkit-transform : rotate(90deg);
}
.html
<span id="element">
Text
</span>
This is a fast and convenient solution for most use cases.
I also use this when I want to implement a different styling (alternative CSS properties), and wish to change the style on-the-fly with a global .5s animation. I add a new class to the BODY
, while having alternative CSS in a form like this:
.js
$("BODY").addClass("Alternative");
.css
BODY.Alternative #element{
color : blue;
transition : .5s linear;
}
This way you can apply different styling with animations, without loading different CSS files. You only involve JavaScript to set a class
.
Your idea of an hidden form element is solid. Something like this
<form action="script.php" method="post">
<input type="hidden" name="total" id="total">
</form>
<script type="text/javascript">
var element = document.getElementById("total");
element.value = getTotalFromSomewhere;
element.form.submit();
</script>
Of course, this will change the location to script.php
. If you want to do this invisibly to the user, you'll want to use AJAX. Here's a jQuery example (for brevity). No form or hidden inputs required
$.post("script.php", { total: getTotalFromSomewhere });
The chosen solution doesn't actually work for me because I get a
"Unexpected Token <"
error in Chrome. This is because the error is thrown as soon as the parse comes across and unknown character. However, there is a way around this if you are returning only string values through ajax (which can be fairly useful if you are using PHP or ASPX to process ajax requests and might or might not return JSON depending on conditions)
The solution is quite simple, you can do the following to check if it was a valid JSON return
var IS_JSON = true;
try
{
var json = $.parseJSON(msg);
}
catch(err)
{
IS_JSON = false;
}
As I have said before, this is the solution for if you are either returning string type stuff from your AJAX request or if you are returning mixed type.
If you use JSON properly, you can have nested object without any issue :
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));
Check if scp
is installed or not on from where you want want to copy
check using which scp
If it's already installed, it will print you a path like /usr/bin/scp
Else, install scp using:
yum -y install openssh-clients
Then copy command
scp -r [email protected]:/var/www/html/database_backup/restore_fullbackup/backup_20140308-023002.sql /var/www/html/db_bkp/
In your header file say foo.h
class Foo{
public:
static void someFunction(params..);
// other stuff
}
In your implementation file say foo.cpp
#include "foo.h"
void Foo::someFunction(params..){
// Implementation of someFunction
}
Just make sure you don't use the static keyword in your method signature when you are implementing the static function in your implementation file.
Good Luck
I had a look into some of the answers above and I'd recommend against using the pattern from @Dan's answer (c. Dec 15 '10), since it incorrectly flags almost 0.4% of valid postcodes as invalid, while the others do not.
Ordnance Survey provide service called Code Point Open which:
contains a list of all the current postcode units in Great Britain
I ran each of the regexs above against the full list of postcodes (Jul 6 '13) from this data using grep
:
cat CSV/*.csv |
# Strip leading quotes
sed -e 's/^"//g' |
# Strip trailing quote and everything after it
sed -e 's/".*//g' |
# Strip any spaces
sed -E -e 's/ +//g' |
# Find any lines that do not match the expression
grep --invert-match --perl-regexp "$pattern"
There are 1,686,202 postcodes total.
The following are the numbers of valid postcodes that do not match each $pattern
:
'^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$'
# => 6016 (0.36%)
'^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$'
# => 0
'^GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4}$'
# => 0
Of course, these results only deal with valid postcodes that are incorrectly flagged as invalid. So:
'^.*$'
# => 0
I'm saying nothing about which pattern is the best regarding filtering out invalid postcodes.
On Windows, you can easily install ffmpeg via chocolatey
choco install ffmpeg
If you're registering a domain and the termination (ex .com
) it is not IDN, as Aaron Hathaway said:
Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, en.wikipedia.org
is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.
The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters a
through z
(in a case-insensitive manner), the digits 0
through 9
, and the hyphen -
. The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.
Later, Spain with it's .es
, .com.es
, .org.es
, .nom,es
, .gob.es
and .edu.es
introduced IDN tlds, if your tld is one of .es
or any other that supports it, any character can be used, but you can't combine alphabets like Latin, Greek or Cyril in one hostname, and that it respects the things that can't go at the start or at the end.
If you're using non-registered tlds, just for local networking, like with local DNS or with hosts files, you can treat them all as IDN.
Keep in mind some programs could not work well, especially old, outdated and unpopular ones.
You can use
t1<- t1[-4:-6,-7:-9]
or
t1 <- t1[-(4:6), -(7:9)]
or
t1 <- t1[-c(4, 5, 6), -c(7, 8, 9)]
You can pass vectors
to select rows/columns
to be deleted. First two methods are useful if you are trying to delete contiguous rows/columns. Third method is useful if You are trying to delete discrete rows/columns
.
> t1 <- array(1:20, dim=c(10,10));
> t1[-c(1, 4, 6, 7, 9), -c(2, 3, 8, 9)]
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 2 12 2 12 2 12
[2,] 3 13 3 13 3 13
[3,] 5 15 5 15 5 15
[4,] 8 18 8 18 8 18
[5,] 10 20 10 20 10 20
Create a drawable checkbox selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/checkbox"
android:state_checked="false"/>
<item android:drawable="@drawable/checkboxselected"
android:state_checked="true"/>
<item android:drawable="@drawable/checkbox"/>
</selector>
Make sure your checkbox is like this android:button="@drawable/checkbox_selector"
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:button="@drawable/checkbox_selector"
android:text="CheckBox"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/Black" />
It's a linker error. ld
is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.
The error message tells you that none of the object files you're linking against contains a definition for avergecolumns
. The reason for that is that the function you've defined is called averagecolumns
(in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).
For Laravel Homestead Users: If anyone using Laravel with homestead you can access app backend using 192.168.10.10 in emulator
Still not working? Another good solution is to use ngrok https://ngrok.com/
An intuitive explanation to this is by simply analysing a single loop:
So the total time for a single loop is O(1)+O(e). Now sum it for each vertex as each vertex is visited once. This gives
For every V
=>
O(1)
+
O(e)
=> O(V) + O(E)
JavaScript
function playAudio(url) {
new Audio(url).play();
}
HTML
<img src="image.png" onclick="playAudio('mysound.mp3')">
Supported in most modern browsers and easy to embed into HTML elements.
If you disable a form field, this won't be sent when form is submitted.
So if you need a readonly
that works like disabled
but sending values do this :
After any change in readonly properties of an element.
$('select.readonly option:not(:selected)').attr('disabled',true);
$('select:not([readonly]) option').removeAttr('disabled');
Mine were located here on Ubuntu 18.04 when I installed JavaFX using apt install openjfx
(as noted already by @jewelsea above)
/usr/share/java/openjfx/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
To start with Socket.IO I suggest you read first the example on the main page:
On the server side, read the "How to use" on the GitHub source page:
https://github.com/Automattic/socket.io
And on the client side:
https://github.com/Automattic/socket.io-client
Finally you need to read this great tutorial:
http://howtonode.org/websockets-socketio
Hint: At the end of this blog post, you will have some links pointing on source code that could be some help.
Using pandas: pd.Timestamp("today").strftime("%m/%d/%Y")
I was getting exception
java.util.zip.ZipException: invalid entry CRC (expected 0x0 but got 0xdeadface)
at java.util.zip.ZipInputStream.read(ZipInputStream.java:221)
at java.util.zip.ZipInputStream.closeEntry(ZipInputStream.java:140)
at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:118)
...
when unzipping an archive in Java. The archive itself didn't seem corrupted as 7zip (and others) opened it without any problems or complaints about invalid CRC.
I switched to Apache Commons Compress for reading the zip-entries and that resolved the problem.
You could always include it using __DIR__
:
include(dirname(__DIR__).'/config.php');
__DIR__
is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__
. In this case, as we need to ascend a directory we use PHP's dirname
which ascends the file tree, and from here we can access config.php
.
You could set the root path in this method too:
define('ROOT_PATH', dirname(__DIR__) . '/');
in test.php would set your root to be at the /root/
level.
include(ROOT_PATH.'config.php');
Should then work to include the config file from where you want.
With a running instance of myExecutableName
having a PID 15073
:
hitting Tab twice after $ gdb myExecu
in the command line, will automagically autocompletes to:
$ gdb myExecutableName 15073
and will attach gdb to this process. That's nice!
On my mac from a terminal:
$ ./adb kill-server
$ ./adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
I opened the eclipse and set the ddms port to 5037. it works fine.
Just in case you don't want to import a big library like jQuery to accomplish something this trivial, you can use the built-in method querySelectorAll
instead. Almost all selector strings used for jQuery work with DOM methods as well:
const anchors = document.querySelectorAll('a[href$="ABC"]');
Or, if you know that there's only one matching element:
const anchor = document.querySelector('a[href$="ABC"]');
You may generally omit the quotes around the attribute value if the value you're searching for is alphanumeric, eg, here, you could also use
a[href$=ABC]
but quotes are more flexible and generally more reliable.
They JKS file is just a container for certificates and key pairs. In a client-side authentication scenario, the various parts of the keys will be located here:
The separation of truststore and keystore is not mandatory but recommended. They can be the same physical file.
To set the filesystem locations of the two stores, use the following system properties:
-Djavax.net.ssl.keyStore=clientsidestore.jks
and on the server:
-Djavax.net.ssl.trustStore=serversidestore.jks
To export the client's certificate (public key) to a file, so you can copy it to the server, use
keytool -export -alias MYKEY -file publicclientkey.cer -store clientsidestore.jks
To import the client's public key into the server's keystore, use (as the the poster mentioned, this has already been done by the server admins)
keytool -import -file publicclientkey.cer -store serversidestore.jks
Another method using a regular expression (this is more correct than Zachary's answer):
var string1 = 'someText',
string2 = 'SometexT',
regex = new RegExp('^' + string1 + '$', 'i');
if (regex.test(string2)) {
return true;
}
RegExp.test() will return true or false.
Also, adding the '^' (signifying the start of the string) to the beginning and '$' (signifying the end of the string) to the end make sure that your regular expression will match only if 'sometext' is the only text in stringToTest. If you're looking for text that contains the regular expression, it's ok to leave those off.
It might just be easier to use the string.toLowerCase() method.
So... regular expressions are powerful, but you should only use them if you understand how they work. Unexpected things can happen when you use something you don't understand.
There are tons of regular expression 'tutorials', but most appear to be trying to push a certain product. Here's what looks like a decent tutorial... granted, it's written for using php, but otherwise, it appears to be a nice beginner's tutorial: http://weblogtoolscollection.com/regex/regex.php
This appears to be a good tool to test regular expressions: http://gskinner.com/RegExr/
put this code in your html header:
<style type="text/css">
html {
overflow: auto;
}
</style>
Assign the enddate to some date variable because AddDays
method returns new Datetime as the result..
Datetime somedate=endDate.AddDays(2);
This should work.
$foo = someFunction 2>$null
you need to wrap your text inside div and float it left while wrapper div should have height, and I've also added line height for vertical alignment
<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray;height:30px;">
<div style="float:left;line-height:30px;">Contact Details</div>
<button type="button" class="edit_button" style="float: right;">My Button</button>
</div>
also js fiddle here =) http://jsfiddle.net/xQgSm/
They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.
I am posting a complete example which I finally got working. Here I am reading in a file rooms/rooms.txt
from a script rooms/rooms.js
var fs = require('fs');
var path = require('path');
var readStream = fs.createReadStream(path.join(__dirname, '../rooms') + '/rooms.txt', 'utf8');
let data = ''
readStream.on('data', function(chunk) {
data += chunk;
}).on('end', function() {
console.log(data);
});
First, as a one-time data-scrubbing exercise, delete the orphaned rows e.g.
DELETE
FROM ReferencingTable
WHERE NOT EXISTS (
SELECT *
FROM MainTable AS T1
WHERE T1.pk_col_1 = ReferencingTable.pk_col_1
);
Second, as a one-time schema-alteration exercise, add the ON DELETE CASCADE
referential action to the foreign key on the referencing table e.g.
ALTER TABLE ReferencingTable DROP
CONSTRAINT fk__ReferencingTable__MainTable;
ALTER TABLE ReferencingTable ADD
CONSTRAINT fk__ReferencingTable__MainTable
FOREIGN KEY (pk_col_1)
REFERENCES MainTable (pk_col_1)
ON DELETE CASCADE;
Then, forevermore, rows in the referencing tables will automatically be deleted when their referenced row is deleted.
I found it really interesting because I just experienced the same thing not so long time ago. However, I came across to an example on the Internet about the solution regarding this.
Without any further ado, see the code fragment below:
<select>
<option value data-isdefault="true">--Choose one Option--</option>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
With that, it will stay un-submittable but selectable, anytime. More convenience for User Interface and great for User Experience.
Well that's all, I hope it helps. Cheers!
Assuming Windows, take a look at the ReadConsoleInput function.
You can use datetime module to help here. Also, as a side note, a simple date subtraction should work as below:
import datetime as dt
import numpy as np
import pandas as pd
#Assume we have df_test:
In [222]: df_test
Out[222]:
first_date second_date
0 2016-01-31 2015-11-19
1 2016-02-29 2015-11-20
2 2016-03-31 2015-11-21
3 2016-04-30 2015-11-22
4 2016-05-31 2015-11-23
5 2016-06-30 2015-11-24
6 NaT 2015-11-25
7 NaT 2015-11-26
8 2016-01-31 2015-11-27
9 NaT 2015-11-28
10 NaT 2015-11-29
11 NaT 2015-11-30
12 2016-04-30 2015-12-01
13 NaT 2015-12-02
14 NaT 2015-12-03
15 2016-04-30 2015-12-04
16 NaT 2015-12-05
17 NaT 2015-12-06
In [223]: df_test['Difference'] = df_test['first_date'] - df_test['second_date']
In [224]: df_test
Out[224]:
first_date second_date Difference
0 2016-01-31 2015-11-19 73 days
1 2016-02-29 2015-11-20 101 days
2 2016-03-31 2015-11-21 131 days
3 2016-04-30 2015-11-22 160 days
4 2016-05-31 2015-11-23 190 days
5 2016-06-30 2015-11-24 219 days
6 NaT 2015-11-25 NaT
7 NaT 2015-11-26 NaT
8 2016-01-31 2015-11-27 65 days
9 NaT 2015-11-28 NaT
10 NaT 2015-11-29 NaT
11 NaT 2015-11-30 NaT
12 2016-04-30 2015-12-01 151 days
13 NaT 2015-12-02 NaT
14 NaT 2015-12-03 NaT
15 2016-04-30 2015-12-04 148 days
16 NaT 2015-12-05 NaT
17 NaT 2015-12-06 NaT
Now, change type to datetime.timedelta, and then use the .days method on valid timedelta objects.
In [226]: df_test['Diffference'] = df_test['Difference'].astype(dt.timedelta).map(lambda x: np.nan if pd.isnull(x) else x.days)
In [227]: df_test
Out[227]:
first_date second_date Difference Diffference
0 2016-01-31 2015-11-19 73 days 73
1 2016-02-29 2015-11-20 101 days 101
2 2016-03-31 2015-11-21 131 days 131
3 2016-04-30 2015-11-22 160 days 160
4 2016-05-31 2015-11-23 190 days 190
5 2016-06-30 2015-11-24 219 days 219
6 NaT 2015-11-25 NaT NaN
7 NaT 2015-11-26 NaT NaN
8 2016-01-31 2015-11-27 65 days 65
9 NaT 2015-11-28 NaT NaN
10 NaT 2015-11-29 NaT NaN
11 NaT 2015-11-30 NaT NaN
12 2016-04-30 2015-12-01 151 days 151
13 NaT 2015-12-02 NaT NaN
14 NaT 2015-12-03 NaT NaN
15 2016-04-30 2015-12-04 148 days 148
16 NaT 2015-12-05 NaT NaN
17 NaT 2015-12-06 NaT NaN
Hope that helps.
You can give simply hide this by giving a boolean parameter----->
debugShowCheckedModeBanner: false,
void main() {
Bloc.observer = SimpleBlocDelegate();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Prescription Writing Software',
theme: ThemeData(
primarySwatch: Colors.blue,
scaffoldBackgroundColor: Colors.white,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: SplashScreen(),
);
}
}
In WPF it seems this code,
System.Windows.Forms.MessageBox.Show("Test");
is replaced with:
System.Windows.MessageBox.Show("Test");
There are three different font families that I know of that you can choose from and each has its own weight element that needs to be applied:
First
font-family: 'Font Awesome 5 Brands';
content: "\f373";
Second
font-family: 'Font Awesome 5 Free';
content: "\f061";
font-weight: 900;
Third
font-family: 'Font Awesome 5 Pro';
Reference here - https://fontawesome.com/how-to-use/on-the-web/advanced/css-pseudo-elements
Hope this helps.
I found this;
from here;
vba- Can a combobox present more then one column on it's textbox part?
and this may help;
I added a sort of demo here;
For Kotlin users:
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?) : View?
{
// Inflate the layout for this fragment
var myView = inflater.inflate(R.layout.fragment_home, container, false)
var btn_test = myView.btn_test as Button
btn_test.setOnClickListener {
textView.text = "hunny home fragment"
}
return myView
}
I have just tested Google Geocoder and got the same problem as you have. I noticed I only get the OVER_QUERY_LIMIT status once every 12 requests So I wait for 1 second (that's the minimum delay to wait) It slows down the application but less than waiting 1 second every request
info = getInfos(getLatLng(code)); //In here I call Google API
record(code, info);
generated++;
if(generated%interval == 0) {
holdOn(delay); // Every x requests, I sleep for 1 second
}
With the basic holdOn method :
private void holdOn(long delay) {
try {
Thread.sleep(delay);
} catch (InterruptedException ex) {
// ignore
}
}
Hope it helps
Making more general the @showdev answer.
var getObjectByValue = function (array, key, value) {
return array.filter(function (object) {
return object[key] === value;
});
};
Example:
getObjectByValue(data, "code", "DZ" );
Short code example:
.slider ul {
overflow: hidden;
-webkit-transition: max-height 3.3s ease;
}
.slider.hide ul {
max-height: 0px;
}
.slider.show ul {
max-height: 1000px;
}
Just going to add a simple example to what everyone has explained,
json.load()
json.load
can deserialize a file itself i.e. it accepts a file
object, for example,
# open a json file for reading and print content using json.load
with open("/xyz/json_data.json", "r") as content:
print(json.load(content))
will output,
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
If I use json.loads
to open a file instead,
# you cannot use json.loads on file object
with open("json_data.json", "r") as content:
print(json.loads(content))
I would get this error:
TypeError: expected string or buffer
json.loads()
json.loads()
deserialize string.
So in order to use json.loads
I will have to pass the content of the file using read()
function, for example,
using content.read()
with json.loads()
return content of the file,
with open("json_data.json", "r") as content:
print(json.loads(content.read()))
Output,
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
That's because type of content.read()
is string, i.e. <type 'str'>
If I use json.load()
with content.read()
, I will get error,
with open("json_data.json", "r") as content:
print(json.load(content.read()))
Gives,
AttributeError: 'str' object has no attribute 'read'
So, now you know json.load
deserialze file and json.loads
deserialize a string.
Another example,
sys.stdin
return file
object, so if i do print(json.load(sys.stdin))
, I will get actual json data,
cat json_data.json | ./test.py
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
If I want to use json.loads()
, I would do print(json.loads(sys.stdin.read()))
instead.
You'd need to remove the blank table cell element entirely, and change the colspan attribute on another cell in the row to encompass the released space, e.g.:
refToCellToRemove.remove();
refTocellToExpand.colspan = 4;
Note that setting it via setAttribute (which would otherwise be correct) will not work properly on IE.
Beware: IE does some very strange table layout things when you muck about with colspans dynamically. If you can avoid it, I would.
Why not execute in backticks ?
x=`echo "$y" | tr '[:upper:]' '[:lower:]'`
This assigns the result of the command in backticks to the variable x
. (i.e. it's not particular to tr
but is a common pattern/solution for shell scripting)
You can use $(..)
instead of the backticks. See here for more info.
PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.
Some workaround solutions are:
Split IN clause to multiple IN clauses where literals are less than 1000 and combine them using OR clauses:
Split the original "WHERE" clause from one "IN" condition to several "IN" condition:
Select id from x where id in (1, 2, ..., 1000,…,1500);
To:
Select id from x where id in (1, 2, ..., 999) OR id in (1000,...,1500);
The limit of 1000 applies to sets of single items: (x) IN ((1), (2), (3), ...). There is no limit if the sets contain two or more items: (x, 0) IN ((1,0), (2,0), (3,0), ...):
Select id from x where (x.id, 0) IN ((1, 0), (2, 0), (3, 0),.....(n, 0));
Select id from x where id in (select id from <temporary-table>);
If possible, let us locate/identify the busy process, kill that process and then unmount
the samba share/ drive to minimize damage:
lsof | grep '<mountpoint of /dev/sda1>'
(or whatever the mounted device is)
pkill target_process
(kills busy proc. by name | kill PID
| killall target_process
)
umount /dev/sda1
(or whatever the mounted device is)
Change your main to:
public static void main(String[] args) {
EchoServer echoServer = new EchoServer();
echoServer.listen();
}
When you declare Object EchoServer0;
you have a few mistakes.
new
.Query A is the same as:
select 'true' where 3 = 1 or 3 = 2 or 3 = 3 or 3 = null
Since 3 = 3
is true, you get a result.
Query B is the same as:
select 'true' where 3 <> 1 and 3 <> 2 and 3 <> null
When ansi_nulls
is on, 3 <> null
is UNKNOWN, so the predicate evaluates to UNKNOWN, and you don't get any rows.
When ansi_nulls
is off, 3 <> null
is true, so the predicate evaluates to true, and you get a row.
Should you use webmin
then these are the steps how to set the PATH
value:
System
-> Scheduled Cron Jobs
-> Create a new environment variable
-> For user: <Select the user name>
-> Variable name: PATH
-> Value: /usr/bin:/bin:<your personal path>
-> Add environment variable: Before all Cron jobs for user
Git stash clear will clear complete stash,
cmd: git stash clear
If you want to delete a particular stash with a stash index, you can use the drop.
cmd: git stash drop 4
(4 is stash id or stash index)
Hello guys Most of the codes you will find will return you server ip address not client ip address .however this code returns correct client ip address.Give it a try. For More info just check this
https://www.youtube.com/watch?v=Nkf37DsxYjI
for getting your local ip address using javascript you can use put this code inside your script tag
<script>
var RTCPeerConnection = /*window.RTCPeerConnection ||*/
window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) (function () {
var rtc = new RTCPeerConnection({ iceServers: [] });
if (1 || window.mozRTCPeerConnection) {
rtc.createDataChannel('', { reliable: false });
};
rtc.onicecandidate = function (evt) {
if (evt.candidate)
grepSDP("a=" + evt.candidate.candidate);
};
rtc.createOffer(function (offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function (e) { console.warn("offer failed", e); });
var addrs = Object.create(null);
addrs["0.0.0.0"] = false;
function updateDisplay(newAddr) {
if (newAddr in addrs) return;
else addrs[newAddr] = true;
var displayAddrs = Object.keys(addrs).filter(function
(k) { return addrs[k]; });
document.getElementById('list').textContent =
displayAddrs.join(" or perhaps ") || "n/a";
}
function grepSDP(sdp) {
var hosts = [];
sdp.split('\r\n').forEach(function (line) {
if (~line.indexOf("a=candidate")) {
var parts = line.split(' '),
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
} else if (~line.indexOf("c=")) {
var parts = line.split(' '),
addr = parts[2];
updateDisplay(addr);
}
});
}
})(); else
{
document.getElementById('list').innerHTML = "<code>ifconfig| grep inet | grep -v inet6 | cut -d\" \" -f2 | tail -n1</code>";
document.getElementById('list').nextSibling.textContent = "In Chrome and Firefox your IP should display automatically, by the power of WebRTCskull.";
}
</script>
<body>
<div id="list"></div>
</body>
and For getting your public ip address you can use put this code inside your script tag
function getIP(json) {
document.write("My public IP address is: ", json.ip);
}
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
I think the easiest would be something like:
// Joda Time
DateTime dateTime=new DateTime();
StartOfDayMillis = dateTime.withMillis(System.currentTimeMillis()).withTimeAtStartOfDay().getMillis();
EndOfDayMillis = dateTime.withMillis(StartOfDayMillis).plusDays(1).minusSeconds(1).getMillis();
These millis can be then converted into Calendar,Instant or LocalDate as per your requirement with Joda Time.
Assuming that your original dataset is similar to the one you created (i.e. with NA
as character
. You could specify na.strings
while reading the data using read.table
. But, I guess NAs would be detected automatically.
The price
column is factor
which needs to be converted to numeric
class. When you use as.numeric
, all the non-numeric elements (i.e. "NA"
, FALSE) gets coerced to NA
) with a warning.
library(dplyr)
df %>%
mutate(price=as.numeric(as.character(price))) %>%
group_by(company, year, product) %>%
summarise(total.count=n(),
count=sum(is.na(price)),
avg.price=mean(price,na.rm=TRUE),
max.price=max(price, na.rm=TRUE))
I am using the same dataset
(except the ...
row) that was showed.
df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
"Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
"7.12", "12.99", "10.99", "NA",FALSE)))
Why not try using the following:
$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');
Download and install LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0).
Steps for open SDF Files:
Click Add Connection
Select Build data context automatically and Default (LINQ to SQL), then Next.
Under Provider choose SQL CE 4.0.
Under Database with Attach database file selected, choose Browse to select your .sdf file.
Click OK.
it's useful to create a new file by mkdir filename
,then running the command of git clone xxxxx
,it does work in my computer
SELECT SC.StoreId
FROM StoreClients SC
WHERE SC.StoreId NOT IN (SELECT StoreId FROM StoreClients WHERE ClientId = 5)
In this way neither JOIN
nor GROUP BY
is necessary.
UPDATE messages SET
status=10
WHERE ID in (SELECT TOP (10) Id FROM Table WHERE status=0 ORDER BY priority DESC);
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
Wanted to add my experience with converting. I had many text
fields in ancient Linq2SQL code. This was to allow text
columns present in indexes to be rebuilt ONLINE.
First I've known about the benefits for years, but always assumed that converting would mean some scary long queries where SQL Server would have to rebuild the table and copy everything over, bringing down my websites and raising my heartrate.
I was also concerned that the Linq2SQL could cause errors if it was doing some kind of verification of the column type.
Happy to report though, that the ALTER commands returned INSTANTLY - so they are definitely only changing table metadata. There may be some offline work happening to bring <8000 character data back to be in-table, but the ALTER command was instant.
I ran the following to find all columns needing conversion:
SELECT concat('ALTER TABLE dbo.[', table_name, '] ALTER COLUMN [', column_name, '] VARCHAR(MAX)'), table_name, column_name
FROM information_schema.columns where data_type = 'TEXT' order by table_name, column_name
SELECT concat('ALTER TABLE dbo.[', table_name, '] ALTER COLUMN [', column_name, '] NVARCHAR(MAX)'), table_name, column_name
FROM information_schema.columns where data_type = 'NTEXT' order by table_name, column_name
This gave me a nice list of queries, which I just selected and copied to a new window. Like I said - running this was instant.
Linq2SQL is pretty ancient - it uses a designer that you drag tables onto. The situation may be more complex for EF Code first but I haven't tackled that yet.
Use a subquery:
SELECT * FROM
(
SELECT * FROM users ORDER BY rand() LIMIT 20
) T1
ORDER BY name
The inner query selects 20 users at random and the outer query orders the selected users by name.
Use the Array#join
method (the argument to join
is what to insert between the strings - in this case a space):
@arr.join(" ")
I'm going to make a summary of the proposed solutions and the one that helped me!
After reading this bug report: bug in the way NetBeans 6.8 creates the jar for a Java Library Project.
Create a manifest.mf file in my project root
Edit manifest.mf. Mine looked something like this:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: 16.3-b01 (Sun Microsystems Inc.)
Main-Class: com.example.MainClass
Class-Path: lib/lib1.jar lib/lib2.jar
Open file /nbproject/project.properties
Add line
manifest.file=manifest.mf
Clean + Build of project
Now the .jar is successfully build.
Thank you very much vkraemer
#include
it used to get "things" from another file to the one the #include
is used in.
Ex:
in file: main.cpp
#include "otherfile.h"
// some stuff here using otherfile.h objects,
// functions or classes declared inside
Header guard is used on the top of each header file (*.h) to prevent including the same file more then once (if it happens you will get compile errors).
in file: otherfile.h
#ifndef OTHERFILE
#define OTHERFILE
// declare functions, classes or objects here
#endif
even if you put #include
"otherfile.h" n time in your code, this inside it will not be redeclared.
Use the .clone() method on your List. It will return a shallow copy, meaning that it will contain pointers to the same objects, so you won't have to copy the list. Then just use Collections.
Ergo,
Collections.reverse(list.clone());
If you are using a List
and don't have access to clone()
you can use subList()
:
List<?> shallowCopy = list.subList(0, list.size());
Collections.reverse(shallowCopy);
I've resolved this using:
.element:before {
font-family: "Font Awesome 5 Free" , "CircularStd";
content: "\f017" " Date";
}
Using the font family "font awesome 5 free" for the icon, and after, We have to specify the font that we are using again because if we doesn't do this, navigator will use the default font (times new roman or something like this).
I hope you have resolved your issue. If you still got issue then double check again if you install this Oracle under a domain account. I found a thread that says Oracle XE giving same error when installing under domain account. Please use a local account instead.
Source:
https://community.oracle.com/thread/2141735?start=0&tstart=0
One thing to note that you guys are over-complicating the problem just like a lot of other posts! All you need to do is create drawable selectors with whatever backgrounds you need and set them to actual items. I just spend two hours trying your solutions (all suggested on this page) and none of them worked. Not to mention that there are tons of errors that essentially slow your performance in those try/catch blocks you have.
Anyways here is a menu xml file:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/m1"
android:icon="@drawable/item1_selector"
/>
<item android:id="@+id/m2"
android:icon="@drawable/item2_selector"
/>
</menu>
Now in your item1_selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/item_highlighted" />
<item android:state_selected="true" android:drawable="@drawable/item_highlighted" />
<item android:state_focused="true" android:drawable="@drawable/item_nonhighlighted" />
<item android:drawable="@drawable/item_nonhighlighted" />
</selector>
Next time you decide to go to the supermarket through Canada try google maps!
if you want to shrink one slide for instance, add shapes to hide the unwanted background margins. you can set the shape color filling as the background (gray or black). It's "ugly" but it works
System read-only variable %CD%
keeps the path of the caller of the batch, not the batch file location.
You can get the name of the batch script itself as typed by the user with %0
(e.g. scripts\mybatch.bat
). Parameter extensions can be applied to this so %~dp0
will return the Drive and Path to the batch script (e.g. W:\scripts\
) and %~f0
will return the full pathname (e.g. W:\scripts\mybatch.cmd
).
You can refer to other files in the same folder as the batch script by using this syntax:
CALL %0\..\SecondBatch.cmd
This can even be used in a subroutine, Echo %0
will give the call label but, echo "%~nx0"
will give you the filename of the batch script.
When the %0
variable is expanded, the result is enclosed in quotation marks.
You can't have a non-keyword argument after a keyword argument.
Make sure you re-arrange your function arguments like so:
def a(len1,til,hgt=len1,col=0):
system('mode con cols='+len1,'lines='+hgt)
system('title',til)
system('color',col)
a(64,"hi",25,"0b")
This isn't as easy to do as one might expect -- you can really only do vertical alignment if you know the height of your container. IF this is the case, you can do it with absolute positioning.
The concept is to set the top / left positions at 50%, and then use negative margins (set to half the height / width) to pull the container back to being centered.
Example: http://jsbin.com/ipawe/edit
Basic CSS:
#mydiv {
position: absolute;
top: 50%;
left: 50%;
height: 400px;
width: 700px;
margin-top: -200px; /* -(1/2 height) */
margin-left: -350px; /* -(1/2 width) */
}
Had the same problem . Fixed it by installing Microsoft Foundation Classes for C++.
To simply combine them you can place them all together like this:
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2,"_AB","_"),"_CD","_"),"_EF","_"),"_40K",""),"_60K",""),"_S_","_"),"_","-")
(note that this may pass the older Excel limit of 7 nested statements. I'm testing in Excel 2010
Another way to do it is by utilizing Left
and Right
functions.
This assumes that the changing data on the end is always present and is 8 characters long
=SUBSTITUTE(LEFT(A2,LEN(A2)-8),"_","-")
This will achieve the same resulting string
If the string doesn't always end with 8 characters that you want to strip off you can search for the "_S" and get the current location. Try this:
=SUBSTITUTE(LEFT(A2,FIND("_S",A2,1)),"_","-")
This is a tricky question.
There a set of problems about file permissions. If you can do this at the command line
$ sudo chown myaccount /path/to/file
then you have a standard permissions problem. Make sure you own the file and have permission to modify the directory.
If you cannnot get permissions, then you have probably mounted a FAT-32 filesystem. If you ls -l
the file, and you find it is owned by root and a member of the "plugdev" group, then you are certain its the issue. FAT-32 permissions are set at the time of mounting, using the line of /etc/fstab file. You can set the uid/gid of all the files like this:
UUID=C14C-CE25 /big vfat utf8,umask=007,uid=1000,gid=1000 0 1
Also, note that the FAT-32 won't take symbolic links.
Wrote the whole thing up at http://www.charlesmerriam.com/blog/2009/12/operation-not-permitted-and-the-fat-32-system/
If you want to add html content to your email, url encode your html code for the message body and include it in your mailto link code, but trouble is you can't set the type of the email from this link from plaintext to html, the client using the link needs their mail client to send html emails by default. In case you want to test here is the code for a simple mailto link, with an image wrapped in a link (angular style urls added for visibility):
<a href="mailto:?body=%3Ca%20href%3D%22{{ scope.url }}%22%3E%3Cimg%20src%3D%22{{ scope.url }}%22%20width%3D%22300%22%20%2F%3E%3C%2Fa%3E">
The html tags are url encoded.
As some people indicated, the officially accepted answer does not quite return the external removable SD card. And i ran upon the following thread that proposes a method I've tested on some Android devices and seems to work reliably, so i thought of re-sharing here as i don't see it in the other responses:
http://forums.androidcentral.com/samsung-galaxy-s7/668364-whats-external-sdcard-path.html
Kudos to paresh996 for coming up with the answer itself, and i can attest I've tried on Samsung S7 and S7edge and seems to work.
Now, i needed a method that returned a valid path where to read files, and that considered the fact that there might not be an external SD, in which case the internal storage should be returned, so i modified the code from paresh996 to this :
File getStoragePath() {
String removableStoragePath;
File fileList[] = new File("/storage/").listFiles();
for (File file : fileList) {
if(!file.getAbsolutePath().equalsIgnoreCase(Environment.getExternalStorageDirectory().getAbsolutePath()) && file.isDirectory() && file.canRead()) {
return file;
}
}
return Environment.getExternalStorageDirectory();
}
Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package
import sun.misc.BASE64Encoder;
import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;
and then,
String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );
public String getAuthantication(String username, String password) {
String auth = new String(Base64.encode(username + ":" + password));
return auth;
}
Adding a new answer to this as the question of printing PDF's in .net has been around for a long time and most of the answers pre-date the Google Pdfium library, which now has a .net wrapper. For me I was researching this problem myself and kept coming up blank, trying to do hacky solutions like spawning Acrobat or other PDF readers, or running into commercial libraries that are expensive and have not very compatible licensing terms. But the Google Pdfium library and the PdfiumViewer .net wrapper are Open Source so are a great solution for a lot of developers, myself included. PdfiumViewer is licensed under the Apache 2.0 license.
You can get the NuGet package here:
https://www.nuget.org/packages/PdfiumViewer/
and you can find the source code here:
https://github.com/pvginkel/PdfiumViewer
Here is some simple code that will silently print any number of copies of a PDF file from it's filename. You can load PDF's from a stream also (which is how we normally do it), and you can easily figure that out looking at the code or examples. There is also a WinForm PDF file view so you can also render the PDF files into a view or do print preview on them. For us I simply needed a way to silently print the PDF file to a specific printer on demand.
public bool PrintPDF(
string printer,
string paperName,
string filename,
int copies)
{
try {
// Create the printer settings for our printer
var printerSettings = new PrinterSettings {
PrinterName = printer,
Copies = (short)copies,
};
// Create our page settings for the paper size selected
var pageSettings = new PageSettings(printerSettings) {
Margins = new Margins(0, 0, 0, 0),
};
foreach (PaperSize paperSize in printerSettings.PaperSizes) {
if (paperSize.PaperName == paperName) {
pageSettings.PaperSize = paperSize;
break;
}
}
// Now print the PDF document
using (var document = PdfDocument.Load(filename)) {
using (var printDocument = document.CreatePrintDocument()) {
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.PrintController = new StandardPrintController();
printDocument.Print();
}
}
return true;
} catch {
return false;
}
}
Here is an example - accepting no parameters and returning nothing.
class CallbackTest
{
public myCallback: {(): void;};
public doWork(): void
{
//doing some work...
this.myCallback(); //calling callback
}
}
var test = new CallbackTest();
test.myCallback = () => alert("done");
test.doWork();
If you want to accept a parameter, you can add that too:
public myCallback: {(msg: string): void;};
And if you want to return a value, you can add that also:
public myCallback: {(msg: string): number;};
That would be an HTML Encoded Line Feed character (using the hexadecimal value).
The decimal value would be
A union
is useful in a couple scenarios.
union
can be a tool for very low level manipulation like writing device drivers for a kernel.
An example of that is dissecting a float
number by using union
of a struct
with bitfields and a float
. I save a number in the float
, and later I can access particular parts of the float
through that struct
. The example shows how union
is used to have different angles to look at data.
#include <stdio.h>
union foo {
struct float_guts {
unsigned int fraction : 23;
unsigned int exponent : 8;
unsigned int sign : 1;
} fg;
float f;
};
void print_float(float f) {
union foo ff;
ff.f = f;
printf("%f: %d 0x%X 0x%X\n", f, ff.fg.sign, ff.fg.exponent, ff.fg.fraction);
}
int main(){
print_float(0.15625);
return 0;
}
Take a look at single precision description on wikipedia. I used the example and the magic number 0.15625 from there.
union
can also be used to implement an algebraic data type that has multiple alternatives. I found an example of that in the "Real World Haskell" book by O'Sullivan, Stewart, and Goerzen.
Check it out in the The discriminated union section.
Cheers!
Actually, For me below works fine.
@Component
public class MyBean {
public static String prop;
@Value("${some.prop}")
public void setProp(String prop) {
this.prop= prop;
}
public MyBean() {
}
@PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
Now whereever i want, just invoke
MyBean.prop
it will return value.
From Wikipedia (granularity):
Granularity is the extent to which a system is broken down into small parts, either the system itself or its description or observation. It is the extent to which a larger entity is subdivided. For example, a yard broken into inches has finer granularity than a yard broken into feet.
Coarse-grained systems consist of fewer, larger components than fine-grained systems; a coarse-grained description of a system regards large subcomponents while a fine-grained description regards smaller components of which the larger ones are composed.
why, how and which parameters are passed to Asynctask<>, see detail here. I think it is the best explanation.
Google's Android Documentation Says that :
An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
AsyncTask's generic types :
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution. Progress, the type of the progress units published during the background computation. Result, the type of the result of the background computation. Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
You Can further refer : http://developer.android.com/reference/android/os/AsyncTask.html
Or You Can clear whats the role of AsyncTask by refering Sankar-Ganesh's Blog
Well The structure of a typical AsyncTask class goes like :
private class MyTask extends AsyncTask<X, Y, Z>
protected void onPreExecute(){
}
This method is executed before starting the new Thread. There is no input/output values, so just initialize variables or whatever you think you need to do.
protected Z doInBackground(X...x){
}
The most important method in the AsyncTask class. You have to place here all the stuff you want to do in the background, in a different thread from the main one. Here we have as an input value an array of objects from the type “X” (Do you see in the header? We have “...extends AsyncTask” These are the TYPES of the input parameters) and returns an object from the type “Z”.
protected void onProgressUpdate(Y y){
} This method is called using the method publishProgress(y) and it is usually used when you want to show any progress or information in the main screen, like a progress bar showing the progress of the operation you are doing in the background.
protected void onPostExecute(Z z){
} This method is called after the operation in the background is done. As an input parameter you will receive the output parameter of the doInBackground method.
What about the X, Y and Z types?
As you can deduce from the above structure:
X – The type of the input variables value you want to set to the background process. This can be an array of objects.
Y – The type of the objects you are going to enter in the onProgressUpdate method.
Z – The type of the result from the operations you have done in the background process.
How do we call this task from an outside class? Just with the following two lines:
MyTask myTask = new MyTask();
myTask.execute(x);
Where x is the input parameter of the type X.
Once we have our task running, we can find out its status from “outside”. Using the “getStatus()” method.
myTask.getStatus(); and we can receive the following status:
RUNNING - Indicates that the task is running.
PENDING - Indicates that the task has not been executed yet.
FINISHED - Indicates that onPostExecute(Z) has finished.
Hints about using AsyncTask
Do not call the methods onPreExecute, doInBackground and onPostExecute manually. This is automatically done by the system.
You cannot call an AsyncTask inside another AsyncTask or Thread. The call of the method execute must be done in the UI Thread.
The method onPostExecute is executed in the UI Thread (here you can call another AsyncTask!).
The input parameters of the task can be an Object array, this way you can put whatever objects and types you want.
I think process.communicate() would be suitable for output having small size. For larger output it would not be the best approach.
I find that the timeout calls are not reliable enough in real life, particularly for internet explorer , however the following solutions may be of help:
You can timeout the complete test by using @Test(timeout=10000) in the junit test that you are running the selenium process from. This will free up the main thread for executing the other tests, instead of blocking up the whole show. However even this does not work at times.
Anyway by timing out you do not intend to salvage the test case, because timing out even a single operation might leave the entire test sequence in inconsistent state. You might just want to proceed with the other testcases without blocking (or perhaps retry the same test again). In such a case a fool-proof method would be to write a poller that polls processes of Webdriver (eg. IEDriverServer.exe, Phantomjs.exe) running for more than say 10 min and kill them. An example could be found at Automatically identify (and kill) processes with long processing time
The accepted answer suggests to modify the raw data for presentation purposes, something you generally do not want. Imagine you need to make further analyses with these columns and you need the precision you lost with rounding.
You can modify the formatting of individual columns in data frames, in your case:
output = df.to_string(formatters={
'var1': '{:,.2f}'.format,
'var2': '{:,.2f}'.format,
'var3': '{:,.2%}'.format
})
print(output)
For your information '{:,.2%}'.format(0.214)
yields 21.40%
, so no need for multiplying by 100.
You don't have a nice HTML table anymore but a text representation. If you need to stay with HTML use the to_html
function instead.
from IPython.core.display import display, HTML
output = df.to_html(formatters={
'var1': '{:,.2f}'.format,
'var2': '{:,.2f}'.format,
'var3': '{:,.2%}'.format
})
display(HTML(output))
Update
As of pandas 0.17.1, life got easier and we can get a beautiful html table right away:
df.style.format({
'var1': '{:,.2f}'.format,
'var2': '{:,.2f}'.format,
'var3': '{:,.2%}'.format,
})
ORA-12154: TNS:could not resolve the connect identifier specified?
In case the TNS is not defined you can also try this one:
If you are using C#.net 2010
or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:
static string constr = @"Data Source=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
User Id=system ;Password=yourpasswrd";
After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified
then first you have to do restart your system and run your project.
And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:
Oracle Data Provider for .NET 2.0
Oracle Providers for ASP.NET
Oracle Developer Tools for Visual Studio
Oracle Instant Client
And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......
I didn't think it would be that simple! go to this link: https://www.codeproject.com/Articles/18399/Localizing-System-MessageBox
Download the source. Take the MessageBoxManager.cs file, add it to your project. Now just register it once in your code (for example in the Main() method inside your Program.cs file) and it will work every time you call MessageBox.Show():
MessageBoxManager.OK = "Alright";
MessageBoxManager.Yes = "Yep!";
MessageBoxManager.No = "Nope";
MessageBoxManager.Register();
See this answer for the source code here for MessageBoxManager.cs.
See https://github.com/php-pm/php-pm.
Works fine with symphony.
But I'm fighting with it, trying run a slim app
new Date().toLocaleTimeString('it-IT')
The it-IT
locale happens to pad the hour if needed and omits PM or AM 01:33:01
To fix this issue, I had to enable the docker service:
sudo systemctl enable /usr/lib/systemd/system/docker.service
employees.ToList().ForEach(
emp=>
{
collection.AddRange(emp.Departments);
emp.Departments.ToList().ForEach(u=>u.SomeProperty = null);
});
You can do it by a combination of javascript and php:
<div id="cont"></div>
And by the other side;
<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';
setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>
Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)
Sets behave different than dicts, you need to use set operations like issubset():
>>> k
{'ip': '123.123.123.123', 'pw': 'test1234', 'port': 1234, 'debug': True}
>>> set('ip,port,pw'.split(',')).issubset(set(k.keys()))
True
>>> set('ip,port,pw'.split(',')) in set(k.keys())
False
I have a tag bar in my app which uses an UICollectionView
& UICollectionViewFlowLayout
, with one row of cells center aligned.
To get the correct indent, you subtract the total width of all the cells (including spacing) from the width of your UICollectionView
, and divide by two.
[........Collection View.........]
[..Cell..][..Cell..]
[____indent___] / 2
=
[_____][..Cell..][..Cell..][_____]
The problem is this function -
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
is called before...
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
...so you can't iterate over your cells to determine the total width.
Instead you need to calculate the width of each cell again, in my case I use [NSString sizeWithFont: ... ]
as my cell widths are determined by the UILabel itself.
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
CGFloat rightEdge = 0;
CGFloat interItemSpacing = [(UICollectionViewFlowLayout*)collectionViewLayout minimumInteritemSpacing];
for(NSString * tag in _tags)
rightEdge += [tag sizeWithFont:[UIFont systemFontOfSize:14]].width+interItemSpacing;
// To center the inter spacing too
rightEdge -= interSpacing/2;
// Calculate the inset
CGFloat inset = collectionView.frame.size.width-rightEdge;
// Only center align if the inset is greater than 0
// That means that the total width of the cells is less than the width of the collection view and need to be aligned to the center.
// Otherwise let them align left with no indent.
if(inset > 0)
return UIEdgeInsetsMake(0, inset/2, 0, 0);
else
return UIEdgeInsetsMake(0, 0, 0, 0);
}
Try this:
$('.datepicker').datepicker('update', new Date(year,month,day));
It's not unique to WP7--it's present on all .Net objects. It sort of does what you describe, but I would not recommend it as a unique identifier in your apps, as it is not guaranteed to be unique.
The safest place to get the correct width and height without the scrollbars is from the HTML element. Try this:
var width = document.documentElement.clientWidth
var height = document.documentElement.clientHeight
Browser support is pretty decent, with IE 9 and up supporting this. For OLD IE, use one of the many fallbacks mentioned here.
I offer two recommendations:
1) Install the supervisor
package (more verbose instructions here):
sudo apt-get install supervisor
2) Create a config file for your daemon at /etc/supervisor/conf.d/flashpolicyd.conf
:
[program:flashpolicyd]
directory=/path/to/project/root
environment=ENV_VARIABLE=example,OTHER_ENV_VARIABLE=example2
command=python flashpolicyd.py
autostart=true
autorestart=true
3) Restart supervisor
to load your new .conf
supervisorctl update
supervisorctl restart flashpolicyd
[Unit]
Description=My Python daemon
[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/project/main.py
WorkingDirectory=/opt/project/
Environment=API_KEY=123456789
Environment=API_PASS=password
Restart=always
RestartSec=2
[Install]
WantedBy=sysinit.target
Place this file into /etc/systemd/system/my_daemon.service
and enable it using systemctl daemon-reload && systemctl enable my_daemon && systemctl start my_daemon --no-block
.
To view logs:
systemctl status my_daemon
I was looking for a different problem and came across this, so I will add my solution to a related problem: comparing two Maps.
// make a copy of the data
Map<String,String> a = new HashMap<String,String>(actual);
Map<String,String> e = new HashMap<String,String>(expected);
// check *every* expected value
for(Map.Entry<String, String> val : e.entrySet()){
// check for presence
if(!a.containsKey(val.getKey())){
System.out.println(String.format("Did not find expected value: %s", val.getKey()));
}
// check for equality
else{
if(0 != a.get(val.getKey()).compareTo(val.getValue())){
System.out.println(String.format("Value does not match expected: %s", val.getValue()));
}
// we have found the item, so remove it
// from future consideration. While it
// doesn't affect Java Maps, other types of sets
// may contain duplicates, this will flag those
// duplicates.
a.remove(val.getKey());
}
}
// check to see that we did not receive extra values
for(Map.Entry<String,String> val : a.entrySet()){
System.out.println(String.format("Found unexpected value: %s", val.getKey()));
}
It works on the same principle as the other solutions but also compares not only that values are present, but that they contain the same value. Mostly I've used this in accounting software when comparing data from two sources (Employee and Manager entered values match; Customer and Corporate transactions match; ... etc)
You could pass a Class<T>
in.
private void foo(Class<?> cls) {
if (cls == String.class) { ... }
else if (cls == int.class) { ... }
}
private void bar() {
foo(String.class);
}
Update: the OOP way depends on the functional requirement. Best bet would be an interface defining foo()
and two concrete implementations implementing foo()
and then just call foo()
on the implementation you've at hand. Another way may be a Map<Class<?>, Action>
which you could call by actions.get(cls)
. This is easily to be combined with an interface and concrete implementations: actions.get(cls).foo()
.
Seems you are looking for ORDER BY
in DESC
ending order with LIMIT clause:
SELECT
*
FROM
scores
ORDER BY score DESC
LIMIT 10
Of course SELECT *
could seriously affect performance, so use it with caution.
On your project folder, open the command terminal and type
ng -v
it will give you a list of items, in that you will be able to see the angular version. See the screenshot.
Perhaps you need to read about interactive usage of Matplotlib. However, if you are going to build an app, you should be using the API and embedding the figures in the windows of your chosen GUI toolkit (see examples/embedding_in_tk.py
, etc).
Since it takes 2 mins to respond, you can increase the timeout to 3 mins by adding the below code
scGetruntotals.CommandTimeout = 180;
Note : the parameter value is in seconds.
EDIT: added a new example for ggplot2 at the end
See ?plotmath for the different mathematical operations in R
You should be able to use expression without paste. If you use the tilda (~) symbol within the expression function it will assume there is a space between the characters, or you could use the * symbol and it won't put a space between the arguments
Sometimes you will need to change the margins in you're putting superscripts on the y-axis.
par(mar=c(5, 4.3, 4, 2) + 0.1)
plot(1:10, xlab = expression(xLab ~ x^2 ~ m^-2),
ylab = expression(yLab ~ y^2 ~ m^-2),
main="Plot 1")
plot(1:10, xlab = expression(xLab * x^2 * m^-2),
ylab = expression(yLab * y^2 * m^-2),
main="Plot 2")
plot(1:10, xlab = expression(xLab ~ x^2 * m^-2),
ylab = expression(yLab ~ y^2 * m^-2),
main="Plot 3")
Hopefully you can see the differences between plots 1, 2 and 3 with the different uses of the ~ and * symbols. An extra note, you can use other symbols such as plotting the degree symbol for temperatures for or mu, phi. If you want to add a subscript use the square brackets.
plot(1:10, xlab = expression('Your x label' ~ mu[3] * phi),
ylab = expression("Temperature (" * degree * C *")"))
Here is a ggplot example using expression with a nonsense example
require(ggplot2)
Or if you have the pacman library installed you can use p_load to automatically download and load and attach add-on packages
# require(pacman)
# p_load(ggplot2)
data = data.frame(x = 1:10, y = 1:10)
ggplot(data, aes(x,y)) + geom_point() +
xlab(expression(bar(yourUnits) ~ g ~ m^-2 ~ OR ~ integral(f(x)*dx, a,b))) +
ylab(expression("Biomass (g per" ~ m^3 *")")) + theme_bw()
use "not" in if-else
x = input()
if not x:
print("Value is not entered")
else:
print("Value is entered")
I was having the same problem. Turned out I was missing the ./Views/Web.config
file, because I created the project from an empty ASP.NET application instead of using an ASP.NET MVC template.
For ASP.NET MVC 5, a vanilla ./Views/Web.config
file contains the following:
<?xml version="1.0"?>
<!-- https://stackoverflow.com/a/19899269/178082 -->
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.web>
<httpHandlers>
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
<!--
Enabling request validation in view pages would cause validation to occur
after the input has already been processed by the controller. By default
MVC performs request validation before a controller processes the input.
To change this behavior apply the ValidateInputAttribute to a
controller or action.
-->
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
Adding a ./Views/Web.config
file containing this content fixed this problem for me.
String aString = "This will return the letter t";
System.out.println(aString.charAt(aString.length() - 1));
Output should be:
t
Happy coding!