I am adding this A because I got caught with a bizarre version of this which really had me scratching my head for about a hour until I spotted the root cause. My load was failing because of multiple repeats of this format
<path>/linit.o:(.rodata1.libs+0x50): multiple definition of `lua_lib_BASE'
<path>/linit.o:(.rodata1.libs+0x50): first defined here
I turned out to be a bug in my Makefile magic where I had a list of C files and using vpath etc., so the compiles would pick them up from the correct directory in hierarchy. However one C file was repeated in the list, at the end of one line and the start of the next so the gcc load generated by the make had the .o
file twice on the command line. Durrrrh. The multiple definitions were from multiple occurances of the same file. The linker ignored duplicates apart from static initialisers!
I've come across a good article about designing Android apps UI for different screen resolutions, and I'd like to leave it here just for somebody searching in this area. Yes, I know that it's somehow described in Google docs (and mentioned in the posts above), I read that but it was not good for me (yeah, I may be too stupid)). It remained unclear for me how to design layouts capable to handle different screen size. I hate DP concept and so on, when I need to implement a "flexible" UI layout for different screens. (Hey iOS developers - yes, you're right it's Storyboard concept).
Android has not bad UI concept, but lacks iOS Storyboard features, unfortunately. Designing flexible UI in Android is not easy thing (at the best).
Here goes the article that helped me to understand what to do in Android to make layouts for different screen sizes:
JMSTUDIO Blog :- Decide Android App Screen Size
How to Design UI for Android Apps for Different Screen Size
To design an app UI for different screen sizes, our initial design has to meet a minimum required space for each screen size. Android defines a minimum size (in dp) for each generalized screen type. Here is an Android screen size guideline. When we get the screen size in dp, it is not enough for us to design the Android app UI. For each screen size, we need to prepare graphics and bitmap images for each density. Here is an Android screen density guideline.
For easy calculation, we can follow the 3:4:6:8 scaling ratio between the four generalized densities. If we create a 36×36 pixel picture for ldpi device, the rest densities pictures size will be 48×48 for mdpi, 72×72 for hdpi, and 96×96 for xhdpi.
How to Design Android Apps UI in Photoshop
Many designers have problems for designing Android app UI in photoshop or other pixel based graphic design tools because of density-independent unit, dp. Designers don’t know how to map dp to pixel. Google also doesn’t give a clear Android UI design guide for them, though they give a basic formula for dp and pixel translation.
As Android’s definition, 1pd equal to 1px under 160 dpi device (mdpi). So we want to design an Android app for xlarge Android device with mdpi density, we can define our UI size in pixel as 960 pixel in width and 720px in height; Follow the same mapping rule, we can get following Android App screen size UI design guideline:
ADDED: If you interested in "flexible" UI too, have a look at this library: An Android SDK that provides a new size unit - sdp (scalable dp). This size unit scales with the screen size (this also mentioned in an answer here, about SDP
library)
ADDED2 Google has finally understood usefulness of iOS Storeboard UI concept, and here goes ConstraintLayout
for Android world: Build a Responsive UI with ConstraintLayout
An approach without ant-contrib is suggested by Tassilo Horn (the original target is here)
Basicly, as there is no extension of <java> (yet?) in the same way that <apply> extends <exec>, he suggests to use <apply> (which can of course also run a java programm in a command line)
Here some examples:
<apply executable="java">
<arg value="-cp"/>
<arg pathref="classpath"/>
<arg value="-f"/>
<srcfile/>
<arg line="-o ${output.dir}"/>
<fileset dir="${input.dir}" includes="*.txt"/>
</apply>
Simply remove the virtual environment from the system.There's no special command for it
rm -rf venv
Assuming I understand what you mean:
If your UserControl
is in a library you can add this to you Toolbox using
Toolbox -> right click -> Choose Items -> Browse
Select your assembly with the UserControl
.
If the UserControl
is part of your project you only need to build the entire solution. After that, your UserControl
should appear in the toolbox.
In general, it is not possible to add a Control from Solution Explorer, only from the Toolbox.
From the Google Font Directory examples:
@font-face {
font-family: 'Tangerine';
font-style: normal;
font-weight: normal;
src: local('Tangerine'), url('http://example.com/tangerine.ttf') format('truetype');
}
body {
font-family: 'Tangerine', serif;
font-size: 48px;
}
This works cross browser with .ttf, I believe it may work with .otf. (Wikipedia says .otf is mostly backwards compatible with .ttf) If not, you can convert the .otf to .ttf
Here are some good sites:
Good primer:
Other Info:
Try putting the following in the environment variables
for the scheme under run(debug)
OS_ACTIVITY_MODE = disable
As of Django 1.2, you can use exists()
:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists
if some_queryset.filter(pk=entity_id).exists():
print("Entry contained in queryset")
this did it for me. you can vary the options for the output format to Base64.Default whatsoever.
// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);
This supplemental answer shows the effect of changing the line spacing.
You can set the multiplier and/or extra spacing with
textView.setLineSpacing(float add, float mult)
Or you can get the values with
int lineHeight = textView.getLineHeight();
float add = tvSampleText.getLineSpacingExtra(); // API 16+
float mult = tvSampleText.getLineSpacingMultiplier(); // API 16+
where the formula is
lineHeight = fontMetricsLineHeight * mult + add
The default multiplier is 1
and the default extra spacing is 0
.
//do the edit in your javascript
$('.signinform').submit(function() {
$(this).ajaxSubmit({
type : "POST",
//set the data type
dataType:'json',
url: 'index.php/user/signin', // target element(s) to be updated with server response
cache : false,
//check this in Firefox browser
success : function(response){ console.log(response); alert(response)},
error: onFailRegistered
});
return false;
});
//controller function
public function signin() {
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
//add the header here
header('Content-Type: application/json');
echo json_encode( $arr );
}
Select extract rows from the relation with some condition and Project extract particular number of attribute/column from the relation with or without some condition.
I faced to this problem a lot when developing my company's website using WordPress. Finally I found that it happened because me and my colleague update the website at the same time as well as we installed and activated many plugins that we did not use them. The solution for me was we update the website in different time and deactivated and uninstalled those plugins.
Here is a more involved example of where extends is allowed and possibly what you want:
public class A<T1 extends Comparable<T1>>
What you want to do is separate the content of the table from the header of the table.
You want only the <th>
elements to be scrolled.
You can easily define this separation in HTML with the <tbody>
and the <thead>
elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block
. This way <thead>
and <tbody>
are separated.
table tbody, table thead
{
display: block;
}
Now you can set the scroll to the body of the table:
table tbody
{
overflow: auto;
height: 100px;
}
And last, because the <thead>
doesn't share the same width as the body anymore, you should set a static width to the header of the table:
th
{
width: 72px;
}
You should also set a static width for <td>
. This solves the issue of the unaligned columns.
td
{
width: 72px;
}
<tr>
element, that includes the header row:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
I hope this is what you meant.
Addendum
If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; }
table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
From the JDK source:
static <T> Function<T, T> identity() {
return t -> t;
}
So, no, as long as it is syntactically correct.
This is just a possible scenario which happened to me. Well if it helps someone then great: I wrote a complicated app which somewhere along the code I used a function to clear all textboxes values before showing them. Sometime later I tried to set a textbox value using jquery val('value') but I did'nt notice that right after that I invoked the ClearAllInputs method.. so, this could also happen.
Stop MySQL sudo service mysql stop
Make MySQL service directory. sudo mkdir /var/run/mysqld
Give MySQL user permission to write to the service directory. sudo chown mysql: /var/run/mysqld
Start MySQL manually, without permission checks or networking. sudo mysqld_safe --skip-grant-tables --skip-networking &
5.Log in without a password. mysql -uroot mysql
6.Update the password for the root user.
UPDATE mysql.user SET authentication_string=PASSWORD('YOURNEWPASSWORD'), plugin='mysql_native_password' WHERE User='root' AND Host='%'; EXIT;
Turn off MySQL. sudo mysqladmin -S /var/run/mysqld/mysqld.sock shutdown
Start the MySQL service normally. sudo service mysql start
There is no specific event for capturing browser close event.
You can only capture on unload of the current page.
By this method, it will be effected while refreshing / navigating the current page.
Even calculating of X Y postion of the mouse event doesn't give you good result.
The answer by @Federico Giorgi was a very good answer. It helpt me. Therefore, I did the following, in order to produce multiple lines in the same plot from the data of a single dataset, I used a for loop. Legend can be added as well.
plot(tab[,1],type="b",col="red",lty=1,lwd=2, ylim=c( min( tab, na.rm=T ),max( tab, na.rm=T ) ) )
for( i in 1:length( tab )) { [enter image description here][1]
lines(tab[,i],type="b",col=i,lty=1,lwd=2)
}
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))
I also faced this issue. My Operating system is Ubuntu 18.04 and my PHP version is PHP 7.2.
Here's how I solved it:
Install Simplexml on your Ubuntu Server:
sudo apt-get install php7.2-simplexml
Restart Apache Server
sudo systemctl restart apache2
That's all.
I hope this helps
Just setting json
option to true
, the body will contain the parsed json:
request({
url: 'http://...',
json: true
}, function(error, response, body) {
console.log(body);
});
free
is not enough, free
just marks the memory as unused, the struct data will be there until overwriting. For safety, set the pointer to NULL
after free
.
Ex:
if (testPerson) {
free(testPerson);
testPerson = NULL;
}
struct
is similar like an array, it is a block of memory. You can access to struct member via its offset. The first struct's member is placed at offset 0
so the address of first struct's member is same as the address of struct.
If you think map()
as an iteration(one level for
loop), flatmap()
is a two-level iteration(like a nested for
loop). (Enter each iterated element foo
, and do foo.getBarList()
and iterate in that barList
again)
map()
: take a stream, do something to every element, collect the single result of every process, output another stream. The definition of "do something function" is implicit. If the processment of any element results in null
, null
is used to compose the final stream. So, the number of elements in the resulting stream will be equal to number of input stream.
flatmap()
: take a stream of elements/streams and a function(explicit definition), apply the function to each element of each stream, and collect all the intermediate resulting stream to be a greater stream("flattening"). If the processment of any element results in null
, empty stream is provided to the final step of "flattening". The number of elements in the resulting stream, is the total of all participating elements in all inputs, if the input is several streams.
You can simply use the toCharArray()
to convert a string to char array:
Scanner s=new Scanner(System.in);
System.out.print("Enter some String:");
String str=s.nextLine();
char a[]=str.toCharArray();
The easiest way would be using Substring
string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);
Using the overload with one int
as I put would get the substring
of a string
, starting from the index int
. In your case being str.Length - 3
, since you want to get the last three chars.
When using Object.keys
, the following works:
Object.keys(this)
.forEach(key => {
console.log(this[key as keyof MyClass]);
});
The IF statement has these forms in PL/SQL
:
IF THEN
IF THEN ELSE
IF THEN ELSIF
You have used elseif
which in terms of PL/SQL is wrong. That need to be replaced with ELSIF
.
So your code should appear like this.
declare
var_number number;
begin
var_number := 10;
if var_number > 100 then
dbms_output.put_line(var_number ||' is greater than 100');
--elseif should be replaced with elsif
elsif var_number < 100 then
dbms_output.put_line(var_number ||' is less than 100');
else
dbms_output.put_line(var_number ||' is equal to 100');
end if;
end;
If you output to html or an html e-mail you will need to use <br>
or <br />
instead of \n
.
If it's just a text e-mail: Are you perhaps using '
instead of "
? Although then your values would not be inserted either...
First make sure adb command is executable by setting PATH to android sdk platform-tools:
export PATH=/Users/espireinfolabs/Desktop/soft/android-sdk-mac_x86/platform-tools:$PATH
then run:
adb shell logcat > log.txt
OR first move to adb platform-tools:
cd /Users/user/Android/Tools/android-sdk-macosx/platform-tools
then run
./adb shell logcat > log.txt
I use this method in my css file
@font-face {
font-family: FontName1;
src: url("fontname1.eot"); /* IE */
src: local('FontName1'), url('fontname1.ttf') format('truetype'); /* others */
}
@font-face {
font-family: FontName2;
src: url("fontname1.eot"); /* IE */
src: local('FontName2'), url('fontname2.ttf') format('truetype'); /* others */
}
@font-face {
font-family: FontName3;
src: url("fontname1.eot"); /* IE */
src: local('FontName3'), url('fontname3.ttf') format('truetype'); /* others */
}
This is my solution:
import pandas as pd
df = pd.read_excel('dic.xlsx')
df_T = df.set_index('id').T
dic = df_T.to_dict('records')
print(dic)
insert image zh
-while we insert image in database using insert query
$Image = $_FILES['Image']['name'];
if(!$Image)
{
$Image="";
}
else
{
$file_path = 'upload/';
$file_path = $file_path . basename( $_FILES['Image']['name']);
if(move_uploaded_file($_FILES['Image']['tmp_name'], $file_path))
{
}
}
If user wants to search for the word in given text file.
fopen = open('logfile.txt',mode='r+')
fread = fopen.readlines()
x = input("Enter the search string: ")
for line in fread:
if x in line:
print(line)
Found the solution after some searching.
You need to add a <meta>
tag in your <head>
containing name="theme-color"
, with your HEX code as the content value. For example:
<meta name="theme-color" content="#999999" />
If the android device has native dark-mode
enabled, then this meta
tag is ignored.
Chrome for Android does not use the color on devices with native
dark-mode
enabled.
This worked on Ubuntu 17.04
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
sudo apt-get update
sudo apt-get install -y mongodb-org
If you see a failure like:
dpkg: error processing archive /var/cache/apt/archives/mongodb-org-tools_3.6.2_amd64.deb (--unpack):
trying to overwrite '/usr/bin/bsondump', which is also in package mongo-tools 3.2.11-1
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Then run this command:
echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" |
sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
and
sudo apt update
sudo apt install mongodb-org
References:
I use pyDev with Eclipse really good, set break points, step into code, view values on any objects and variables, try it.
If you want to fit other type of models, like a dose-response curve using logistic models you would also need to create more data points with the function predict if you want to have a smoother regression line:
fit: your fit of a logistic regression curve
#Create a range of doses:
mm <- data.frame(DOSE = seq(0, max(data$DOSE), length.out = 100))
#Create a new data frame for ggplot using predict and your range of new
#doses:
fit.ggplot=data.frame(y=predict(fit, newdata=mm),x=mm$DOSE)
ggplot(data=data,aes(x=log10(DOSE),y=log(viability)))+geom_point()+
geom_line(data=fit.ggplot,aes(x=log10(x),y=log(y)))
Use ByteArrayInputStream
:
InputStream is = new ByteArrayInputStream(decodedBytes);
It looks like you're writing PHP, in which case you want:
<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>
Notice that the ('us'=>'United', 'ca'=>'canada')
needs to be a parameter to the array function in PHP.
Most programming languages that support associative arrays or dictionaries use arr['key']
to retrieve the item specified by 'key'
For instance:
ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
=> {"us"=>"USA", "ca"=>"Canada"}
ruby-1.9.1-p378 > h['ca']
=> "Canada"
>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'
#
class P
{
static void Main()
{
var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
System.Console.WriteLine(d["ca"]);
}
}
t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables
The easiest way to generate QR codes with PHP is the phpqrcode library.
Dominc has the right idea, but put the calculation on the other side of the expression.
SELECT * FROM my_table WHERE endTime < DATE_SUB(CONVERT_TZ(NOW(), @@global.time_zone, 'GMT'), INTERVAL 30 MINUTE)
This has the advantage that you're doing the 30 minute calculation once instead of on every row. That also means MySQL can use the index on that column. Both of thse give you a speedup.
You have to duplicate the repo
You can see this doc (from github)
To create a duplicate of a repository without forking, you need to run a special clone command against the original repository and mirror-push to the new one.
In the following cases, the repository you're trying to push to--like exampleuser/new-repository or exampleuser/mirrored--should already exist on GitHub. See "Creating a new repository" for more information.
Mirroring a repository
To make an exact duplicate, you need to perform both a bare-clone and a mirror-push.
Open up the command line, and type these commands:
$ git clone --bare https://github.com/exampleuser/old-repository.git # Make a bare clone of the repository $ cd old-repository.git $ git push --mirror https://github.com/exampleuser/new-repository.git # Mirror-push to the new repository $ cd .. $ rm -rf old-repository.git # Remove our temporary local repository
If you want to mirror a repository in another location, including getting updates from the original, you can clone a mirror and periodically push the changes.
$ git clone --mirror https://github.com/exampleuser/repository-to-mirror.git # Make a bare mirrored clone of the repository $ cd repository-to-mirror.git $ git remote set-url --push origin https://github.com/exampleuser/mirrored # Set the push location to your mirror
As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references will be overwritten each time you fetch, so it will always be the same as the original repository. Setting the URL for pushes simplifies pushing to your mirror. To update your mirror, fetch updates and push, which could be automated by running a cron job.
$ git fetch -p origin $ git push --mirror
For those looking for less complicated solution. I actually find this one more simplisitic solution that will do similar job:
import pandas as pd
a = ['a','b','c']
df = pd.DataFrame({'a': a})
df= df.set_index('a').T
df.to_csv('list_a.csv', index=False)
Hope this helps as well.
Your log4j.properties file should be on the root level of your capitolo2.ear (not in META-INF), that is, here:
MyProject
¦ build.xml
¦
+---build
¦ ¦ capitolo2-ejb.jar
¦ ¦ capitolo2-war.war
¦ ¦ JBoss4.dpf
¦ ¦ log4j.properties
I used
diff -rqyl folder1 folder2 --exclude=node_modules
in my nodejs apps.
This is what I use, and it works for me:
//variables
String subject = "Whatever subject you want";
String body = "Whatever text you want to put in the body";
String intentType = "text/html";
String mailToParse = "mailto:";
//start Intent
Intent variableName = new Intent(Intent.ACTION_SENDTO);
variableName.setType(intentType);
variableName.setData(Uri.parse(mailToParse));
variableName.putExtra(Intent.EXTRA_SUBJECT, subject);
variableName.putExtra(Intent.EXTRA_TEXT, body);
startActivity(variableName);
This will also let the user choose their preferred email app. The only thing this does not allow you to do is to set the recipient's email address.
If you are only interested in the packages installed globally without the full TREE then:
npm -g ls --depth=0
or locally (omit -g) :
npm ls --depth=0
I got into this state recently. After resolving conflicts during a rebase, I committed my changes, rather than running git rebase --continue
. This yields the same messages you saw when you ran your git status
and git rebase --continue
commands. I resolved the issue by running git rebase --abort
, and then re-running the rebase. One could likely also skip the rebase, but I wasn't sure what state that would leave me in.
$ git rebase --continue
Applying: <commit message>
No changes - did you forget to use 'git add'?
If there is nothing left to stage, chances are that something else
already introduced the same changes; you might want to skip this patch.
When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".
$ git status
rebase in progress; onto 4df0775
You are currently rebasing branch '<local-branch-name>' on '4df0775'.
(all conflicts fixed: run "git rebase --continue")
nothing to commit, working directory clean
Calendar.getInstance().get(Calendar.MILLISECOND);
In JQuery you can call
$("form:first").trigger("submit")
Don't know if that is much better. I think form.submit(); is pretty universal.
You have found the root cause. Alternately do like this:
ser.write(bytes(b'your_commands'))
Wrap the 'child' function(s) being passed as/with arguments within function wrappers to prevent them being evaluated when the 'parent' function is called.
function outcome(){
return false;
}
function process(callbackSuccess, callbackFailure){
if ( outcome() )
callbackSuccess();
else
callbackFailure();
}
process(function(){alert("OKAY");},function(){alert("OOPS");})
1) When to use include directive ?
To prevent duplication of same output logic across multiple jsp's of the web app ,include mechanism is used ie.,to promote the re-usability of presentation logic include directive is used
<%@ include file="abc.jsp" %>
when the above instruction is received by the jsp engine,it retrieves the source code of the abc.jsp and copy's the same inline in the current jsp. After copying translation is performed for the current page
Simply saying it is static instruction to jsp engine ie., whole source code of "abc.jsp" is copied into the current page
2) When to use include action ?
include tag doesn't include the source code of the included page into the current page instead the output generated at run time by the included page is included into the current page response
include tag functionality is similar to that of include mechanism of request dispatcher of servlet programming
include tag is run-time instruction to jsp engine ie., rather copying whole code into current page a method call is made to "abc.jsp" from current page
There is pretty simple and easy solution to this problem) Just few simple steps that will transform your ugly Eclipse into fully darked beast)
example of full darked Eclipse
No heavy work or manually editing files required!
At least this works with the last Eclipse (Mars 2) on Ubuntu 14.04 (though i think such process should work on all OS's)
So:
Download some dark GTK theme
for example, you can grab few from http://www.noobslab.com/
To apply your newly installed theme you will need Unity tweak tool
sudo apt-get install unity-tweak-tool
sudo apt-get install unity-webapps-service
Launch Unity tweak - Appearance - Theme - apply your dark theme
Open Eclipse; in preferences choose GTK theme
In Eclipse, open Marketplace and install Color Theme - you will be able to change editor background and highlight colors to match your dark theme
Close Eclipse
Go to Eclipe folder:
../Eclipse/plugins/org.eclipse.ui.themes_WHATEVER_NUMBER_HERE/
in that folder rename or delete 'css' folder
Open and enjoy fully darked Eclipse!
PS: install a few dark themes and try which will suit you more
Hope this will help you .
Here is Html code:-
<body>
<div ng-controller="MyController" class="container">
<h1>Modal example</h1>
<button ng-click="open()" class="btn btn-primary">Test Modal</button>
<modal title="Login form" visible="showModal">
<form role="form">
</form>
</modal>
</div>
</body>
AngularJs code:-
var mymodal = angular.module('mymodal', []);
mymodal.controller('MyController', function ($scope) {
$scope.showModal = false;
$scope.open = function(){
$scope.showModal = !$scope.showModal;
};
});
mymodal.directive('modal', function () {
return {
template: '<div class="modal fade">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
'<h4 class="modal-title">{{ title }}</h4>' +
'</div>' +
'<div class="modal-body" ng-transclude></div>' +
'</div>' +
'</div>' +
'</div>',
restrict: 'E',
transclude: true,
replace:true,
scope:true,
link: function postLink(scope, element, attrs) {
scope.title = attrs.title;
scope.$watch(attrs.visible, function(value){
if(value == true)
$(element).modal('show');
else
$(element).modal('hide');
});
$(element).on('shown.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
});
}
};
});
Check this--jsfiddle
I think this is no longer an issue in Chrome but just in case. I wrote this jQuery script to inspect the DOM when I move around with the TAB key.
If changed to use 'mouseover', would look like this:
$("body *").on('mouseover', function(event) {
console.log(event.target);
inspect(event.target);
event.stopPropagation();
});
You can easily modify it to remove the event handler whenever you click or do something on an element you want to stop at.
Check your php error log which might be a separate file from your apache error log.
Find it by going to phpinfo()
and check for error_log attribute.
If it is not set. Set it: https://stackoverflow.com/a/12835262/445131
Maybe your post_max_size is too small for what you're trying to post, or one of the other max memory settings is too low.
a bit of a cheat, but it works:
HTML:
<ol type="A" style="font-weight: bold;">
<li><span>Text</span></li>
<li><span>More text</span></li>
</ol>
CSS:
li span { font-weight: normal; }
Try this when nothing as mentioned above is working for you.
git config credential.helper 'cache --timeout=30'
this will remove the cache every 3sec and will ask for username and password.You can re-run the command with increased timeout values.
Another solution for this;
const isClockwise = (vertices=[]) => {
const len = vertices.length;
const sum = vertices.map(({x, y}, index) => {
let nextIndex = index + 1;
if (nextIndex === len) nextIndex = 0;
return {
x1: x,
x2: vertices[nextIndex].x,
y1: x,
y2: vertices[nextIndex].x
}
}).map(({ x1, x2, y1, y2}) => ((x2 - x1) * (y1 + y2))).reduce((a, b) => a + b);
if (sum > -1) return true;
if (sum < 0) return false;
}
Take all the vertices as an array like this;
const vertices = [{x: 5, y: 0}, {x: 6, y: 4}, {x: 4, y: 5}, {x: 1, y: 5}, {x: 1, y: 0}];
isClockwise(vertices);
I've just been playing with this and discovered a rather odd result. Say you have public properties on your class in C# like this:
public class Customer
{
public string contact_name;
public string company_name;
}
then you must do the JSON.stringify trick as suggested by Shyju and call it like this:
var customer = {contact_name :"Scott",company_name:"HP"};
$.ajax({
type: "POST",
data :JSON.stringify(customer),
url: "api/Customer",
contentType: "application/json"
});
However, if you define getters and setters on your class like this:
public class Customer
{
public string contact_name { get; set; }
public string company_name { get; set; }
}
then you can call it much more simply:
$.ajax({
type: "POST",
data :customer,
url: "api/Customer"
});
This uses the HTTP header:
Content-Type:application/x-www-form-urlencoded
I'm not quite sure what's happening here but it looks like a bug (feature?) in the framework. Presumably the different binding methods are calling different "adapters", and while the adapter for application/json one works with public properties, the one for form encoded data doesn't.
I have no idea which would be considered best practice though.
Starting with EF6.1 you can use Interceptors to register a database logger. See chapters "Interceptors" and "Logging Database Operations" to a File here
<interceptors>
<interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">
<parameters>
<parameter value="C:\Temp\LogOutput.txt"/>
<parameter value="true" type="System.Boolean"/>
</parameters>
</interceptor>
</interceptors>
you can use display:flex
to do this : http://codepen.io/anon/pen/yCKuz
html,body {
height:100%;
width:100%;
margin:0;
}
body {
display:flex;
}
form {
margin:auto;/* nice thing of auto margin if display:flex; it center both horizontal and vertical :) */
}
or display:table
http://codepen.io/anon/pen/LACnF/
body, html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
display:table;
}
body {
display:table-cell;
vertical-align:middle;
}
form {
display:table;/* shrinks to fit content */
margin:auto;
}
I have created a javascript function that looks if he has enough space on the right side. If it has he will show it on the right side, else he will display it on the left side
Tested in:
Javascript:
$(document).ready(function(){
//little fix for the poisition.
var newPos = $(".fixed-menuprofile .dropdown-submenu").offset().left - $(this).width();
$(".fixed-menuprofile .dropdown-submenu").find('ul').offset({ "left": newPos });
$(".fixed-menu .dropdown-submenu").mouseover(function() {
var submenuPos = $(this).offset().left + 325;
var windowPos = $(window).width();
var oldPos = $(this).offset().left + $(this).width();
var newPos = $(this).offset().left - $(this).width();
if( submenuPos > windowPos ){
$(this).find('ul').offset({ "left": newPos });
} else {
$(this).find('ul').offset({ "left": oldPos });
}
});
});
because I don't want to add this fix on every menu items I created a new class on it. place the fixed-menu on the ul:
<ul class="dropdown-menu fixed-menu">
I hope this works out for you.
ps. little bug in safari and chrome, first hover will place it to mutch to the left will update this post if I fixed it.
Try this after curl_exec to see what's the problem:
print curl_error($ch);
If it's print something like 'malformed' then check your URL format.
When you use scp you have to tell the host name and ip address from where you want to copy the file. For instance, if you are at the remote host and you want to transfer the file to your pc you may use something like this:
scp -P[portnumber] myfile_at_remote_host [user]@[your_ip_address]:/your/path/
Example:
scp -P22 table [email protected]:/home/me/Desktop/
On the other hand, if you are at your are actually on your machine you may use something like this:
scp -P[portnumber] [remote_login]@[remote's_ip_address]:/remote/path/myfile_at_remote_host /your/path/
Example:
scp -P22 [fake_user]@222.222.222.222:/remote/path/table /home/me/Desktop/
I am working on DOM Keyboard Event Level 3 polyfill . In latest browsers or with this polyfill you can do something like this:
element.addEventListener("keydown", function(e){ console.log(e.key, e.char, e.keyCode) })
var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : "Q", char : "Q", shiftKey : true});
element.dispatchEvent(e);
//If you need legacy property "keyCode"
// Note: In some browsers you can't overwrite "keyCode" property. (At least in Safari)
delete e.keyCode;
Object.defineProperty(e, "keyCode", {"value" : 666})
UPDATE:
Now my polyfill supports legacy properties "keyCode", "charCode" and "which"
var e = new KeyboardEvent("keydown", {
bubbles : true,
cancelable : true,
char : "Q",
key : "q",
shiftKey : true,
keyCode : 81
});
Examples here
Additionally here is cross-browser initKeyboardEvent separately from my polyfill: (gist)
Polyfill demo
If the DC is Win2k3 SP2 or above, you can use something like:
(&(objectCategory=user)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com))
to get the nested group membership.
Source: https://ldapwiki.com/wiki/Active%20Directory%20Group%20Related%20Searches
i think i am having a bit of confusion here. :) But seems no one else have ..
Are you asking which one to use in this scenario? If Yes then And is the correct answer.
If you are asking about how the operators are working, then
In php both AND, && and OR, || will work in the same way. If you are new in programming and php is one of your first languages them i suggest using AND and OR, because it increases readability and reduces confusion when you check back. But if you are familiar with any other languages already then you might already have familiarized the && and || operators.
Clustered indexes physically order the data on the disk. This means no extra data is needed for the index, but there can be only one clustered index (obviously). Accessing data using a clustered index is fastest.
All other indexes must be non-clustered. A non-clustered index has a duplicate of the data from the indexed columns kept ordered together with pointers to the actual data rows (pointers to the clustered index if there is one). This means that accessing data through a non-clustered index has to go through an extra layer of indirection. However if you select only the data that's available in the indexed columns you can get the data back directly from the duplicated index data (that's why it's a good idea to SELECT only the columns that you need and not use *)
Personally, I think one of the answers above can be modified to check if the array has contents:
if UBound(ar) > LBound(ar) Then
This handles negative number references and takes less time than some of the other options.
When you export you use the compatibility system set to MYSQL40
. Worked for me.
Why not just generate a whitespace string dynamically to insert into the statement.
So if you want them all to start on the 50th character...
String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);
Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder
class too which is more efficient.
Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.
Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload
If you'd like to track only failed logins, you can use the SQL Server Audit feature (available in SQL Server 2008 and above). You will need to add the SQL server instance you want to audit, and check the failed login operation to audit.
Note: tracking failed logins via SQL Server Audit has its disadvantages. For example - it doesn't provide the names of client applications used.
If you want to audit a client application name along with each failed login, you can use an Extended Events session.
To get you started, I recommend reading this article: http://www.sqlshack.com/using-extended-events-review-sql-server-failed-logins/
If above solutions are not working for your TextView then this will definitely work:
1. add this style
<style name="ClickableView">
<item name="colorControlHighlight">@android:color/white</item>
<item name="android:background">?selectableItemBackground</item>
</style>
2. use it just by
android:theme="@style/ClickableView"
def _col_seq_set(df, col_list, seq_list):
''' set dataframe 'df' col_list's sequence by seq_list '''
col_not_in_col_list = [x for x in list(df.columns) if x not in col_list]
for i in range(len(col_list)):
col_not_in_col_list.insert(seq_list[i], col_list[i])
return df[col_not_in_col_list]
DataFrame.col_seq_set = _col_seq_set
The information schema views and pg_typeof() return incomplete type information. Of these answers, psql
gives the most precise type information. (The OP might not need such precise information, but should know the limitations.)
create domain test_domain as varchar(15);
create table test (
test_id test_domain,
test_vc varchar(15),
test_n numeric(15, 3),
big_n bigint,
ip_addr inet
);
Using psql
and \d public.test
correctly shows the use of the data type test_domain
, the length of varchar(n) columns, and the precision and scale of numeric(p, s) columns.
sandbox=# \d public.test Table "public.test" Column | Type | Modifiers ---------+-----------------------+----------- test_id | test_domain | test_vc | character varying(15) | test_n | numeric(15,3) | big_n | bigint | ip_addr | inet |
This query against an information_schema view does not show the use of test_domain
at all. It also doesn't report the details of varchar(n) and numeric(p, s) columns.
select column_name, data_type
from information_schema.columns
where table_catalog = 'sandbox'
and table_schema = 'public'
and table_name = 'test';
column_name | data_type -------------+------------------- test_id | character varying test_vc | character varying test_n | numeric big_n | bigint ip_addr | inet
You might be able to get all that information by joining other information_schema views, or by querying the system tables directly. psql -E
might help with that.
The function pg_typeof()
correctly shows the use of test_domain
, but doesn't report the details of varchar(n) and numeric(p, s) columns.
select pg_typeof(test_id) as test_id,
pg_typeof(test_vc) as test_vc,
pg_typeof(test_n) as test_n,
pg_typeof(big_n) as big_n,
pg_typeof(ip_addr) as ip_addr
from test;
test_id | test_vc | test_n | big_n | ip_addr -------------+-------------------+---------+--------+--------- test_domain | character varying | numeric | bigint | inet
Your compiled classes may need to be recompiled from the source with the new jars.
Try running "mvn clean" and then rebuild
I've not noticed any difference in startup time between the 2, but clocked a very minimal improvement in application performance with "-server" (Solaris server, everyone using SunRays to run the app). That was under 1.5.
This fixed me
var width = window.innerWidth;
var height = window.innerHeight;
They're apples and oranges. You don't want to compare them. They're two different things. AngularJs has already jQuery lite built in which allows you to perform basic DOM manipulation without even including the full blown jQuery version.
jQuery is all about DOM manipulation. It solves all the cross browser pain otherwise you will have to deal with but it's not a framework that allows you to divide your app into components like AngularJS.
A nice thing about AngularJs is that it allows you to separate/isolate the DOM manipulation in the directives. There are built-in directives ready for you to use such as ng-click. You can create your own custom directives that will contain all your view logic or DOM manipulation so you don't end up mingle DOM manipulation code in the controllers or services that should take care of the business logic.
Angular breaks down your app into - Controllers - Services - Views - etc.
and there is one more thing, that's the directive. It's an attribute you can attach to any DOM element and you can go nuts with jQuery within it without worrying about your jQuery ever conflicts with AngularJs components or messes up with its architecture.
I heard from a meetup I attended, one of the founders of Angular said they worked really hard to separate out the DOM manipulation so do not try to include them back in.
clock() has a often a pretty lousy resolution. If you want to measure time at the millisecond level, one alternative is to use clock_gettime(), as explained in this question.
(Remember that you need to link with -lrt on Linux).
You need to create a new Font
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
I had to add !important
to get it to work. I also made my own class button-primary-override
.
.button-primary-override:hover,
.button-primary-override:active,
.button-primary-override:focus,
.button-primary-override:visited{
background-color: #42A5F5 !important;
border-color: #42A5F5 !important;
background-image: none !important;
border: 0 !important;
}
This sets the scrollbar width:
::-webkit-scrollbar {
width: 8px; // for vertical scroll bar
height: 8px; // for horizontal scroll bar
}
// for Firefox add this class as well
.thin_scroll{
scrollbar-width: thin; // auto | thin | none | <length>;
}
I would recommend using jQuery with this function:
$(document).ready(function(){
$('#about').addClass('expand');
});
This will add the expand class to an element with id of about when the dom is ready on page load.
One of the easy ways is not to store the output in a variable, but directly iterate over it with a while/read loop.
Something like:
grep xyz abc.txt | while read -r line ; do
echo "Processing $line"
# your code goes here
done
There are variations on this scheme depending on exactly what you're after.
If you need to change variables inside the loop (and have that change be visible outside of it), you can use process substitution as stated in fedorqui's answer:
while read -r line ; do
echo "Processing $line"
# your code goes here
done < <(grep xyz abc.txt)
A simple definition: A web service is a function that can be accessed by other programs over the web (HTTP).
For example, when you create a website in PHP that outputs HTML, its target is the browser and by extension the human reading the page in the browser. A web service is not targeted at humans but rather at other programs.
So your PHP site that generates a random integer could be a web service if it outputs the integer in a format that may be consumed by another program. It might be in an XML format or another format, as long as other programs can understand the output.
The full definition is obviously more complex but you asked for plain English.
if you have two application like (your app, phpmyadmin) just disable APC extension Hope that fix that issue it's worked with me
I'm sad to say: We are sh*t out of luck on this one.
I'd like to refer you to the author of WhichBrowser: Everybody lies.
Basically, no browser is being honest. No matter if you use Chrome or IE, they both will tell you that they are "Mozilla Netscape" with Gecko and Safari support. Try it yourself on any of the fiddles flying around in this thread:
or any other... Try it with Chrome (which might still succeed), then try it with a recent version of IE, and you will cry. Of course, there are heuristics, to get it all right, but it will be tedious to grasp all the edge cases, and they will very likely not work anymore in a year's time.
Take your code, for example:
<div id="example"></div>
<script type="text/javascript">
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
</script>
Chrome says:
Browser CodeName: Mozilla
Browser Name: Netscape
Browser Version: 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
Cookies Enabled: true
Platform: Win32
User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
IE says:
Browser CodeName: Mozilla
Browser Name: Netscape
Browser Version: 5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko
Cookies Enabled: true
Platform: Win32
User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko
At least Chrome still has a string that contains "Chrome" with the exact version number. But, for IE you must extrapolate from the things it supports to actually figure it out (who else would boast that they support .NET
or Media Center
:P), and then match it against the rv:
at the very end to get the version number. Of course, even such sophisticated heuristics might very likely fail as soon as IE 12 (or whatever they want to call it) comes out.
I know this is an old question, but the following should work if you don't need the month name at the DB level:
SELECT EXTRACT(YEAR_MONTH FROM summaryDateTime) summary_year_month
FROM trading_summary
GROUP BY summary_year_month;
You will probably find this to be better performing.. and if you are building a JSON object in the application layer, you can do the formatting/ordering as you run through the results.
N.B. I wasn't aware you could add DESC to a GROUP BY clause in MySQL, perhaps you are missing an ORDER BY clause:
SELECT EXTRACT(YEAR_MONTH FROM summaryDateTime) summary_year_month
FROM trading_summary
GROUP BY summary_year_month
ORDER BY summary_year_month DESC;
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
Yeah it's possible.
Button myBtn = (Button)findViewById(R.id.myButtonId);
myBtn.requestFocus();
or in XML
<Button ...><requestFocus /></Button>
Important Note: The button widget needs to be focusable
and focusableInTouchMode
. Most widgets are focusable
but not focusableInTouchMode
by default. So make sure to either set it in code
myBtn.setFocusableInTouchMode(true);
or in XML
android:focusableInTouchMode="true"
The col
argument in the plot
function assign colors automatically to a vector of integers. If you convert iris$Species
to numeric, notice you have a vector of 1,2 and 3s So you can apply this as:
plot(iris$Sepal.Length, iris$Sepal.Width, col=as.numeric(iris$Species))
Suppose you want red, blue and green instead of the default colors, then you can simply adjust it:
plot(iris$Sepal.Length, iris$Sepal.Width, col=c('red', 'blue', 'green')[as.numeric(iris$Species)])
You can probably see how to further modify the code above to get any unique combination of colors.
VB Code:
Dim ListItem1 As New ListItem()
ListItem1.Text = "put anything here"
ListItem1.Value = "0"
drpTag.DataBind()
drpTag.Items.Insert(0, ListItem1)
View:
<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator" ControlToValidate="drpTag"
ValueToCompare="0">
</asp:CompareValidator>
It's a lot easier than that:
List = open("filename.txt").readlines()
This returns a list of each line in the file.
I solved this by writing a debounce decorator. The problem described could be solved by applying the @debounceAccessor to the property's set accessor.
I've also supplied an additional debounce decorator for methods, which can be useful for other occasions.
This makes it very easy to debounce a property or a method. The parameter is the number of milliseconds the debounce should last, 100 ms in the example below.
@debounceAccessor(100)
set myProperty(value) {
this._myProperty = value;
}
@debounceMethod(100)
myMethod (a, b, c) {
let d = a + b + c;
return d;
}
And here's the code for the decorators:
function debounceMethod(ms: number, applyAfterDebounceDelay = false) {
let timeoutId;
return function (target: Object, propName: string, descriptor: TypedPropertyDescriptor<any>) {
let originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
if (timeoutId) return;
timeoutId = window.setTimeout(() => {
if (applyAfterDebounceDelay) {
originalMethod.apply(this, args);
}
timeoutId = null;
}, ms);
if (!applyAfterDebounceDelay) {
return originalMethod.apply(this, args);
}
}
}
}
function debounceAccessor (ms: number) {
let timeoutId;
return function (target: Object, propName: string, descriptor: TypedPropertyDescriptor<any>) {
let originalSetter = descriptor.set;
descriptor.set = function (...args: any[]) {
if (timeoutId) return;
timeoutId = window.setTimeout(() => {
timeoutId = null;
}, ms);
return originalSetter.apply(this, args);
}
}
}
I added an additional parameter for the method decorator which let's you trigger the method AFTER the debounce delay. I did that so I could for instance use it when coupled with mouseover or resize events, where I wanted the capturing to occur at the end of the event stream. In this case however, the method won't return a value.
With the requests
lib JSONDecodeError
can happen when you have an http error code like 404 and try to parse the response as JSON !
You must first check for 200 (OK) or let it raise on error to avoid this case. I wish it failed with a less cryptic error message.
NOTE: as Martijn Pieters stated in the comments servers can respond with JSON in case of errors (it depends on the implementation), so checking the Content-Type
header is more reliable.
you can try to export as "Runnable jar" in eclipse. I have also problems, when i export as "jar", but i have never problems when i export as "Runnable jar".
NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];
or use
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
OFFSET is what you are looking for.
SELECT * FROM table LIMIT 10 OFFSET 10
If you are getting this from the Ditto
command creating multiple instances of the same name (NOT the 'copy files' build phase
), you may have to change the Product Module Name
.
Build Settings
Product Module Name
We have a watch target and a few notification targets in our app, so I just put things like Extension
on the end of the module name.
I found this solution originally here: https://forums.developer.apple.com/thread/103913
If you want the timestamp for yesterday try something like:
(CURRENT_TIMESTAMP - INTERVAL '1' DAY)
What would you like these support libraries to do? Just using OpenGL from C# is simple enough and does not require any additional libraries afaik.
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fees Paid Rs100:"
android:textColor="#276ca4"
android:checked="false"
android:onClick="checkbox_clicked" />
Main Activity from here
public class RegistA extends Activity {
CheckBox fee_checkbox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regist);
fee_checkbox = (CheckBox)findViewById(R.id.checkBox1);// Fee Payment Check box
}
checkbox clicked
public void checkbox_clicked(View v)
{
if(fee_checkbox.isChecked())
{
// true,do the task
}
else
{
}
}
$str = "Hello World!\n\n";
echo chop($str);
output : Hello World!
To support the answer by @oberstet, if the cert is not trusted by the browser (for example you get a "this site is not secure, do you want to continue?") one solution is to open the browser options, navigate to the certificates settings and add the host and post that the websocket server is being served from to the certificate provider as an exception.
for example add 'example-wss-domain.org:6001' as an exception to 'Certificate Provider Ltd'.
In firefox, this can be done from 'about:preferences' and searching for 'Certificates'
public class MySQLiteOpenHelper extends SQLiteOpenHelper { MySQLiteOpenHelper(Context context) { super(context, "/mnt/sdcard/database_name.db", null, 0); } }
Do not hardcode "/sdcard/"; use Environment.getExternalStorageDirectory().getPath() instead
Well, I was looking to make my canvas fullscreen too, This is how i did it. I'll post the entire index.html since I am not a CSS expert yet : (basically just using position:fixed and width and height as 100% and top and left as 0% and i nested this CSS code for every tag. I also have min-height and min-width as 100%. When I tried it with a 1px border the border size was changing as I zoomed in and out but the canvas remained fullscreen.)
<!DOCTYPE html>_x000D_
<html style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
<head>_x000D_
<title>MOUSEOVER</title>_x000D_
<script "text/javascript" src="main.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body id="BODY_CONTAINER" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
_x000D_
_x000D_
<div id="DIV_GUI_CONTAINER" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
<canvas id="myCanvas" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
</canvas>_x000D_
_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
_x000D_
</html>
_x000D_
EDIT: add this to the canvas element:
<canvas id="myCanvas" width="" height="" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">_x000D_
_x000D_
</canvas>
_x000D_
add this to the javascript
canvas.width = window.screen.width;
canvas.height = window.screen.height;
I found this made the drawing a lot smoother than my original comment.
Thanks.
var str = "\(INT_VALUE) , \(FLOAT_VALUE) , \(DOUBLE_VALUE), \(STRING_VALUE)"
Your code could look more like:
<?php
session_start();
$errorMsg = "";
$validUser = $_SESSION["login"] === true;
if(isset($_POST["sub"])) {
$validUser = $_POST["username"] == "admin" && $_POST["password"] == "password";
if(!$validUser) $errorMsg = "Invalid username or password.";
else $_SESSION["login"] = true;
}
if($validUser) {
header("Location: /login-success.php"); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Login</title>
</head>
<body>
<form name="input" action="" method="post">
<label for="username">Username:</label><input type="text" value="<?= $_POST["username"] ?>" id="username" name="username" />
<label for="password">Password:</label><input type="password" value="" id="password" name="password" />
<div class="error"><?= $errorMsg ?></div>
<input type="submit" value="Home" name="sub" />
</form>
</body>
</html>
Now, when the page is redirected based on the header('LOCATION:wherever.php)
, put session_start()
at the top of the page and test to make sure $_SESSION['login'] === true
. Remember that ==
would be true if $_SESSION['login'] == 1
as well.
Of course, this is a bad idea for security reasons, but my example may teach you a different way of using PHP.
cal_days_in_month() should give you the total number of days in the month, and therefore, the last one.
CREATE TRIGGER sampleTrigger
ON database1.dbo.table1
FOR DELETE
AS
DELETE FROM database2.dbo.table2
WHERE bar = 4 AND ID IN(SELECT deleted.id FROM deleted)
GO
No, a view consists of a single SELECT
statement. You cannot create or drop tables in a view.
Maybe a common table expression (CTE) can solve your problem. CTEs are temporary result sets that are defined within the execution scope of a single statement and they can be used in views.
Example (taken from here) - you can think of the SalesBySalesPerson
CTE as a temporary table:
CREATE VIEW vSalesStaffQuickStats
AS
WITH SalesBySalesPerson (SalesPersonID, NumberOfOrders, MostRecentOrderDate)
AS
(
SELECT SalesPersonID, COUNT(*), MAX(OrderDate)
FROM Sales.SalesOrderHeader
GROUP BY SalesPersonID
)
SELECT E.EmployeeID,
EmployeeOrders = OS.NumberOfOrders,
EmployeeLastOrderDate = OS.MostRecentOrderDate,
E.ManagerID,
ManagerOrders = OM.NumberOfOrders,
ManagerLastOrderDate = OM.MostRecentOrderDate
FROM HumanResources.Employee AS E
INNER JOIN SalesBySalesPerson AS OS ON E.EmployeeID = OS.SalesPersonID
LEFT JOIN SalesBySalesPerson AS OM ON E.ManagerID = OM.SalesPersonID
GO
Have a look at the psutil
module:
psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network) in Python. [...] It currently supports Linux, Windows, OSX, FreeBSD and Sun Solaris, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.4 (users of Python 2.4 and 2.5 may use 2.1.3 version). PyPy is also known to work.
It has a function called pid_exists()
that you can use to check whether a process with the given pid exists.
Here's an example:
import psutil
pid = 12345
if psutil.pid_exists(pid):
print("a process with pid %d exists" % pid)
else:
print("a process with pid %d does not exist" % pid)
For reference:
Above (Pre-SQL12) we see examples like this:-
SELECT
T1.id, SUM(T2.id) AS CumSum
FROM
#TMP T1
JOIN #TMP T2 ON T2.id < = T1.id
GROUP BY
T1.id
More efficient...
SELECT
T1.id, SUM(T2.id) + T1.id AS CumSum
FROM
#TMP T1
JOIN #TMP T2 ON T2.id < T1.id
GROUP BY
T1.id
I have created a general multi replace string Oracle function by a table of varchar2 as parameter. The varchar will be replaced for the position rownum value of table.
For example:
Text: Hello {0}, this is a {2} for {1}
Parameters: TABLE('world','all','message')
Returns:
Hello world, this is a message for all.
You must create a type:
CREATE OR REPLACE TYPE "TBL_VARCHAR2" IS TABLE OF VARCHAR2(250);
The funcion is:
CREATE OR REPLACE FUNCTION FN_REPLACETEXT(
pText IN VARCHAR2,
pPar IN TBL_VARCHAR2
) RETURN VARCHAR2
IS
vText VARCHAR2(32767);
vPos INT;
vValue VARCHAR2(250);
CURSOR cuParameter(POS INT) IS
SELECT VAL
FROM
(
SELECT VAL, ROWNUM AS RN
FROM (
SELECT COLUMN_VALUE VAL
FROM TABLE(pPar)
)
)
WHERE RN=POS+1;
BEGIN
vText := pText;
FOR i IN 1..REGEXP_COUNT(pText, '[{][0-9]+[}]') LOOP
vPos := TO_NUMBER(SUBSTR(REGEXP_SUBSTR(pText, '[{][0-9]+[}]',1,i),2, LENGTH(REGEXP_SUBSTR(pText, '[{][0-9]+[}]',1,i)) - 2));
OPEN cuParameter(vPos);
FETCH cuParameter INTO vValue;
IF cuParameter%FOUND THEN
vText := REPLACE(vText, REGEXP_SUBSTR(pText, '[{][0-9]+[}]',1,i), vValue);
END IF;
CLOSE cuParameter;
END LOOP;
RETURN vText;
EXCEPTION
WHEN OTHERS
THEN
RETURN pText;
END FN_REPLACETEXT;
/
Usage:
TEXT_RETURNED := FN_REPLACETEXT('Hello {0}, this is a {2} for {1}', TBL_VARCHAR2('world','all','message'));
If you need to check for null, that is the way. However, if you have control on this, just return empty collection, whenever you can, and check only for empty later on.
This thread is about the same thing with C#, but the principles applies equally well to java. Like mentioned there, null should be returned only if
- null might mean something more specific;
- your API (contract) might force you to return null.
.test * {padding: 40px 100px 40px 50px;}
From all the answers above, Björn's answer seems to be the most elegant and short. I personally used this approach many times. MAX or MIN function will do the job equally well. Complete PL/SQL follows, just the where clause should be specified.
declare v_column my_table.column%TYPE;
begin
select MIN(column) into v_column from my_table where ...;
DBMS_OUTPUT.PUT_LINE('v_column=' || v_column);
end;
Single line- There are two ways, you can simply change.
1- Pragmatically (Swift 3)
Just add the following code
yourLabel.numberOfLines = 1;
yourLabel.minimumScaleFactor = 0.7;
yourLabel.adjustsFontSizeToFitWidth = true;
2 - Using UILabel Attributes inspector
i- Select your label- Set number of lines 1.
ii- Autoshrink- Select Minimum Font Scale from drop down
iii- Set Minimum Font Scale value as you wish , I have set 0.7 as in below image. (default is 0.5)
Use something like this:
page1.php
<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>
Any other PHP page:
<?php
session_start();
echo $_SESSION['myValue'];
?>
A few notes to keep in mind though: You need to call session_start()
BEFORE any output, HTML, echos - even whitespace.
You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.
The setting of the variable itself can be done in one of a number of ways:
$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];
And if you want to check if the variable is set before getting a potential error, use something like this:
if(!empty($_SESSION['myValue'])
{
echo $_SESSION['myValue'];
}
else
{
echo "Session not set yet.";
}
I had the same error, but it was because password_expired
was set to Y
. You can fix that issue by following the same approach as the currently accepted answer, but instead executing the MySQL query:
UPDATE mysql.user SET password_expired = 'N' WHERE User='root';
you can use the shell(bash for example)
$ string="12 BBQ ,45 rofl, 89 lol"
$ echo ${string% rofl*}
12 BBQ ,45
$ string=${string% rofl*}
$ echo ${string##*,}
45
Short answer: classmaps are static while PSR autoloading is dynamic.
If you don't want to use classmaps, use PSR autoloading instead.
Another important note that I have missed, and fixed the "Bad Source" Error instantly:
(Just thought I will share my mistake just in case someone encounters it.. :))
Make sure the the correct path is selected in the git Console when you run the command:
- git mv Source Destination
If needed, use:
- cd SourceFolder
And then the mv command.
If you've definitely got an absolute path, use Path.GetDirectoryName(path)
.
If you might only get a relative name, use new FileInfo(path).Directory.FullName
.
Note that Path
and FileInfo
are both found in the namespace System.IO
.
Mostly we write below statement select * from table where length(ltrim(rtrim(field)))=10;
You can try Kafka Magic - it's free and you can write complex queries in JavaScript referencing message properties and metadata. Works with Avro serialization too
#ifndef <token>
/* code */
#else
/* code to include if the token is defined */
#endif
#ifndef
checks whether the given token has been #defined
earlier in the file or in an included file; if not, it includes the code between it and the closing #else
or, if no #else
is present, #endif
statement. #ifndef
is often used to make header files idempotent by defining a token once the file has been included and checking that the token was not set at the top of that file.
#ifndef _INCL_GUARD
#define _INCL_GUARD
#endif
I guess this has been solved by now but still the best thing to do here is to send the token with your form
{!! csrf_field() !!}
and then in your ajax
$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
url: "test",
type:"POST",
data: { '_token': token, 'someOtherData': someOtherData },
success:function(data){
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
You can use:
git rev-parse --is-inside-work-tree
Which will print 'true' if you are in a git repos working tree.
Note that it still returns output to STDERR if you are outside of a git repo (and does not print 'false').
Taken from this answer: https://stackoverflow.com/a/2044714/12983
x.times do |i|
something(i+1)
end
you can split using a third party software http://www.hjsplit.org/, for example give yours input that could be upto 9GB and then split, in my case I split 10 MB each
Yes you can. Just check my fiddle for clarification. For demo purpose i kept the code in fiddle at same location. You can extract that code as shown in two different Javascript files and load them in html file.
https://jsfiddle.net/mvora/mrLmkxmo/
/******** PUT THIS CODE IN ONE JS FILE *******/
var secondFileFuntion = function(){
this.name = 'XYZ';
}
secondFileFuntion.prototype.getSurname = function(){
return 'ABC';
}
var secondFileObject = new secondFileFuntion();
/******** Till Here *******/
/******** PUT THIS CODE IN SECOND JS FILE *******/
function firstFileFunction(){
var name = secondFileObject.name;
var surname = secondFileObject.getSurname()
alert(name);
alert(surname );
}
firstFileFunction();
If you make an object using the constructor function and trying access the property or method from it in second file, it will give you the access of properties which are present in another file.
Just take care of sequence of including these files in index.html
You need to write a document.write object:
document.write('<script type="text/javascript" src="file.js" ></script>');
and place it in your main javascript file
Yes, a static class
for storing constants would be just fine, except for constants that are related to specific types.
Make sure to watch your selectors. You appear to have forgotten the #
for div2
. Additionally, you can toggle the visibility of many elements at once with .toggle()
:
// Short-form of `document.ready`
$(function(){
$("#div2").hide();
$("#preview").on("click", function(){
$("#div1, #div2").toggle();
});
});
Do you have variables that are associated with these print statements been output? if so, I have found that if the variable has no value then the print statement will not be ouput.
"Allocation Failure" is a cause of GC cycle to kick in.
"Allocation Failure" means that no more space left in Eden to allocate object. So, it is normal cause of young GC.
Older JVM were not printing GC cause for minor GC cycles.
"Allocation Failure" is almost only possible cause for minor GC. Another reason for minor GC to kick could be CMS remark phase (if +XX:+ScavengeBeforeRemark
is enabled).
"location" directive should be inside a 'server' directive, e.g.
server {
listen 8765;
location / {
resolver 8.8.8.8;
proxy_pass http://$http_host$uri$is_args$args;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
Unlike languages such as C, a Python variable is in scope for the whole of the function (or class, or module) where it appears, not just in the innermost "block". It is as though you declared int x
at the top of the function (or class, or module), except that in Python you don't have to declare variables.
Note that the existence of the variable x
is checked only at runtime -- that is, when you get to the print x
statement. If __name__
didn't equal "__main__"
then you would get an exception: NameError: name 'x' is not defined
.
use Jackson (https://github.com/FasterXML/jackson) from http://json.org/
HashMap<String,Object> result =
new ObjectMapper().readValue(<JSON_OBJECT>, HashMap.class);
I allowed myself to create a javascript version of it. Might it be helpful. The javascript should be direct transcription of the Pseudocode given above. Available as npm package and github repo:
// javascript port of: https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/48895639#48895639
function sum(a) {
return a.reduce((acc, val) => acc + val)
}
function mean(a) {
return sum(a) / a.length
}
function stddev(arr) {
const arr_mean = mean(arr)
const r = function(acc, val) {
return acc + ((val - arr_mean) * (val - arr_mean))
}
return Math.sqrt(arr.reduce(r, 0.0) / arr.length)
}
function smoothed_z_score(y, params) {
var p = params || {}
// init cooefficients
const lag = p.lag || 5
const threshold = p.threshold || 3.5
const influence = p.influece || 0.5
if (y === undefined || y.length < lag + 2) {
throw ` ## y data array to short(${y.length}) for given lag of ${lag}`
}
//console.log(`lag, threshold, influence: ${lag}, ${threshold}, ${influence}`)
// init variables
var signals = Array(y.length).fill(0)
var filteredY = y.slice(0)
const lead_in = y.slice(0, lag)
//console.log("1: " + lead_in.toString())
var avgFilter = []
avgFilter[lag - 1] = mean(lead_in)
var stdFilter = []
stdFilter[lag - 1] = stddev(lead_in)
//console.log("2: " + stdFilter.toString())
for (var i = lag; i < y.length; i++) {
//console.log(`${y[i]}, ${avgFilter[i-1]}, ${threshold}, ${stdFilter[i-1]}`)
if (Math.abs(y[i] - avgFilter[i - 1]) > (threshold * stdFilter[i - 1])) {
if (y[i] > avgFilter[i - 1]) {
signals[i] = +1 // positive signal
} else {
signals[i] = -1 // negative signal
}
// make influence lower
filteredY[i] = influence * y[i] + (1 - influence) * filteredY[i - 1]
} else {
signals[i] = 0 // no signal
filteredY[i] = y[i]
}
// adjust the filters
const y_lag = filteredY.slice(i - lag, i)
avgFilter[i] = mean(y_lag)
stdFilter[i] = stddev(y_lag)
}
return signals
}
module.exports = smoothed_z_score
return value.equals("false") || value.equals("true");
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]
Make sure you have Desktop Development with C++ installed. I was experiencing the same problem because I only had Universal Windows Platform Development installed.
If you're simply sharing a counter, consider using an AtomicInteger or another suitable class from the java.util.concurrent.atomic package:
public class Test {
private final static AtomicInteger count = new AtomicInteger(0);
public void foo() {
count.incrementAndGet();
}
}
Using Between condition
SELECT *
FROM TEST
WHERE COLUMN_NAME BETWEEN x AND y ;
Or using Just operators,
SELECT *
FROM TEST
WHERE COLUMN_NAME >= x AND COLUMN_NAME <= y;
lockless Copy and Write approach works great if you're not dealing with too many items. Here's a class I wrote:
public class CopyAndWriteList<T>
{
public static List<T> Clear(List<T> list)
{
var a = new List<T>(list);
a.Clear();
return a;
}
public static List<T> Add(List<T> list, T item)
{
var a = new List<T>(list);
a.Add(item);
return a;
}
public static List<T> RemoveAt(List<T> list, int index)
{
var a = new List<T>(list);
a.RemoveAt(index);
return a;
}
public static List<T> Remove(List<T> list, T item)
{
var a = new List<T>(list);
a.Remove(item);
return a;
}
}
example usage: orders_BUY = CopyAndWriteList.Clear(orders_BUY);
Indirectly Relevant: when 1=2 is used:
CREATE TABLE New_table_name
as
select *
FROM Old_table_name
WHERE 1 = 2;
this will create a new table with same schema as old table. (Very handy if you want to load some data for compares)
Here is the solution that I recently used:
public class Test {
public String a;
public long b;
public Date c;
public String d;
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Test)) {
return false;
}
Test testOther = (Test) obj;
return (a != null ? a.equals(testOther.a) : testOther.a == null)
&& (b == testOther.b)
&& (c != null ? c.equals(testOther.c) : testOther.c == null)
&& (d != null ? d.equals(testOther.d) : testOther.d == null);
}
}
@BozidarS: FileAPI is supported quite well nowadays and provides a number of useful options.
var file = document.forms['formName']['inputName'].files[0];
//file.name == "photo.png"
//file.type == "image/png"
//file.size == 300821
You should also be able to do:
apt install sudo
sudo -i -u tomcat
Then you should be the tomcat user. It's not clear which Linux distribution you're using, but this works with Ubuntu 18.04 LTS, for example.
I would consider writing a CLR replace function with RegEx support for this kind of string manipulation.
You can also use PostCSS and the custom selectors plugin
@custom-selector :--headings h1, h2, h3, h4, h5, h6;
article :--headings {
margin-top: 0;
}
Output:
article h1,
article h2,
article h3,
article h4,
article h5,
article h6 {
margin-top: 0;
}
No, nothing built-in (until Excel 2013 - see this answer).
There are three versions of URLEncode()
in this answer.
A variant that supports UTF-8 encoding and is based on ADODB.Stream
(include a reference to a recent version of the "Microsoft ActiveX Data Objects" library in your project):
Public Function URLEncode( _
ByVal StringVal As String, _
Optional SpaceAsPlus As Boolean = False _
) As String
Dim bytes() As Byte, b As Byte, i As Integer, space As String
If SpaceAsPlus Then space = "+" Else space = "%20"
If Len(StringVal) > 0 Then
With New ADODB.Stream
.Mode = adModeReadWrite
.Type = adTypeText
.Charset = "UTF-8"
.Open
.WriteText StringVal
.Position = 0
.Type = adTypeBinary
.Position = 3 ' skip BOM
bytes = .Read
End With
ReDim result(UBound(bytes)) As String
For i = UBound(bytes) To 0 Step -1
b = bytes(i)
Select Case b
Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
result(i) = Chr(b)
Case 32
result(i) = space
Case 0 To 15
result(i) = "%0" & Hex(b)
Case Else
result(i) = "%" & Hex(b)
End Select
Next i
URLEncode = Join(result, "")
End If
End Function
This function was found on freevbcode.com:
Public Function URLEncode( _
StringToEncode As String, _
Optional UsePlusRatherThanHexForSpace As Boolean = False _
) As String
Dim TempAns As String
Dim CurChr As Integer
CurChr = 1
Do Until CurChr - 1 = Len(StringToEncode)
Select Case Asc(Mid(StringToEncode, CurChr, 1))
Case 48 To 57, 65 To 90, 97 To 122
TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
Case 32
If UsePlusRatherThanHexForSpace = True Then
TempAns = TempAns & "+"
Else
TempAns = TempAns & "%" & Hex(32)
End If
Case Else
TempAns = TempAns & "%" & _
Right("0" & Hex(Asc(Mid(StringToEncode, _
CurChr, 1))), 2)
End Select
CurChr = CurChr + 1
Loop
URLEncode = TempAns
End Function
I've corrected a little bug that was in there.
I would use more efficient (~2× as fast) version of the above:
Public Function URLEncode( _
StringVal As String, _
Optional SpaceAsPlus As Boolean = False _
) As String
Dim StringLen As Long: StringLen = Len(StringVal)
If StringLen > 0 Then
ReDim result(StringLen) As String
Dim i As Long, CharCode As Integer
Dim Char As String, Space As String
If SpaceAsPlus Then Space = "+" Else Space = "%20"
For i = 1 To StringLen
Char = Mid$(StringVal, i, 1)
CharCode = Asc(Char)
Select Case CharCode
Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
result(i) = Char
Case 32
result(i) = Space
Case 0 To 15
result(i) = "%0" & Hex(CharCode)
Case Else
result(i) = "%" & Hex(CharCode)
End Select
Next i
URLEncode = Join(result, "")
End If
End Function
Note that neither of these two functions support UTF-8 encoding.
Maybe you have no Comments record with such primary key, then you should use this code:
try:
comment = Comment.objects.get(pk=comment_id)
except Comment.DoesNotExist:
comment = None
This is one more option to find the element for above question
$("#tbIntervalos").find('td[id="'+horaInicial+'"]')
//By each()
var testval = [];
$('.hobbies_class:checked').each(function() {
testval.push($(this).val());
});
//by map()
var testval = $('input:checkbox:checked.hobbies_class').map(function(){
return this.value; }).get().join(",");
//HTML Code
<input type="checkbox" value="cricket" name="hobbies[]" class="hobbies_class">Cricket
<input type="checkbox" value="hockey" name="hobbies[]" class="hobbies_class">Hockey
Example
Demo
NSNumber *lat = [NSNumber numberWithDouble:destinationMapView.camera.target.latitude];
NSNumber *lon = [NSNumber numberWithDouble:destinationMapView.camera.target.longitude];
NSString *DesconCatenated = [NSString stringWithFormat:@"%@|%@",lat,lon];
when you pushing code to another branch just follow the below git command. Remember demo is my other branch name you can replace with your branch name.
git push origin master:demo
You can use the JAVA 7 Files api
Path myDirectoryPath = Paths.get("path to my directory");
List<Path> subDirectories = Files.find(
myDirectoryPath ,
Integer.MAX_VALUE,
(filePath, fileAttr) -> fileAttr.isDirectory() && !filePath.equals(myDirectoryPath )
).collect(Collectors.toList());
If you want a specific value you can call map with the value you want before collecting the data.
Check that the "Windows Management Instrumentation (WMI-In)" rule is enabled in the firewall for each remote machine.
Or in an Administrative Command/Powershell prompt run:
netsh advfirewall firewall set rule group="Windows Management Instrumentation (WMI)" new enable=yes
You can do this.
git clone https://github.com/sferik/sign-in-with-twitter.git signin
You can use pandas.Series.tolist
e.g.:
import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
Run:
>>> df['a'].tolist()
You will get
>>> [1, 2, 3]
if you want to populate a table in SQL SERVER you can use while statement as follows:
declare @llenandoTabla INT = 0;
while @llenandoTabla < 10000
begin
insert into employeestable // Name of my table
(ID, FIRSTNAME, LASTNAME, GENDER, SALARY) // Parameters of my table
VALUES
(555, 'isaias', 'perez', 'male', '12220') //values
set @llenandoTabla = @llenandoTabla + 1;
end
Hope it helps.
my combination looks like this. it fades out and fades in on each scroll down/up. otherwise you have to scroll up to the header, for fading the header in.
var header = $("#header");
$('#content-container').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
if (header.data('faded')) {
header.data('faded', 0).stop(true).fadeTo(800, 1);
}
}
else{
if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);
}
});
the above one is not optimized for touch/mobile, I think this one does it better for all mobile:
var iScrollPos = 0;
var header = $("#header");
$('#content-container').scroll(function () {
var iCurScrollPos = $(this).scrollTop();
if (iCurScrollPos > iScrollPos) {
if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);
} else {
//Scrolling Up
if (header.data('faded')) {
header.data('faded', 0).stop(true).fadeTo(800, 1);
}
}
iScrollPos = iCurScrollPos;
});
If you already have boto installed in one python version and then install a higher python version, boto is not found by the new version of python.
For example, I had python2.7 and then installed python3.5 (keeping both). My script under python3.5 could not find boto. Doing "pip install boto
" told me that boto was already installed in /usr/lib/python2.7/dist-packages
.
So I did
pip install --target /usr/lib/python3.5/dist-packages boto
This allowed my script under python3.5 to find boto.
PHP can be easily utilized for reading bar codes printed on paper documents. Connecting manual barcode reader to the computer via USB significantly extends usability of PHP (or any other web programming language) into tasks involving document and product management, like finding a book records in the database or listing all bills for a particular customer.
Following sections briefly describe process of connecting and using manual bar code reader with PHP.
The usage of bar code scanners described in this article are in the same way applicable to any web programming language, such as ASP, Python or Perl. This article uses only PHP since all tests have been done with PHP applications.
What is a bar code reader (scanner)
Bar code reader is a hardware pluggable into computer that sends decoded bar code strings into computer. The trick is to know how to catch that received string. With PHP (and any other web programming language) the string will be placed into focused input HTML element in browser. Thus to catch received bar code string, following must be done:
just before reading the bar code, proper input element, such as INPUT TEXT FIELD must be focused (mouse cursor is inside of the input field). once focused, start reading the code when the code is recognized (bar code reader usually shortly beeps), it is send to the focused input field. By default, most of bar code readers will append extra special character to decoded bar code string called CRLF (ENTER). For example, if decoded bar code is "12345AB", then computer will receive "12345ABENTER". Appended character ENTER (or CRLF) emulates pressing the key ENTER causing instant submission of the HTML form:
<form action="search.php" method="post">
<input name="documentID" onmouseover="this.focus();" type="text">
</form>
Choosing the right bar code scanner
When choosing bar code reader, one should consider what types of bar codes will be read with it. Some bar codes allow only numbers, others will not have checksum, some bar codes are difficult to print with inkjet printers, some barcode readers have narrow reading pane and cannot read for example barcodes with length over 10 cm. Most of barcode readers support common barcodes, such as EAN8, EAN13, CODE 39, Interleaved 2/5, Code 128 etc.
For office purposes, the most suitable barcodes seem to be those supporting full range of alphanumeric characters, which might be:
Other important things to note:
Installing scanner drivers
Installing manual bar code reader requires installing drivers for your particular operating system and should be normally supplied with purchased bar code reader.
Once installed and ready, bar code reader turns on signal LED light. Reading the barcode starts with pressing button for reading.
Scanning the barcode - how does it work?
STEP 1 - Focused input field ready for receiving character stream from bar code scanner:
STEP 2 - Received barcode string from bar code scanner is immediatelly submitted for search into database, which creates nice "automated" effect:
STEP 3 - Results returned after searching the database with submitted bar code:
Conclusion
It seems, that utilization of PHP (and actually any web programming language) for scanning the bar codes has been quite overlooked so far. However, with natural support of emulated keypress (ENTER/CRLF) it is very easy to automate collecting & processing recognized bar code strings via simple HTML (GUI) fomular.
The key is to understand, that recognized bar code string is instantly sent to the focused HTML element, such as INPUT text field with appended trailing character ASCII 13 (=ENTER/CRLF, configurable option), which instantly sends input text field with populated received barcode as a HTML formular to any other script for further processing.
Reference: http://www.synet.sk/php/en/280-barcode-reader-scanner-in-php
Hope this helps you :)
SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.
Let's suppose you have two databases on the same server - Db1
and Db2
. Db1
has a table called Clients
with a column ClientId
and Db2
has a table called Messages
with a column ClientId
(let's leave asside why those tables are in different databases).
Now, to perform a join on the above-mentioned tables you will be using this query:
select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId
You are confuising two CSS styles, the display style and the visibility style.
If the element is hidden by setting the visibility css style, then you should be able to get the height regardless of whether or not the element is visible or not as the element still takes space on the page.
If the element is hidden by changing the display css style to "none", then the element doesn't take space on the page, and you will have to give it a display style which will cause the element to render in some space, at which point, you can get the height.
If you are confused what to do, just refer to the manual of session_destroy() function:
http://php.net/manual/en/function.session-destroy.php
There you can find some more features of session_destroy().
It can also be done with a positive assertion of removal, like this:
textContent = textContent.replace(/[\u{0080}-\u{FFFF}]/gu,"");
This uses unicode. In Javascript, when expressing unicode for a regular expression, the characters are specified with the escape sequence \u{xxxx}
but also the flag 'u'
must present; note the regex has flags 'gu'
.
I called this a "positive assertion of removal" in the sense that a "positive" assertion expresses which characters to remove, while a "negative" assertion expresses which letters to not remove. In many contexts, the negative assertion, as stated in the prior answers, might be more suggestive to the reader. The circumflex "^
" says "not" and the range \x00-\x7F
says "ascii," so the two together say "not ascii."
textContent = textContent.replace(/[^\x00-\x7F]/g,"");
That's a great solution for English language speakers who only care about the English language, and its also a fine answer for the original question. But in a more general context, one cannot always accept the cultural bias of assuming "all non-ascii is bad." For contexts where non-ascii is used, but occasionally needs to be stripped out, the positive assertion of Unicode is a better fit.
A good indication that zero-width, non printing characters are embedded in a string is when the string's "length" property is positive (nonzero), but looks like (i.e. prints as) an empty string. For example, I had this showing up in the Chrome debugger, for a variable named "textContent":
> textContent
""
> textContent.length
7
This prompted me to want to see what was in that string.
> encodeURI(textContent)
"%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B"
This sequence of bytes seems to be in the family of some Unicode characters that get inserted by word processors into documents, and then find their way into data fields. Most commonly, these symbols occur at the end of a document. The zero-width-space "%E2%80%8B"
might be inserted by CK-Editor (CKEditor).
encodeURI() UTF-8 Unicode html Meaning
----------- -------- ------- ------- -------------------
"%E2%80%8B" EC 80 8B U 200B ​ zero-width-space
"%E2%80%8E" EC 80 8E U 200E ‎ left-to-right-mark
"%E2%80%8F" EC 80 8F U 200F ‏ right-to-left-mark
Some references on those:
http://www.fileformat.info/info/unicode/char/200B/index.htm
https://en.wikipedia.org/wiki/Left-to-right_mark
Note that although the encoding of the embedded character is UTF-8, the encoding in the regular expression is not. Although the character is embedded in the string as three bytes (in my case) of UTF-8, the instructions in the regular expression must use the two-byte Unicode. In fact, UTF-8 can be up to four bytes long; it is less compact than Unicode because it uses the high bit (or bits) to escape the standard ascii encoding. That's explained here:
Since I haven't gotten any more feedback on this issue, I thought I'd just share what ended up being my solution:
As suggested by Barry in a comment to the original post, manually renaming the '...bin\Debug[ProjectName].exe' to something else (e.g. '[ProjectName]1.exe') is one work-around (I'm however not allowed to delete the file myself, and I must say I find that a bit weird as one would believe the same lock preventing deletion would also prevent renaming...). It's not a good solution, but it's reasonable fast (at least after you've done it a couple of times, it almost becomes a routine), and at least way faster than restarting Visual Studio which is what I did in the beginning.
In case somebody wonders, I could also add that I only see this problem semi-randomly. It usually happens after I've done some changes in the design mode of a form (but not always). It usually doesn't happen if I only change business-logic code or non-visual related code (but sometimes it does...). Frustrating indeed, but at least I have a hack that works for me - let's just hope that my next project doesn't face this problem as well...
@Barry: if you would like to get credit for your comment, please feel free to post it as an answer and I'll make sure to accept it :)
If this div is a function I suggest use cursor:pointer in your style like style="cursor:pointer" and can use onclick function.
like this
<div onclick="myfunction()" style="cursor:pointer"></div>
From MSDN:
The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable(Of T) interface.
So, it's not necessarily Array. It could even be a lazy collection with no idea about the count of items in the collection.
I saw some contradictions in the answers above, I just tried the following on Oracle 12c and the following is correct :
LEFT OUTER JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT *
FROM A, B
WHERE B.column(+) = A.column
for 14.04.1-Ubuntu https://wkhtmltopdf.org/downloads.html
wget https://downloads.wkhtmltopdf.org/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz -O mktemp.tar.xz
tar xf mktemp.tar.xz
sudo cp wkhtmltox/bin/wkhtmltopdf /usr/bin/wkhtmltopdf
sudo chmod +x /usr/bin/wkhtmltopdf
rm mktemp.tar.xz
rm wkhtmltox -rf
apt-get update
apt-get install -y libxrender1 libxtst6 libxi6
wkhtmltopdf http://www.google.com test.pdf
string source;
// source gets initialized
string dest;
if (source.Length > 0)
{
dest = source.Substring(0, source.Length - 1);
}
The most fundamental thing here probably is that you don't want to transmit static images but only changes to the images, which essentially is analogous to video stream.
My best guess is some very efficient (and heavily specialized and optimized) motion compensation algorithm, because most of the actual change in generic desktop usage is linear movement of elements (scrolling text, moving windows, etc. opposed to transformation of elements).
The DirectX 3D performance of 1 FPS seems to confirm my guess to some extent.
I had the same problem, and I found the solution in this post of Sam Goddard,
The solution if to defined the call to the font twice. First as it is recommended, to be used for all the browsers, and after a particular call only for Chrome with a special media query:
@font-face {
font-family: 'chunk-webfont';
src: url('../../includes/fonts/chunk-webfont.eot');
src: url('../../includes/fonts/chunk-webfont.eot?#iefix') format('eot'),
url('../../includes/fonts/chunk-webfont.woff') format('woff'),
url('../../includes/fonts/chunk-webfont.ttf') format('truetype'),
url('../../includes/fonts/chunk-webfont.svg') format('svg');
font-weight: normal;
font-style: normal;
}
@media screen and (-webkit-min-device-pixel-ratio:0) {
@font-face {
font-family: 'chunk-webfont';
src: url('../../includes/fonts/chunk-webfont.svg') format('svg');
}
}
With this method the font will render good in all browsers. The only negative point that I found is that the font file is also downloaded twice.
You can find an spanish version of this article in my page
I got the same error in this code:
var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();
this was the exactly error:
System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'
I solved this way:
var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();
I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated
NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory
The above solution for the JsonCreationConverter<T>
is all over the internet, but has a flaw that manifests itself in rare occasions. The new JsonReader created in the ReadJson method does not inherit any of the original reader's configuration values (Culture, DateParseHandling, DateTimeZoneHandling, FloatParseHandling, etc...). These values should be copied over before using the new JsonReader in serializer.Populate().
This is the best I could come up with to fix some of the problems with the above implementation, but I still think there are some things being overlooked:
Update I updated this to have a more explicit method that makes a copy of an existing reader. This just encapsulates the process of copying over individual JsonReader settings. Ideally this function would be maintained in the Newtonsoft library itself, but for now, you can use the following:
/// <summary>Creates a new reader for the specified jObject by copying the settings
/// from an existing reader.</summary>
/// <param name="reader">The reader whose settings should be copied.</param>
/// <param name="jToken">The jToken to create a new reader for.</param>
/// <returns>The new disposable reader.</returns>
public static JsonReader CopyReaderForObject(JsonReader reader, JToken jToken)
{
JsonReader jTokenReader = jToken.CreateReader();
jTokenReader.Culture = reader.Culture;
jTokenReader.DateFormatString = reader.DateFormatString;
jTokenReader.DateParseHandling = reader.DateParseHandling;
jTokenReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
jTokenReader.FloatParseHandling = reader.FloatParseHandling;
jTokenReader.MaxDepth = reader.MaxDepth;
jTokenReader.SupportMultipleContent = reader.SupportMultipleContent;
return jTokenReader;
}
This should be used as follows:
public override object ReadJson(JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
// Populate the object properties
using (JsonReader jObjectReader = CopyReaderForObject(reader, jObject))
{
serializer.Populate(jObjectReader, target);
}
return target;
}
Older solution follows:
/// <summary>Base Generic JSON Converter that can help quickly define converters for specific types by automatically
/// generating the CanConvert, ReadJson, and WriteJson methods, requiring the implementer only to define a strongly typed Create method.</summary>
public abstract class JsonCreationConverter<T> : JsonConverter
{
/// <summary>Create an instance of objectType, based properties in the JSON object</summary>
/// <param name="objectType">type of object expected</param>
/// <param name="jObject">contents of JSON object that will be deserialized</param>
protected abstract T Create(Type objectType, JObject jObject);
/// <summary>Determines if this converted is designed to deserialization to objects of the specified type.</summary>
/// <param name="objectType">The target type for deserialization.</param>
/// <returns>True if the type is supported.</returns>
public override bool CanConvert(Type objectType)
{
// FrameWork 4.5
// return typeof(T).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
// Otherwise
return typeof(T).IsAssignableFrom(objectType);
}
/// <summary>Parses the json to the specified type.</summary>
/// <param name="reader">Newtonsoft.Json.JsonReader</param>
/// <param name="objectType">Target type.</param>
/// <param name="existingValue">Ignored</param>
/// <param name="serializer">Newtonsoft.Json.JsonSerializer to use.</param>
/// <returns>Deserialized Object</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
//Create a new reader for this jObject, and set all properties to match the original reader.
JsonReader jObjectReader = jObject.CreateReader();
jObjectReader.Culture = reader.Culture;
jObjectReader.DateParseHandling = reader.DateParseHandling;
jObjectReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
jObjectReader.FloatParseHandling = reader.FloatParseHandling;
// Populate the object properties
serializer.Populate(jObjectReader, target);
return target;
}
/// <summary>Serializes to the specified type</summary>
/// <param name="writer">Newtonsoft.Json.JsonWriter</param>
/// <param name="value">Object to serialize.</param>
/// <param name="serializer">Newtonsoft.Json.JsonSerializer to use.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
I used the handler below to handle 404 error with a static .ejs
file.
Put this code in a route script and then require that file.js
through app.use()
in your app.js
/server.js
/www.js
(if using IntelliJ for NodeJS)
You can also use a static .html
file.
//Unknown route handler
router.get("[otherRoute]", function(request, response) {
response.status(404);
response.render("error404.[ejs]/[html]");
response.end();
});
This way, the running express server will response with a proper 404 error
and your website can also include a page that properly displays the server's 404 response properly. You can also include a navbar
in that 404 error template
that links to other important content of your website.
Dan Tello fix worked well for me.
One additional issue I found with IE8 was that if the PNG was held in a DIV with smaller CSS width or height dimensions than the PNG then the black edge prob was re-triggered.
Correcting the width and height CSS or removing them altogether fixed.
Another (less javascriptish) approach, that I did, goes something like this:
public static MvcHtmlString AntiForgeryTokenForAjaxPost(this HtmlHelper helper)
{
var antiForgeryInputTag = helper.AntiForgeryToken().ToString();
// Above gets the following: <input name="__RequestVerificationToken" type="hidden" value="PnQE7R0MIBBAzC7SqtVvwrJpGbRvPgzWHo5dSyoSaZoabRjf9pCyzjujYBU_qKDJmwIOiPRDwBV1TNVdXFVgzAvN9_l2yt9-nf4Owif0qIDz7WRAmydVPIm6_pmJAI--wvvFQO7g0VvoFArFtAR2v6Ch1wmXCZ89v0-lNOGZLZc1" />
var removedStart = antiForgeryInputTag.Replace(@"<input name=""__RequestVerificationToken"" type=""hidden"" value=""", "");
var tokenValue = removedStart.Replace(@""" />", "");
if (antiForgeryInputTag == removedStart || removedStart == tokenValue)
throw new InvalidOperationException("Oops! The Html.AntiForgeryToken() method seems to return something I did not expect.");
return new MvcHtmlString(string.Format(@"{0}:""{1}""", "__RequestVerificationToken", tokenValue));
}
__RequestVerificationToken:"P5g2D8vRyE3aBn7qQKfVVVAsQc853s-naENvpUAPZLipuw0pa_ffBf9cINzFgIRPwsf7Ykjt46ttJy5ox5r3mzpqvmgNYdnKc1125jphQV0NnM5nGFtcXXqoY3RpusTH_WcHPzH4S4l1PmB8Uu7ubZBftqFdxCLC5n-xT0fHcAY1"
$(function () {
$("#submit-list").click(function () {
$.ajax({
url: '@Url.Action("SortDataSourceLibraries")',
data: { items: $(".sortable").sortable('toArray'), @Html.AntiForgeryTokenForAjaxPost() },
type: 'post',
traditional: true
});
});
});
And it seems to work!
That should work. Better if you pass a function to val
:
$('#replyBox').val(function(i, text) {
return text + quote;
});
This way you avoid searching the element and calling val
twice.
Short Summary
Active Directory
is a directory services implemented by Microsoft, and it supports Lightweight Directory Access Protocol
(LDAP).
Long Answer
Firstly, one needs to know what's Directory Service
.
Directory Service is a software system that stores, organises, and provides access to information in a computer operating system's directory. In software engineering, a directory is a map between names and values. It allows the lookup of named values, similar to a dictionary.
For more details, read https://en.wikipedia.org/wiki/Directory_service
Secondly,as one could imagine, different vendors implement all kinds of forms of directory service, which is harmful to multi-vendor interoperability.
Thirdly, so in the 1980s, the ITU and ISO came up with a set of standards - X.500, for directory services, initially to support the requirements of inter-carrier electronic messaging and network name lookup.
Fourthly, so based on this standard, Lightweight Directory Access Protocol, LDAP, is developed. It uses the TCP/IP stack and a string encoding scheme of the X.500 Directory Access Protocol (DAP), giving it more relevance on the Internet.
Lastly, based on this LDAP/X.500 stack, Microsoft implemented a modern directory service for Windows, originating from the X.500 directory, created for use in Exchange Server. And this implementation is called Active Directory
.
So in a short summary, Active Directory
is a directory services implemented by Microsoft, and it supports Lightweight Directory Access Protocol
(LDAP).
PS[0]: This answer heavily copies content from the wikipedia page listed above.
PS[1]: To know why it may be better use directory service rather just using a relational database, read https://en.wikipedia.org/wiki/Directory_service#Comparison_with_relational_databases
First break the number into its decimal factors like 995 = 900 + 90 + 5 then convert each factor recursively
public class IntegerToRoman {
private Map<Integer, String> romanChars = new HashMap<>();
public IntegerToRoman() {
romanChars.put(1, "I");
romanChars.put(5, "V");
romanChars.put(10, "X");
romanChars.put(50, "L");
romanChars.put(100, "C");
romanChars.put(500, "D");
romanChars.put(1000, "M");
romanChars.put(5000, "V|");
}
public String intToRoman(int num) {
if (num == 0) {
return "";
}
int decimalFact = 0;
StringBuilder result = new StringBuilder();
for (int i = (int)Math.log10(num); i >= 0; i--) {
int divisor = (int) Math.pow(10, i);
decimalFact = num - num % divisor;
result.append(convertDecimalFact(decimalFact));
num = num % divisor;
}
return result.toString();
}
private String convertDecimalFact(int decimalFact){
if(decimalFact == 0){return "";}
int[] keyArray = romanChars.keySet().stream().mapToInt(key -> key)
.sorted().toArray();
for(int i =0 ; i+1<keyArray.length ; i++){
if( keyArray[i] <= decimalFact && decimalFact<= keyArray[i+1] ){
int bigger1stDgt = getLeftMostNum(keyArray[i+1]);
int decimalFact1stDgt = getLeftMostNum(decimalFact);
return decimalFact1stDgt >= bigger1stDgt-1 ?
intToRoman(keyArray[i+1]-decimalFact)+romanChars.get(keyArray[i+1]):
romanChars.get(keyArray[i])+intToRoman(decimalFact - keyArray[i]);
}
}
return "";
}
private int getLeftMostNum(int number) {
int oneDgt = Integer.valueOf(Integer.valueOf(number).toString()
.substring(0, 0 +1));
if(number<10){
return oneDgt;
}
int twoDgts = Integer.valueOf(Integer.valueOf(number).toString()
.substring(0, 0 +2));
return twoDgts==10 ? twoDgts : oneDgt;
}
public static void main(String[] args) {
IntegerToRoman solution = new IntegerToRoman();
System.out.format(" Decimal 3 -> Roman %s \n ", solution.intToRoman(3));
System.out.format("Decimal 4 -> Roman %s \n ", solution.intToRoman(4));
System.out.format("Decimal 8 -> Roman %s \n ", solution.intToRoman(8));
System.out.format("Decimal 58 -> Roman %s \n ", solution.intToRoman(58));
System.out.format("Decimal 344 -> Roman %s \n ", solution.intToRoman(344));
System.out.format("Decimal 995 -> Roman %s \n ", solution.intToRoman(995));
System.out.format("Decimal 1994 -> Roman %s \n ", solution.intToRoman(1994));
}
}
Output is like:
Decimal 3 -> Roman III
Decimal 4 -> Roman IV
Decimal 8 -> Roman VIII
Decimal 58 -> Roman LVIII
Decimal 344 -> Roman CCCXLIV
Decimal 995 -> Roman CMXCV
Decimal 1994 -> Roman MCMXCIV
"npm install" replaces all dependencies in your node_modules installed with "npm link" with versions from npmjs (specified in your package.json)
How to find out the document width and height very easily?
in HTML
<span id="hidden_placer" style="position:absolute;right:0;bottom:0;visibility:hidden;"></span>
in javascript
var c=document.querySelector('#hidden_placer');
var r=c.getBoundingClientRect();
r.right=document width
r.bottom=document height`
You may update this on every window resize event, if needed.
with io.vavr
public static char[] alphanumericAlphabet() {
return CharSeq
.rangeClosed('0','9')
.appendAll(CharSeq.rangeClosed('a','z'))
.appendAll(CharSeq.rangeClosed('A','Z'))
.toCharArray();
}
I came here from golang, where it's common to see something like
if (err := doSomething(); err != nil) {
return nil, err
}
In which err
is scoped to that if
block only. As such, here's what I'm doing in es6, which seems pretty ugly, but doesn't make my rather strict eslint rules whinge, and achieves the same.
{
const err = doSomething()
if (err != null) {
return (null, err)
}
}
The extra braces define a new, uh, "lexical scope"? Which means I can use const
, and err
isn't available to the outer block.
You want the :checkbox:checked
selector and map
to create an array of the values:
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked')
, or for a common name $('input[name="Foo"]:checked')
- Update -
If you don't need IE support then you can now make the map()
call more succinct by using an arrow function:
var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();