You may probably do this way
var currentMonth = new Date().getMonth();
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
for(var i = currentMonth-1 ; i<= 4; i++){
console.log(monthNames[i])// make it as an array of objects here
}
Iterable is a generic interface. A problem you might be having (you haven't actually said what problem you're having, if any) is that if you use a generic interface/class without specifying the type argument(s) you can erase the types of unrelated generic types within the class. An example of this is in Non-generic reference to generic class results in non-generic return types.
So I would at least change it to:
public class ProfileCollection implements Iterable<Profile> {
private ArrayList<Profile> m_Profiles;
public Iterator<Profile> iterator() {
Iterator<Profile> iprof = m_Profiles.iterator();
return iprof;
}
...
public Profile GetActiveProfile() {
return (Profile)m_Profiles.get(m_ActiveProfile);
}
}
and this should work:
for (Profile profile : m_PC) {
// do stuff
}
Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:
for (Object profile : m_PC) {
// do stuff
}
This is a pretty obscure corner case of Java generics.
If not, please provide some more info about what's going on.
First you should check if books
itself isn't null, then simply check whether books[i] != null
:
if(books==null) throw new IllegalArgumentException();
for (int i = 0; i < books.length; i++){
if(books[i] != null){
total += books[i].getPrice();
}
}
Long after accept answer.
Use sprintf()
, or related functions, as many others have answers suggested, but use a better format specifier.
Using "%.*e"
, code solves various issues:
The maximum buffer size needed is far more reasonable, like 18 for float
(see below). With "%f"
, sprintf(buf, "%f", FLT_MAX);
could need 47+. sprintf(buf, "%f", DBL_MAX);
may need 317+
Using ".*"
allows code to define the number of decimal places needed to distinguish a string version of float x
and it next highest float
. For deatils, see Printf width specifier to maintain precision of floating-point value
Using "%e"
allows code to distinguish small float
s from each other rather than all printing "0.000000"
which is the result when |x| < 0.0000005
.
Example usage
#include <float.h>
#define FLT_STRING_SIZE (1+1+1+(FLT_DECIMAL_DIG-1)+1+1+ 4 +1)
// - d . dddddddd e - dddd \0
char buf[FLT_STRING_SIZE];
sprintf(buf, "%.*e", FLT_DECIMAL_DIG-1, some_float);
Ideas:
IMO, better to use 2x buffer size for scratch pads like buf[FLT_STRING_SIZE*2]
.
For added robustness, use snprintf()
.
As a 2nd alterative consider "%.*g"
. It is like "%f"
for values exponentially near 1.0 and like "%e"
for others.
You use the Python 2 docs but write your program in Python 3.
A standard prolog predicate will do this.
isfive(5).
will evaluate to true if you call it with 5 and fail(return false) if you run it with anything else. For not equal you use \=
isNotEqual(A,B):- A\=B.
Technically it is does not unify, but it is similar to not equal.
Learn Prolog Now is a good website for learning prolog.
Edit: To add another example.
isEqual(A,A).
the conversion from 1970,1,1 needs the double rounded to zero decimal places i thinks
DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return Math.Round( ts.TotalMilliseconds,0);
on the client side i use
new Date(+data.replace(/\D/g, ''));
There are many good answers here, but I would like to point out that they can be extended very simply to achieve a lot more complex sorting. The only thing you have to do is to use the OR operator to chain comparision functions like this:
objs.sort((a,b)=> fn1(a,b) || fn2(a,b) || fn3(a,b) )
Where fn1
, fn2
, ... are the sort functions which return [-1,0,1]. This results in "sorting by fn1", "sorting by fn2" which is pretty much equal to ORDER BY in SQL.
This solution is based on the behaviour of ||
operator which evaluates to the first evaluated expression which can be converted to true.
The simplest form has only one inlined function like this:
// ORDER BY last_nom
objs.sort((a,b)=> a.last_nom.localeCompare(b.last_nom) )
Having two steps with last_nom
,first_nom
sort order would look like this:
// ORDER_BY last_nom, first_nom
objs.sort((a,b)=> a.last_nom.localeCompare(b.last_nom) ||
a.first_nom.localeCompare(b.first_nom) )
A generic comparision function could be something like this:
// ORDER BY <n>
let cmp = (a,b,n)=>a[n].localeCompare(b[n])
This function could be extended to support numeric fields, case sensitity, arbitary datatypes etc.
You can them use it with chaining them by sort priority:
// ORDER_BY last_nom, first_nom
objs.sort((a,b)=> cmp(a,b, "last_nom") || cmp(a,b, "first_nom") )
// ORDER_BY last_nom, first_nom DESC
objs.sort((a,b)=> cmp(a,b, "last_nom") || -cmp(a,b, "first_nom") )
// ORDER_BY last_nom DESC, first_nom DESC
objs.sort((a,b)=> -cmp(a,b, "last_nom") || -cmp(a,b, "first_nom") )
The point here is that pure JavaScript with functional approach can take you a long way without external libraries or complex code. It is also very effective, since no string parsing have to be done
Generally on Android, if you simply display the phone number, and the user taps on it, it will pull it up in the dialer. So, you could simply do
For more information, call us at <b>416-555-1234</b>
When the user taps on the bold part, since it's formatted like a phone number, the dialer will pop up, and show 4165551234
in the phone number field. The user then just has to hit the call button.
You might be able to do
For more information, call us at <a href='tel:416-555-1234'>416-555-1234</a>
to cover both devices, but I'm not sure how well this would work. I'll give it a try shortly and let you know.
EDIT: I just gave this a try on my HTC Magic running a rooted Rogers 1.5 with SenseUI:
For more information, call us at <a href='tel:416-555-1234'>416-555-1234</a><br />
<br />
Call at <a href='tel:416-555-1234'>our number</a>
<br />
<br />
<a href='416-555-1234'>Blah</a>
<br />
<br />
For more info, call <b>416-555-1234</b>
The first one, surrounding with the link and printing the phone number, worked perfectly. Pulled up the dialer with the hyphens and all. The second, saying our number
with the link, worked exactly the same. This means that using <a href='tel:xxx-xxx-xxxx'>
should work across the board, but I wouldn't suggest taking my one test as conclusive.
Linking straight to the number did the expected: Tried to pull up the nonexistent file from the server.
The last one did as I mentioned above, and pulled up the dialer, but without the nice formatting hyphens.
for example I faced this in express node.js when trying to create route for paths not starting with /internal
app.get(`\/(?!internal).*`, (req, res)=>{
and after long trying it just worked when passing it as a RegExp Object using new RegExp()
app.get(new RegExp("\/(?!internal).*"), (req, res)=>{
this may help if you are getting this common issue in routing
Try adding this to your css
.form { width:985px; margin:0 auto }
and add width:100% to the body tag
Then put:
<div class="form">
before the tag.
I used to do this a lot when I worked with Classic ASP. Usually I used it when server-side validation was needed of some sort for the input (before the days of AJAX). The main draw back I see is that it doesn't separate programming logic from the presentation, at the file level.
Wrap the image in a div
with dimensions 64x64 and set width: inherit
to the image:
<div style="width: 64px; height: 64px;">
<img src="Runtime path" style="width: inherit" />
</div>
#!/bin/bash
START=$(date +%s)
# do something
# start your script work here
ls -R /etc > /tmp/x
rm -f /tmp/x
# your logic ends here
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "It took $DIFF seconds"
Python(the interpreter) is compiled.
Proof: It won't even compile your code if it contains syntax error.
Example 1:
print("This should print")
a = 9/0
Output:
This should print
Traceback (most recent call last):
File "p.py", line 2, in <module>
a = 9/0
ZeroDivisionError: integer division or modulo by zero
Code gets compiled successfully. First line gets executed (
ZeroDivisionError
(run time error) .
Example 2:
print("This should not print")
/0
Output:
File "p.py", line 2
/0
^
SyntaxError: invalid syntax
Conclusion: If your code file contains
SyntaxError
nothing will execute as compilation fails.
Try using toDegrees="359"
since 360° and 0° are the same.
I tried several jquery based custom select with images, but none worked in responsive layouts. Finally i came accross Bootstrap-Select. After some modifications i was able to produce this code.
SELECT id, amount
FROM report
WHERE type='P'
UNION
SELECT id, (amount * -1) AS amount
FROM report
WHERE type = 'N'
ORDER BY id;
I guess that what you want to do is an UNION
of both tables.
If both tables have the same columns then you can just do
SELECT category_id, col1, col2, col3
FROM items_a
UNION
SELECT category_id, col1, col2, col3
FROM items_b
Else, you might have to do something like
SELECT category_id, col1, col2, col3
FROM items_a
UNION
SELECT category_id, col_1 as col1, col_2 as col2, col_3 as col3
FROM items_b
With Matlab 2014b python libraries can be called directly from matlab. A prefix py.
is added to all packet names:
>> wrapped = py.textwrap.wrap("example")
wrapped =
Python list with no properties.
['example']
I use ubuntu 18.04, and it was actually permission issue in my local machine. The issue was gone when I set read/write permission to my .git folder.
I've found this works well as a conditional within page.php
that includes the WooCommerce cart and checkout screens.
!is_page(array('cart', 'checkout'))
There's no fast way to retrieve attributes. But code ought to look like this (credit to Aaronaught):
var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var hasIsIdentity = Attribute.IsDefined(pi, typeof(IsIdentity));
If you need to retrieve attribute properties then
var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var attr = (IsIdentity[])pi.GetCustomAttributes(typeof(IsIdentity), false);
if (attr.Length > 0) {
// Use attr[0], you'll need foreach on attr if MultiUse is true
}
You are comparing strings. If an arguments are omitted, %1
expands to a blank so the commands become IF =="-b" GOTO SPECIFIC
for example (which is a syntax error). Wrap your strings in quotes (or square brackets).
REM this is ok
IF [%1]==[/?] GOTO BLANK
REM I'd recommend using quotes exclusively
IF "%1"=="-b" GOTO SPECIFIC
IF NOT "%1"=="-b" GOTO UNKNOWN
Once I encounterred a build which could not be stopped by the "Script Console". Finally I solved the problem with these steps:
ssh onto the jenkins server
cd to .jenkins/jobs/<job-name>/builds/
rm -rf <build-number>
restart jenkins
To make things simple , please note that every time you do itr2.next()
the pointer moves to the next element i.e. here if you notice carefully, then the output is perfectly fine according to the logic you have written .
This may help you in understanding better:
1st Iteration of While loop(pointer is before the 1st element):
Key: if ,value: 2 {itr2.next()=if; m.get(itr2.next()=it)=>2}
2nd Iteration of While loop(pointer is before the 3rd element):
Key: is ,value: 2 {itr2.next()=is; m.get(itr2.next()=to)=>2}
3rd Iteration of While loop(pointer is before the 5th element):
Key: be ,value: 1 {itr2.next()="be"; m.get(itr2.next()="up")=>"1"}
4th Iteration of While loop(pointer is before the 7th element):
Key: me ,value: 1 {itr2.next()="me"; m.get(itr2.next()="delegate")=>"1"}
Key: if ,value: 1
Key: it ,value: 2
Key: is ,value: 2
Key: to ,value: 2
Key: be ,value: 1
Key: up ,value: 1
Key: me ,value: 1
Key: delegate ,value: 1
It prints:
Key: if ,value: 2
Key: is ,value: 2
Key: be ,value: 1
Key: me ,value: 1
In WampServer
Open WampServer Tray icon ----> Apache ---> Apache Modules --->rewrite_module
To get nth highest salary you need to first sort data by using ORDER BY
and then select the nth highest record using LIMIT
with OFFSET
.
SELECT DISTINCT(salary) AS salary
FROM tbl_salary
ORDER BY salary DESC
LIMIT 1 OFFSET (n - 1);
Here's my salt :
current = datetime.datetime(mydate.year, mydate.month, 1)
next_month = datetime.datetime(mydate.year + int(mydate.month / 12), ((mydate.month % 12) + 1), 1)
Quick and easy :)
The easy way is by using sprintf
. I know others have suggested itoa
, but a) it isn't part of the standard library, and b) sprintf
gives you formatting options that itoa
doesn't.
not sure if it'll work in your scenario, but try adding the following to your web.config
under <system.web>
:
<system.web>
<customErrors mode="Off" />
...
</system.web>
works in my instance.
also see:
Using an absolute or relative string as the filename.
name_of_file = input("What is the name of the file: ")
completeName = '/home/user/Documents'+ name_of_file + ".txt"
file1 = open(completeName , "w")
toFile = input("Write what you want into the field")
file1.write(toFile)
file1.close()
This is an old question, but is high ranked on Google. I almost can't believe on the highest voted answers, because running a node.js process inside a screen session, with the &
or even with the nohup
flag -- all of them -- are just workarounds.
Specially the screen/tmux solution, which should really be considered an amateur solution. Screen and Tmux are not meant to keep processes running, but for multiplexing terminal sessions. It's fine, when you are running a script on your server and want to disconnect. But for a node.js server your don't want your process to be attached to a terminal session. This is too fragile. To keep things running you need to daemonize the process!
There are plenty of good tools to do that.
PM2: http://pm2.keymetrics.io/
# basic usage
$ npm install pm2 -g
$ pm2 start server.js
# you can even define how many processes you want in cluster mode:
$ pm2 start server.js -i 4
# you can start various processes, with complex startup settings
# using an ecosystem.json file (with env variables, custom args, etc):
$ pm2 start ecosystem.json
One big advantage I see in favor of PM2 is that it can generate the system startup script to make the process persist between restarts:
$ pm2 startup [platform]
Where platform
can be ubuntu|centos|redhat|gentoo|systemd|darwin|amazon
.
forever.js: https://github.com/foreverjs/forever
# basic usage
$ npm install forever -g
$ forever start app.js
# you can run from a json configuration as well, for
# more complex environments or multi-apps
$ forever start development.json
Init scripts:
I'm not go into detail about how to write a init script, because I'm not an expert in this subject and it'd be too long for this answer, but basically they are simple shell scripts, triggered by OS events. You can read more about this here
Docker:
Just run your server in a Docker container with -d
option and, voilá, you have a daemonized node.js server!
Here is a sample Dockerfile (from node.js official guide):
FROM node:argon
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install
# Bundle app source
COPY . /usr/src/app
EXPOSE 8080
CMD [ "npm", "start" ]
Then build your image and run your container:
$ docker build -t <your username>/node-web-app .
$ docker run -p 49160:8080 -d <your username>/node-web-app
Hope this helps somebody landing on this page. Always use the proper tool for the job. It'll save you a lot of headaches and over hours!
Another option is not to start the async task until the dialog is attached to the window by overriding onAttachedToWindow() on the dialog, that way it is always dismissible.
I ended up fixing our Ubuntu 18.04 / Apache 2.4.29 / PHP 7.2 install for Chrome 80 by installing mod_headers:
a2enmod headers
Adding the following directive to our Apache VirtualHost configurations:
Header edit Set-Cookie ^(.*)$ "$1; Secure; SameSite=None"
And restarting Apache:
service apache2 restart
In reviewing the docs (http://www.balkangreenfoundation.org/manual/en/mod/mod_headers.html) I noticed the "always" condition has certain situations where it does not work from the same pool of response headers. Thus not using "always" is what worked for me with PHP but the docs suggest that if you want to cover all your bases you could add the directive both with and without "always". I have not tested that.
If you are using a Linux server, you can use
exec("nohup $php_path path/script.php > /dev/null 2>/dev/null &")
If you need pass some args
exec("nohup $php_path path/script.php $args > /dev/null 2>/dev/null &")
In script.php
$args = $argv[1];
Or use Symfony https://symfony.com/doc/current/components/process.html
$process = Process::fromShellCommandline("php ".base_path('script.php'));
$process->setTimeout(0);
$process->disableOutput();
$process->start();
You can also use ngrok: https://ngrok.com/. I use it all the time to have a public server running on my localhost. Hope this helps.
Another options which even provides your own custom domain for free are serveo.net and https://localtunnel.github.io/www/
There are a few yet to be mentioned techniques available for you. Start with setting the contentType property in your ajax params.
Building on pradeek's example:
$('form').submit(function (e) {
var data;
data = new FormData();
data.append('file', $('#file')[0].files[0]);
$.ajax({
url: 'http://hacheck.tel.fer.hr/xml.pl',
data: data,
processData: false,
type: 'POST',
// This will override the content type header,
// regardless of whether content is actually sent.
// Defaults to 'application/x-www-form-urlencoded'
contentType: 'multipart/form-data',
//Before 1.5.1 you had to do this:
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("multipart/form-data");
}
},
// Now you should be able to do this:
mimeType: 'multipart/form-data', //Property added in 1.5.1
success: function (data) {
alert(data);
}
});
e.preventDefault();
});
In some cases when forcing jQuery ajax to do non-expected things, the beforeSend
event is a great place to do it. For a while people were using beforeSend
to override the mimeType before that was added into jQuery in 1.5.1. You should be able to modify just about anything on the jqXHR object in the before send event.
The Best Solution is to use Android Emulator with Intel Virtualization Technology.
Now if your system have a Processor that have a feature called as Intel Virtualization Technology, then Intel X86 images will be huge benefit for you. because it supports Intel® Hardware Accelerated Execution Manager (Intel® HAXM).
To check that your processor support HAXM or not : Click Here
You need to manually install the Intel HAXM in your system. Follow these steps for that.
Hope it will be helpful for you. :) Thanks.
Just complementing: It's kind of obvious, but you can use static imports to give you a hand, like this:
import static javax.swing.JOptionPane.*;
public class SimpleDialog(){
public static void main(String argv[]) {
showMessageDialog(null, "Message", "Title", ERROR_MESSAGE);
}
}
you can also use
word-break: break-all;
when nothing seems working this works always ;)
It's possible that the Windows internal resolver is adding '.local' to the domain name because there's no dots in it. nslookup
wouldn't do that.
To verify this possiblity, install 'Wireshark' (previously aka Ethereal) on your client machine and observe any DNS request packets leaving it when you run the ping
command.
OK, further investigation on my own XP machine at home reveals that for single label names (i.e. "foo", or "foo.") the system doesn't use DNS at all, and instead uses NBNS (NetBios Name Service).
Using a hint found at http://www.chicagotech.net/netforums/viewtopic.php?t=1476, I found that I was able to force DNS lookups for single label domains by putting a single entry reading "." in the "Append these DNS suffixes (in order)" in the "Advanced TCP/IP settings" dialog
I had this problem and then found these pages: Here you can see that apache library is deprecated, but it's not removed, so it should work. It doesn't.
See.
And here you can see how to include apache library to your project
See.
I resolved problem by adding following to my build.gradle file as recommended in second link.
android {
useLibrary 'org.apache.http.legacy'
}
However this only works if you are using gradle 1.3.0-beta2 or greater, so you will have to add this to buildscript dependencies if you are on a lower version:
classpath 'com.android.tools.build:gradle:1.3.0-beta2'
Hope this helps.
In my case, with Swift 4.2 you can use:
Disable vertical scroll:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollView.contentOffset.y = 0.0
}
Disable horizontal scroll:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollView.contentOffset.x = 0.0
}
The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.
Also, I didn't understand when the accepted answer said "it defaults to node server.js
". I think the documentation clarifies the default behavior:
npm-start
Start a package
Synopsis
npm start [-- <args>]
Description
This runs an arbitrary command specified in the package's "
start
" property of its "scripts
" object. If no "start
" property is specified on the "scripts
" object, it will runnode server.js
.
In summary, running npm start
could do one of two things:
npm start {command_name}
: Run an arbitrary command (i.e. if such command is specified in the start
property of package.json's scripts
object)npm start
: Else if no start
property exists (or no command_name
is passed): Run node server.js
, (which may not be appropriate, for example the OP doesn't have server.js
; the OP runs node
app.js
)package.json
in the directory where you run npm start
, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'
Commonly, each translation unit will generate an object file that contains the definitions of the symbols defined in that translation unit. To use those symbols, you have to link against those object files.
Under gcc you would specify all object files that are to be linked together in the command line, or compile the implementation files together.
g++ -o test objectFile1.o objectFile2.o -lLibraryName
The libraryName
here is just the bare name of the library, without platform-specific additions. So e.g. on Linux library files are usually called libfoo.so
but you'd only write -lfoo
. On Windows that same file might be called foo.lib
, but you'd use the same argument. You might have to add the directory where those files can be found using -L‹directory›
. Make sure to not write a space after -l
or -L
.
For XCode: Add the User Header Search Paths -> add the Library Search Path -> drag and drop the actual library reference into the project folder.
Under MSVS, files added to a project automatically have their object files linked together and a lib
file would be generated (in common usage). To use the symbols in a separate project, you'd
need to include the lib
files in the project settings. This is done in the Linker section of the project properties, in Input -> Additional Dependencies
. (the path to the lib
file should be
added in Linker -> General -> Additional Library Directories
) When using a third-party library that is provided with a lib
file, failure to do so usually results in the error.
It can also happen that you forget to add the file to the compilation, in which case the object file won't be generated. In gcc you'd add the files to the command line. In MSVS adding the file to the project will make it compile it automatically (albeit files can, manually, be individually excluded from the build).
In Windows programming, the tell-tale sign that you did not link a necessary library is that the name of the unresolved symbol begins with __imp_
. Look up the name of the function in the documentation, and it should say which library you need to use. For example, MSDN puts the information in a box at the bottom of each function in a section called "Library".
Not the place to give a complete tutorial, but here it is in short;
RewriteCond basically means "execute the next RewriteRule only if this is true". The !-l
path is the condition that the request is not for a link (!
means not, -l
means link)
The RewriteRule basically means that if the request is done that matches ^(.+)$
(matches any URL except the server root), it will be rewritten as index.php?url=$1
which means a request for olle
will be rewritten as index.php?url=olle
).
QSA
means that if there's a query string passed with the original URL, it will be appended to the rewrite (olle?p=1
will be rewritten as index.php?url=olle&p=1
.
L
means if the rule matches, don't process any more RewriteRules below this one.
For more complete info on this, follow the links above. The rewrite support can be a bit hard to grasp, but there are quite a few examples on stackoverflow to learn from.
This works really well for me:
.image-upload>input {_x000D_
display: none;_x000D_
}
_x000D_
<div class="image-upload">_x000D_
<label for="file-input">_x000D_
<img src="https://icon-library.net/images/upload-photo-icon/upload-photo-icon-21.jpg"/>_x000D_
</label>_x000D_
_x000D_
<input id="file-input" type="file" />_x000D_
</div>
_x000D_
Basically the for attribute of the label makes it so that clicking the label is the same as clicking the specified input.
Also, the display property set to none makes it so that the file input isn't rendered at all, hiding it nice and clean.
Tested in Chrome but according to the web should work on all major browsers. :)
EDIT: Added JSFiddle here: https://jsfiddle.net/c5s42vdz/
Ctrl+K, Ctrl+1 and then Ctrl+K, Ctrl+2 will do close to what you want.
The first command collapses level 1 (usually classes), and the second command collapses level 2 (usually methods).
You might even find it useful to skip the first command.
The first and the last, at least, are possible using the following syntax:
String.Format("{0,20}", "String goes here");
String.Format("{0,-20}", "String goes here");
The concept was clear to me after going over above posts. But there were some lingering questions. So, I wrote this small piece of code.
When we try to give a semaphore without taking it, it goes through. But, when you try to give a mutex without taking it, it fails. I tested this on a Windows platform. Enable USE_MUTEX to run the same code using a MUTEX.
#include <stdio.h>
#include <windows.h>
#define xUSE_MUTEX 1
#define MAX_SEM_COUNT 1
DWORD WINAPI Thread_no_1( LPVOID lpParam );
DWORD WINAPI Thread_no_2( LPVOID lpParam );
HANDLE Handle_Of_Thread_1 = 0;
HANDLE Handle_Of_Thread_2 = 0;
int Data_Of_Thread_1 = 1;
int Data_Of_Thread_2 = 2;
HANDLE ghMutex = NULL;
HANDLE ghSemaphore = NULL;
int main(void)
{
#ifdef USE_MUTEX
ghMutex = CreateMutex( NULL, FALSE, NULL);
if (ghMutex == NULL)
{
printf("CreateMutex error: %d\n", GetLastError());
return 1;
}
#else
// Create a semaphore with initial and max counts of MAX_SEM_COUNT
ghSemaphore = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL);
if (ghSemaphore == NULL)
{
printf("CreateSemaphore error: %d\n", GetLastError());
return 1;
}
#endif
// Create thread 1.
Handle_Of_Thread_1 = CreateThread( NULL, 0,Thread_no_1, &Data_Of_Thread_1, 0, NULL);
if ( Handle_Of_Thread_1 == NULL)
{
printf("Create first thread problem \n");
return 1;
}
/* sleep for 5 seconds **/
Sleep(5 * 1000);
/*Create thread 2 */
Handle_Of_Thread_2 = CreateThread( NULL, 0,Thread_no_2, &Data_Of_Thread_2, 0, NULL);
if ( Handle_Of_Thread_2 == NULL)
{
printf("Create second thread problem \n");
return 1;
}
// Sleep for 20 seconds
Sleep(20 * 1000);
printf("Out of the program \n");
return 0;
}
int my_critical_section_code(HANDLE thread_handle)
{
#ifdef USE_MUTEX
if(thread_handle == Handle_Of_Thread_1)
{
/* get the lock */
WaitForSingleObject(ghMutex, INFINITE);
printf("Thread 1 holding the mutex \n");
}
#else
/* get the semaphore */
if(thread_handle == Handle_Of_Thread_1)
{
WaitForSingleObject(ghSemaphore, INFINITE);
printf("Thread 1 holding semaphore \n");
}
#endif
if(thread_handle == Handle_Of_Thread_1)
{
/* sleep for 10 seconds */
Sleep(10 * 1000);
#ifdef USE_MUTEX
printf("Thread 1 about to release mutex \n");
#else
printf("Thread 1 about to release semaphore \n");
#endif
}
else
{
/* sleep for 3 secconds */
Sleep(3 * 1000);
}
#ifdef USE_MUTEX
/* release the lock*/
if(!ReleaseMutex(ghMutex))
{
printf("Release Mutex error in thread %d: error # %d\n", (thread_handle == Handle_Of_Thread_1 ? 1:2),GetLastError());
}
#else
if (!ReleaseSemaphore(ghSemaphore,1,NULL) )
{
printf("ReleaseSemaphore error in thread %d: error # %d\n",(thread_handle == Handle_Of_Thread_1 ? 1:2), GetLastError());
}
#endif
return 0;
}
DWORD WINAPI Thread_no_1( LPVOID lpParam )
{
my_critical_section_code(Handle_Of_Thread_1);
return 0;
}
DWORD WINAPI Thread_no_2( LPVOID lpParam )
{
my_critical_section_code(Handle_Of_Thread_2);
return 0;
}
The very fact that semaphore lets you signal "it is done using a resource", even though it never owned the resource, makes me think there is a very loose coupling between owning and signaling in the case of semaphores.
In javascript you can use
s3.listObjects(params, function (err, result) {});
to get all objects inside bucket. you have to pass bucket name inside params (Bucket: name).
Try this code:-
var input string
func main() {
fmt.Print("Enter Your Name=")
fmt.Scanf("%s",&input)
fmt.Println("Hello "+input)
}
Not possible, but the layout folder is sorted by name. So, I prepend the layout file names with my package names. E.g. for the two packages "buying" and "playing":
buying_bought_tracks.xml
buying_buy_tracks.xml
playing_edit_playlist.xml
playing_play_playlist.xml
playing_show_playlists.xml
A variable that shows caps lock state:
let isCapsLockOn = false;
document.addEventListener( 'keydown', function( event ) {
var caps = event.getModifierState && event.getModifierState( 'CapsLock' );
if(isCapsLockOn !== caps) isCapsLockOn = caps;
});
document.addEventListener( 'keyup', function( event ) {
var caps = event.getModifierState && event.getModifierState( 'CapsLock' );
if(isCapsLockOn !== caps) isCapsLockOn = caps;
});
works on all browsers => canIUse
For me I had rename from
[Database_LS].[schema].[TableView]
to
[Database_LS].[Database].[schema].[TableView]
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
/* The customcheck */_x000D_
.customcheck {_x000D_
display: block;_x000D_
position: relative;_x000D_
padding-left: 35px;_x000D_
margin-bottom: 12px;_x000D_
cursor: pointer;_x000D_
font-size: 22px;_x000D_
-webkit-user-select: none;_x000D_
-moz-user-select: none;_x000D_
-ms-user-select: none;_x000D_
user-select: none;_x000D_
}_x000D_
_x000D_
/* Hide the browser's default checkbox */_x000D_
.customcheck input {_x000D_
position: absolute;_x000D_
opacity: 0;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
/* Create a custom checkbox */_x000D_
.checkmark {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 25px;_x000D_
width: 25px;_x000D_
background-color: #eee;_x000D_
border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* On mouse-over, add a grey background color */_x000D_
.customcheck:hover input ~ .checkmark {_x000D_
background-color: #ccc;_x000D_
}_x000D_
_x000D_
/* When the checkbox is checked, add a blue background */_x000D_
.customcheck input:checked ~ .checkmark {_x000D_
background-color: #02cf32;_x000D_
border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* Create the checkmark/indicator (hidden when not checked) */_x000D_
.checkmark:after {_x000D_
content: "";_x000D_
position: absolute;_x000D_
display: none;_x000D_
}_x000D_
_x000D_
/* Show the checkmark when checked */_x000D_
.customcheck input:checked ~ .checkmark:after {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
/* Style the checkmark/indicator */_x000D_
.customcheck .checkmark:after {_x000D_
left: 9px;_x000D_
top: 5px;_x000D_
width: 5px;_x000D_
height: 10px;_x000D_
border: solid white;_x000D_
border-width: 0 3px 3px 0;_x000D_
-webkit-transform: rotate(45deg);_x000D_
-ms-transform: rotate(45deg);_x000D_
transform: rotate(45deg);_x000D_
}
_x000D_
<div class="container">_x000D_
<h1>Custom Checkboxes</h1></br>_x000D_
_x000D_
<label class="customcheck">One_x000D_
<input type="checkbox" checked="checked">_x000D_
<span class="checkmark"></span>_x000D_
</label>_x000D_
<label class="customcheck">Two_x000D_
<input type="checkbox">_x000D_
<span class="checkmark"></span>_x000D_
</label>_x000D_
<label class="customcheck">Three_x000D_
<input type="checkbox">_x000D_
<span class="checkmark"></span>_x000D_
</label>_x000D_
<label class="customcheck">Four_x000D_
<input type="checkbox">_x000D_
<span class="checkmark"></span>_x000D_
</label>_x000D_
</div>
_x000D_
@ubuntu 18.04
sudo apt install openjdk-8-jdk
then
sudo update-alternatives --config java
Selection Path Priority Status
------------------------------------------------------------
0 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1111 auto mode
1 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1111 manual mode
* 2 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1081 manual mode
Press <enter> to keep the current choice[*], or type selection number:
choose java 8 then restart netbeans
Done
If you can't find the clipboard, then close that excel sheet and reopen it again. This will solve your problem.
$getyear = explode("-", $value['users_dob']);
$dob = date('Y') - $getyear[0];
$value['users_dob']
is the database value with format yyyy-mm-dd
<select>
<option disabled selected>select your beverage</option>
<option >Tea</option>
<option>coffee</option>
<option>soda</option>
</select>
Simple solution without adding observer notification
-(void)setViewMovedUp:(BOOL)movedUp
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3]; // if you want to slide up the view
CGRect rect = self.view.frame;
if (movedUp)
{
// 1. move the view's origin up so that the text field that will be hidden come above the keyboard
// 2. increase the size of the view so that the area behind the keyboard is covered up.
rect.origin.y -= kOFFSET_FOR_KEYBOARD;
rect.size.height += kOFFSET_FOR_KEYBOARD;
}
else
{
// revert back to the normal state.
rect.origin.y += kOFFSET_FOR_KEYBOARD;
rect.size.height -= kOFFSET_FOR_KEYBOARD;
}
self.view.frame = rect;
[UIView commitAnimations];
}
-(void)textFieldDidEndEditing:(UITextField *)sender
{
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:NO];
}
}
-(void)textFieldDidBeginEditing:(UITextField *)sender
{
//move the main view, so that the keyboard does not hide it.
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
}
Where
#define kOFFSET_FOR_KEYBOARD 80.0
public static void mulptiTransfer(WebDriver driver, By dropdownID, String text, By to)
{
String valuetext = null;
WebElement element = locateElement(driver, dropdownID, 10);
Select select = new Select(element);
List<WebElement> options = element.findElements(By.tagName("option"));
for (WebElement value: options)
{
valuetext = value.getText();
if (valuetext.equalsIgnoreCase(text))
{
try
{
select.selectByVisibleText(valuetext);
locateElement(driver, to, 5).click();
break;
}
catch (Exception e)
{
System.out.println(valuetext + "Value not found in Dropdown to Select");
}
}
}
}
Updated list as of 6/11/2013
204.15.20.0/22
69.63.176.0/20
66.220.144.0/20
66.220.144.0/21
69.63.184.0/21
69.63.176.0/21
74.119.76.0/22
69.171.255.0/24
173.252.64.0/18
69.171.224.0/19
69.171.224.0/20
103.4.96.0/22
69.63.176.0/24
173.252.64.0/19
173.252.70.0/24
31.13.64.0/18
31.13.24.0/21
66.220.152.0/21
66.220.159.0/24
69.171.239.0/24
69.171.240.0/20
31.13.64.0/19
31.13.64.0/24
31.13.65.0/24
31.13.67.0/24
31.13.68.0/24
31.13.69.0/24
31.13.70.0/24
31.13.71.0/24
31.13.72.0/24
31.13.73.0/24
31.13.74.0/24
31.13.75.0/24
31.13.76.0/24
31.13.77.0/24
31.13.96.0/19
31.13.66.0/24
173.252.96.0/19
69.63.178.0/24
31.13.78.0/24
31.13.79.0/24
31.13.80.0/24
31.13.82.0/24
31.13.83.0/24
31.13.84.0/24
31.13.85.0/24
31.13.87.0/24
31.13.88.0/24
31.13.89.0/24
31.13.90.0/24
31.13.91.0/24
31.13.92.0/24
31.13.93.0/24
31.13.94.0/24
31.13.95.0/24
69.171.253.0/24
69.63.186.0/24
204.15.20.0/22
69.63.176.0/20
69.63.176.0/21
69.63.184.0/21
66.220.144.0/20
69.63.176.0/20
Here ready static class
import java.io.*;
import java.util.Properties;
public class Settings {
public static String Get(String name,String defVal){
File configFile = new File(Variables.SETTINGS_FILE);
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
reader.close();
return props.getProperty(name);
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
return defVal;
} catch (IOException ex) {
// I/O error
logger.error(ex);
return defVal;
} catch (Exception ex){
logger.error(ex);
return defVal;
}
}
public static Integer Get(String name,Integer defVal){
File configFile = new File(Variables.SETTINGS_FILE);
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
reader.close();
return Integer.valueOf(props.getProperty(name));
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
return defVal;
} catch (IOException ex) {
// I/O error
logger.error(ex);
return defVal;
} catch (Exception ex){
logger.error(ex);
return defVal;
}
}
public static Boolean Get(String name,Boolean defVal){
File configFile = new File(Variables.SETTINGS_FILE);
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
reader.close();
return Boolean.valueOf(props.getProperty(name));
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
return defVal;
} catch (IOException ex) {
// I/O error
logger.error(ex);
return defVal;
} catch (Exception ex){
logger.error(ex);
return defVal;
}
}
public static void Set(String name, String value){
File configFile = new File(Variables.SETTINGS_FILE);
try {
Properties props = new Properties();
FileReader reader = new FileReader(configFile);
props.load(reader);
props.setProperty(name, value.toString());
FileWriter writer = new FileWriter(configFile);
props.store(writer, Variables.SETTINGS_COMMENT);
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
} catch (IOException ex) {
// I/O error
logger.error(ex);
} catch (Exception ex){
logger.error(ex);
}
}
public static void Set(String name, Integer value){
File configFile = new File(Variables.SETTINGS_FILE);
try {
Properties props = new Properties();
FileReader reader = new FileReader(configFile);
props.load(reader);
props.setProperty(name, value.toString());
FileWriter writer = new FileWriter(configFile);
props.store(writer,Variables.SETTINGS_COMMENT);
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
} catch (IOException ex) {
// I/O error
logger.error(ex);
} catch (Exception ex){
logger.error(ex);
}
}
public static void Set(String name, Boolean value){
File configFile = new File(Variables.SETTINGS_FILE);
try {
Properties props = new Properties();
FileReader reader = new FileReader(configFile);
props.load(reader);
props.setProperty(name, value.toString());
FileWriter writer = new FileWriter(configFile);
props.store(writer,Variables.SETTINGS_COMMENT);
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
} catch (IOException ex) {
// I/O error
logger.error(ex);
} catch (Exception ex){
logger.error(ex);
}
}
}
Here sample:
Settings.Set("valueName1","value");
String val1=Settings.Get("valueName1","value");
Settings.Set("valueName2",true);
Boolean val2=Settings.Get("valueName2",true);
Settings.Set("valueName3",100);
Integer val3=Settings.Get("valueName3",100);
Why not just use NSMutableAttributedString?
let attributedString = NSMutableAttributedString(string: "Want to learn iOS? Just visit developer.apple.com!")
attributedString.addAttribute(.link, value: "https://developer.apple.com", range: NSRange(location: 30, length: 50))
myView.attributedText = attributedString
You can find more details here
This worked for me:
hoja_trabajo.Cells[i + 2, j + 1] = fecha.ToString("dd-MMM-yyyy").Replace(".", "");
CsvHelper (a library I maintain) will read a CSV file into custom objects.
var csv = new CsvReader( File.OpenText( "file.csv" ) );
var myCustomObjects = csv.GetRecords<MyCustomObject>();
Sometimes you don't own the objects you're trying to read into. In this case, you can use fluent mapping because you can't put attributes on the class.
public sealed class MyCustomObjectMap : CsvClassMap<MyCustomObject>
{
public MyCustomObjectMap()
{
Map( m => m.Property1 ).Name( "Column Name" );
Map( m => m.Property2 ).Index( 4 );
Map( m => m.Property3 ).Ignore();
Map( m => m.Property4 ).TypeConverter<MySpecialTypeConverter>();
}
}
EDIT:
CsvReader now requires CultureInfo to be passed into the constuctor (https://github.com/JoshClose/CsvHelper/issues/1441).
Example:
var csv = new CsvReader(File.OpenText("file.csv"), System.Globalization.CultureInfo.CurrentCulture);
If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:
var items = (from x in parameters
join y in myStrings on x.Source equals y
select x)
.ToList();
If a bash script
If [[ $input -gt number || $input -lt number ]]
then
echo .........
else
echo .........
fi
exit
Here is how you do in Eloquent
$users = User::whereIn('id', array(1, 2, 3))->get();
And if you are using Query builder then :
$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();
Example of not very good, but simple decision (not only for Jackson, also for Spring RestTemplate, etc.):
Set<MyClass> res = new HashSet<>();
objectMapper.readValue(json, res.getClass());
if you have no systemctl and started the docker daemon by:
sudo service docker start
you can stop it by:
sudo service docker stop
When I wanted to use the standard XMLGregorianCalendar for my XML to object marshalling of DateTime in Java, I heard a lot of comments on how heavy weight and cumbersome it was to use it. I was trying to comtrol the XML fields in the xs:datetime structs to manage timezone, milliseconds, etc.
So I designed a utility to build an XMLGregorian calendar from a GregorianCalendar or java.util.Date.
Because of where I work I'm not allowed to share it online without legal, but here's an example of how a client uses it. It abstracts the details and filters some of the implementation of XMLGregorianCalendar that are less used for xs:datetime.
XMLGregorianCalendarBuilder builder = XMLGregorianCalendarBuilder.newInstance(jdkDate);
XMLGregorianCalendar xmlCalendar = builder.excludeMillis().excludeOffset().build();
Granted this pattern is more of a filter as it sets fields in the xmlCalendar as undefined so they are excluded, it still "builds" it. I've easily added other options to the builder to create an xs:date, and xs:time struct and also to manipulate timezone offsets when needed.
If you've ever seen code that creates and uses XMLGregorianCalendar, you would see how this made it much easier to manipulate.
It's very simple.
You create a css property to this image.
img { transition: all 0.3s ease-in-out 0s; }
You add an animation like that:
img:hover
{
cursor: default;
transform: rotate(360deg);
transition: all 0.3s ease-in-out 0s;
}
Using jQuery you can use contents()
. For example:
var inside = $('#one').contents();
When call add_subparsers
method save the first positional argument to dest=
and check value after argparse has been initialized, like this:
subparsers = parser.add_subparsers(dest='command')
And just check this this variable:
if not args.command:
parser.print_help()
parser.exit(1) # If exit() - exit code will be zero (no error)
Full example:
#!/usr/bin/env python
""" doc """
import argparse
import sys
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(dest='command',
help='List of commands')
list_parser = subparsers.add_parser('list',
help='List contents')
list_parser.add_argument('dir', action='store',
help='Directory to list')
create_parser = subparsers.add_parser('create',
help='Create a directory')
create_parser.add_argument('dirname', action='store',
help='New directory to create')
create_parser.add_argument('--read-only', default=False, action='store_true',
help='Set permissions to prevent writing to the directory')
args = parser.parse_args()
if not args.command:
parser.print_help()
parser.exit(1)
print(vars(args)) # For debug
I don't think what you really need is to close the menu when the user clicks outside; what you need is for the menu to close when the user clicks anywhere at all on the page. If you click on the menu, or off the menu it should close right?
Finding no satisfactory answers above prompted me to write this blog post the other day. For the more pedantic, there are a number of gotchas to take note of:
body { margin-left:auto; margin-right: auto; width:960px;}
In windows " wmic process where processid="pid of the process running" get commandline " worked for me. The culprit was wrapper.exe process of webhuddle jboss soft.
There is no limit to the number of elements that you are passing to IN clause. If there are more elements it will consider it as array and then for each scan in the database it will check if it is contained in the array or not. This approach is not so scalable. Instead of using IN clause try using INNER JOIN with temp table. Refer http://www.xaprb.com/blog/2006/06/28/why-large-in-clauses-are-problematic/ for more info. Using INNER JOIN scales well as query optimizer can make use of hash join and other optimization. Whereas with IN clause there is no way for the optimizer to optimize the query. I have noticed speedup of at least 2x with this change.
You missed some breaks there:
switch (searchType)
{
case "SearchBooks":
Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
break;
case "SearchAuthors":
Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
break;
}
Without them, the compiler thinks you're trying to execute the lines below case "SearchAuthors":
immediately after the lines under case "SearchBooks":
have been executed, which isn't allowed in C#.
By adding the break
statements at the end of each case, the program exits each case after it's done, for whichever value of searchType
.
Your TextView Attributes need to be something like,
<TextView ...
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|right" ../>
Now, Description why these need to be done,
android:layout_width="match_parent"
android:layout_height="match_parent"
Makes your TextView to match_parent
or fill_parent
if You don't want to be it like, match_parent
you have to give some specified values to layout_height
so it get space for vertical center gravity. android:layout_width="match_parent"
necessary because it align your TextView in Right side so you can recognize respect to Parent Layout of TextView.
Now, its about android:gravity
which makes the content of Your TextView alignment. android:layout_gravity
makes alignment of TextView respected to its Parent Layout.
Update:
As below comment says use fill_parent
instead of match_parent
. (Problem in some device.)
In the end you have to implement this around Enum.GetNames
:
public bool TryParseEnum<T>(string str, bool caseSensitive, out T value) where T : struct {
// Can't make this a type constraint...
if (!typeof(T).IsEnum) {
throw new ArgumentException("Type parameter must be an enum");
}
var names = Enum.GetNames(typeof(T));
value = (Enum.GetValues(typeof(T)) as T[])[0]; // For want of a better default
foreach (var name in names) {
if (String.Equals(name, str, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) {
value = (T)Enum.Parse(typeof(T), name);
return true;
}
}
return false;
}
Additional notes:
Enum.TryParse
is included in .NET 4. See here http://msdn.microsoft.com/library/dd991876(VS.100).aspxEnum.Parse
catching the exception thrown when it fails. This could be faster when a match is found, but will likely to slower if not. Depending on the data you are processing this may or may not be a net improvement.EDIT: Just seen a better implementation on this, which caches the necessary information: http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5
Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID
before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.
You have to nest the requests:
$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ obj = name; // sID is only now available! sID = obj.id; console.log(sID); });
name.id
is sufficient unless you really need the other variables outside the function.$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ // We don't need sID or obj here - name.id is sufficient console.log(name.id); doSecondRequest(name.id); }); /// TODO Choose a better name function doSecondRequest(sID) { $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){ console.log(stats); }); }
Hapy New Year :)
Compare value of phone2
with empty string:
select phone, phone2
from jewishyellow.users
where phone like '813%' and phone2<>''
Note that NULL
value is interpreted as false
.
cd
" to go to your home folder.touch .bash_profile
".open -e .bash_profile
" to open .bash_profile in TextEdit.alias mvn='/[Your file location]/apache-maven-x.x.x/bin/mvn'
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdkx.x.x_xx.jdk/Contents/Home/
(Make sure there are no speech marks or apostrophe's) 8. Make sure you fill the required data (ex your file location and version number).
. .bash_profile
" to reload .bash_profile and update any functions you add. (*make sure you separate the dots with a single space).mvn -version
If successful you should see the following:
Apache Maven 3.1.1
Maven home: /Users/admin/Maven/apache-maven-3.1.1
Java version: 1.7.0_51, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.9.1", arch: "x86_64", family: "mac"
To "remove" the 1st character point to the second character:
char mystr[] = "Nmy stringP";
char *p = mystr;
p++; /* 'N' is not in `p` */
To remove the last character replace it with a '\0'
.
p[strlen(p)-1] = 0; /* 'P' is not in `p` (and it isn't in `mystr` either) */
i use these three lines of code to print out the column names which contain at least one null value:
for column in dataframe:
if dataframe[column].isnull().any():
print('{0} has {1} null values'.format(column, dataframe[column].isnull().sum()))
When We Add First Fragment --> Second Fragment using add() method
btn_one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Click First
Fragment",Toast.LENGTH_LONG).show();
Fragment fragment = new SecondFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
// .replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
});
When we use add() in fragment
E/Keshav SecondFragment: onAttach
E/Keshav SecondFragment: onCreate
E/Keshav SecondFragment: onCreateView
E/Keshav SecondFragment: onActivityCreated
E/Keshav SecondFragment: onStart
E/Keshav SecondFragment: onResume
When we use replace() in fragment
going to first fragment to second fragment in First -->Second using replace() method
btn_one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Click First Fragment",Toast.LENGTH_LONG).show();
Fragment fragment = new SecondFragment();
getActivity().getSupportFragmentManager().beginTransaction()
// .add(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
});
E/Keshav SecondFragment: onAttach
E/Keshav SecondFragment: onCreate
E/Keshav FirstFragment: onPause -------------------------- FirstFragment
E/Keshav FirstFragment: onStop --------------------------- FirstFragment
E/Keshav FirstFragment: onDestroyView -------------------- FirstFragment
E/Keshav SecondFragment: onCreateView
E/Keshav SecondFragment: onActivityCreated
E/Keshav SecondFragment: onStart
E/Keshav SecondFragment: onResume
In case of Replace First Fragment these method is extra called ( onPause,onStop,onDestroyView is extra called )
E/Keshav FirstFragment: onPause
E/Keshav FirstFragment: onStop
E/Keshav FirstFragment: onDestroyView
create a package protected (assumes test class in same package) method in the sub class that calls the super class method and then call that method in your overridden sub class method. you can then set expectations on this method in your test through the use of the spy pattern. not pretty but certainly better than having to deal with all the expectation setting for the super method in your test
New project. Fixed this issue by clicking on "File->Sync Project with Gradle Files"
You can use zfill:
print str(1).zfill(2)
print str(10).zfill(2)
print str(100).zfill(2)
prints:
01
10
100
I like this solution, as it helps not only when outputting the number, but when you need to assign it to a variable... e.g. - x = str(datetime.date.today().month).zfill(2) will return x as '02' for the month of feb.
Ideally you need to have .d.ts
file for typings to let Linting
work.
But It seems that d3gauge
doesn't have one, you can Ask the developers to provide and hope they will listen.
Alternatively, you can solve this specific issue by doing this
declare var drawGauge: any;
import '../../../../js/d3gauge.js';
export class MemMonComponent {
createMemGauge() {
new drawGauge(this.opt); //drawGauge() is a function inside d3gauge.js
}
}
If you use it in multiple files, you can create a d3gauage.d.ts
file with the content below
declare var drawGauge: any;
and reference it in your boot.ts
(bootstrap) file at the top, like this
///<reference path="../path/to/d3gauage.d.ts"/>
I prefer using another library called Pechkin because it is able to convert non trivial HTML (that also has CSS classes). This is possible because this library uses the WebKit layout engine that is also used by browsers like Chrome and Safari.
I detailed on my blog my experience with Pechkin: http://codeutil.wordpress.com/2013/09/16/convert-html-to-pdf/
Thank you to all that have responded! I've tried all of the solutions presented here and I've done more searching on the internet for other possible solutions, and I think I've found one that's promising:
tr.top td {_x000D_
border-top: thin solid black;_x000D_
}_x000D_
_x000D_
tr.bottom td {_x000D_
border-bottom: thin solid black;_x000D_
}_x000D_
_x000D_
tr.row td:first-child {_x000D_
border-left: thin solid black;_x000D_
}_x000D_
_x000D_
tr.row td:last-child {_x000D_
border-right: thin solid black;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<table cellspacing="0">_x000D_
<tr>_x000D_
<td>no border</td>_x000D_
<td>no border here either</td>_x000D_
</tr>_x000D_
<tr class="top row">_x000D_
<td>one</td>_x000D_
<td>two</td>_x000D_
</tr>_x000D_
<tr class="bottom row">_x000D_
<td>three</td>_x000D_
<td>four</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan="2">once again no borders</td>_x000D_
</tr>_x000D_
<tr class="top bottom row">_x000D_
<td colspan="2">hello</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan="2">world</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Output:
Instead of having to add the top
, bottom
, left
, and right
classes to every <td>
, all I have to do is add top row
to the top <tr>
, bottom row
to the bottom <tr>
, and row
to every <tr>
in between. Is there anything wrong with this solution? Are there any cross-platform issues I should be aware of?
The cause of the issue is this, I already had Apache
web server installed and actively listening on port 80
on my local machine.
Apache
and Nginx
are the two major open-source high-performance web servers capable of handling diverse workloads to satisfy the needs of modern web demands. However, Apache
serves primarily as a HTTP server whereas Nginx
is a high-performance asynchronous web server and reverse proxy server.
The inability of Nginx
to start was because Apache
was already listening on port 80 as its default port, which is also the default port for Nginx
.
One quick workaround would be to stop Apache
server by running the command below
systemctl stop apache2
systemctl status apache2
And then starting up Nginx
server by running the command below
systemctl stop nginx
systemctl status nginx
However, this same issue will arise again when we try to start Apache
server again, since they both use port 80
as their default port.
Here's how I fixed it:
Run the command below to open the default configuration file of Nginx in Nano editor
sudo nano /etc/nginx/sites-available/default
When the file opens in Nano editor, scroll down and change the default server port to any port of your choice. For me, I chose to change it to port 85
# Default server configuration
#
server {
listen 85 default_server;
listen [::]:85 default_server;
Also, scroll down and change the virtual host port to any port of your choice. For me, I also chose to change it to port 85
# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
# server {
# listen 85;
# listen [::]:85;
Then save and exit the file by pressing on your keyboard:
Ctrl + S
Ctrl + X
You may still be prompted to press Y on your keyboard to save your changes.
Finally, confirm that your configuration is correct and restart the Nginx
server:
sudo nginx -t
sudo systemctl restart nginx
You can now navigate to localhost:nginx-port
(localhost:85
) on your browser to confirm the changes.
Displaying the default Nginx start page
If you want the default Nginx start page to show when you navigate to localhost:nginx-port
(localhost:85
) on your browser, then follow these steps:
Examine the directory /var/www/html/
which is the default root
directory for both Apache
and Nginx
by listing its contents:
cd ~
ls /var/www/html/
You will 2 files listed in the directory:
index.html # Apache default start page
index.nginx-debian.html # Nginx default start page
Run the command below to open the default configuration file of Nginx in Nano editor:
cd ~
sudo nano /etc/nginx/sites-available/default
Change the order of the index files in the root directory from this:
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
to this (putting the default Nginx start page - index.nginx-debian.html
in the 2nd position immediately after index
):
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.nginx-debian.html index.html index.htm;
Then save and exit the file by pressing on your keyboard:
Ctrl + S
Ctrl + X
You may still be prompted to press Y on your keyboard to save your changes.
Finally, confirm that your configuration is correct and restart the Nginx
server:
sudo nginx -t
sudo systemctl restart nginx
You can now navigate to localhost:nginx-port
(localhost:85
) on your browser to confirm the changes.
That's all.
I hope this helps
You have to resolve the conflict manually (copying the file over) and then commit the file (no matter if you copied it over or used the local version) like this
git commit -a -m "Fix merge conflict in test.foo"
Git normally autocommits after merging, but when it detects conflicts it cannot solve by itself, it applies all patches it figured out and leaves the rest for you to resolve and commit manually. The Git Merge Man Page, the Git-SVN Crash Course or this blog entry might shed some light on how it's supposed to work.
Edit: See the post below, you don't actually have to copy the files yourself, but can use
git checkout --ours -- path/to/file.txt
git checkout --theirs -- path/to/file.txt
to select the version of the file you want. Copying / editing the file will only be necessary if you want a mix of both versions.
Please mark mipadis answer as the correct one.
Leaving the action value blank will cause the form to post back to itself.
Try this:
...(to_date('2011/04/22 08:30:00', 'yyyy/mm/dd hh24:mi:ss'));
guys. I had the same problem before when I'm trying import a .aar package into my project, and unfortunately before make the .aar package as a module-dependence of my project, I had two modules (one about ROS-ANDROID-CV-BRIDGE, one is OPENCV-FOR-ANDROID) already. So, I got this error as you guys meet:
Error:Could not find method android() for arguments [org.ros.gradle_plugins.RosAndroidPlugin$_apply_closure2_closure4@7e550e0e] on project ‘:xxx’ of type org.gradle.api.Project.
So, it's the painful gradle-structure caused this problem when you have several modules in your project, and worse, they're imported in different way or have different types (.jar/.aar packages or just a project of Java library). And it's really a headache matter to make the configuration like compile-version, library dependencies etc. in each subproject compatible with the main-project.
I solved my problem just follow this steps:
? Copy .aar package in app/libs.
? Add this in app/build.gradle file:
repositories {
flatDir {
dirs 'libs' //this way we can find the .aar file in libs folder
}
}
? Add this in your add build.gradle file of the module which you want to apply the .aar dependence (in my situation, just add this in my app/build.gradle file):
dependencies {
compile(name:'package_name', ext:'aar')
}
So, if it's possible, just try export your module-dependence as a .aar package, and then follow this way import it to your main-project. Anyway, I hope this can be a good suggestion and would solve your problem if you have the same situation with me.
While doing my own server side JS experimentation I ended up using teajs. It conforms to common.js, is based on V8 AND is the only project that I know of that provides 'mod_teajs' apache server module.
In my opinion Node.js server is not production ready and lacks too many features - Apache is battle tested and the right way to do SSJS.
Be aware that the result may be slightly different than you expect.
NOW()
returns a DATETIME
.
And INTERVAL
works as named, e.g. INTERVAL 1 DAY = 24 hours
.
So if your script is cron'd to run at 03:00
, it will miss the first three hours of records from the 'oldest' day
.
To get the whole day use CURDATE() - INTERVAL 1 DAY
. This will get back to the beginning of the previous day regardless of when the script is run.
No As of now you can't do this by any command. You've to remove Manually from app.module.ts
and app.routing.module.ts
if you're using Angular 5
You need the return so the true/false gets passed up to the form's submit event (which looks for this and prevents submission if it gets a false).
Lets look at some standard JS:
function testReturn() { return false; }
If you just call that within any other code (be it an onclick handler or in JS elsewhere) it will get back false, but you need to do something with that value.
...
testReturn()
...
In that example the return value is coming back, but nothing is happening with it. You're basically saying execute this function, and I don't care what it returns. In contrast if you do this:
...
var wasSuccessful = testReturn();
...
then you've done something with the return value.
The same applies to onclick handlers. If you just call the function without the return in the onsubmit, then you're saying "execute this, but don't prevent the event if it return false." It's a way of saying execute this code when the form is submitted, but don't let it stop the event.
Once you add the return, you're saying that what you're calling should determine if the event (submit) should continue.
This logic applies to many of the onXXXX events in HTML (onclick, onsubmit, onfocus, etc).
Within Spring Boot 2.4 it is
sec:authorize="hasAnyRole('ROLE_ADMIN')
Ensure that you have
thymeleaf-extras-springsecurity5
in your dependencies. Also make sure that you include the namespace
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
in your html...
Use \overleftarrow
to create a long arrow to the left.
\overleftarrow{blahblahblah}
You can use EL if you want to work as IF:
<h:outputLabel value="#{row==10? '10' : '15'}"/>
Changing styles or classes:
style="#{test eq testMB.test? 'font-weight:bold' : 'font-weight:normal'}"
class="#{test eq testMB.test? 'divRred' : 'divGreen'}"
A simplified, easy to extend version.
var iOS = ['iPad', 'iPhone', 'iPod'].indexOf(navigator.platform) >= 0;
One more thing needed for my setup was to add
172.17.0.1 localhost
to /etc/hosts
so that Docker would point to 172.17.0.1
as the DB hostname, and not rely on a changing outer ip to find the DB. Hope this helps someone else with this issue!
If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):
var UserInRole = db.UserProfiles.
Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
(u, uir) => new { u, uir }).
Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
.Where(m => m.r.u.UserId == 1)
.Select (m => new AddUserToRole
{
UserName = m.r.u.UserName,
RoleName = m.ro.RoleName
});
Hope that helps.
You need to include the protocol scheme:
'http://192.168.1.61:8080/api/call'
Without the http://
part, requests
has no idea how to connect to the remote server.
Note that the protocol scheme must be all lowercase; if your URL starts with HTTP://
for example, it won’t find the http://
connection adapter either.
Another method using jquery
<script type="text/javascript">
//set this variable according to the need within the page
var BACKSPACE_NAV_DISABLED = true;
function fnPreventBackspace(event){if (BACKSPACE_NAV_DISABLED && event.keyCode == 8) {return false;}}
function fnPreventBackspacePropagation(event){if(BACKSPACE_NAV_DISABLED && event.keyCode == 8){event.stopPropagation();}return true;}
$(document).ready(function(){
if(BACKSPACE_NAV_DISABLED){
//for IE use keydown, for Mozilla keypress
//as described in scr: http://www.codeproject.com/KB/scripting/PreventDropdownBackSpace.aspx
$(document).keypress(fnPreventBackspace);
$(document).keydown(fnPreventBackspace);
//Allow Backspace is the following controls
var jCtrl = null;
jCtrl = $('input[type="text"]');
jCtrl.keypress(fnPreventBackspacePropagation);
jCtrl.keydown(fnPreventBackspacePropagation);
jCtrl = $('input[type="password"]');
jCtrl.keypress(fnPreventBackspacePropagation);
jCtrl.keydown(fnPreventBackspacePropagation);
jCtrl = $('textarea');
jCtrl.keypress(fnPreventBackspacePropagation);
jCtrl.keydown(fnPreventBackspacePropagation);
//disable backspace for readonly and disabled
jCtrl = $('input[type="text"][readonly="readonly"]')
jCtrl.keypress(fnPreventBackspace);
jCtrl.keydown(fnPreventBackspace);
jCtrl = $('input[type="text"][disabled="disabled"]')
jCtrl.keypress(fnPreventBackspace);
jCtrl.keydown(fnPreventBackspace);
}
});
</script>
PORT 4369: Erlang makes use of a Port Mapper Daemon (epmd) for resolution of node names in a cluster. Nodes must be able to reach each other and the port mapper daemon for clustering to work.
PORT 35197 set by inet_dist_listen_min/max Firewalls must permit traffic in this range to pass between clustered nodes
RabbitMQ Management console:
PORT 5672
RabbitMQ main port.
For a cluster of nodes, they must be open to each other on 35197
, 4369
and 5672
.
For any servers that want to use the message queue, only 5672
is required.
It allows you to add as many base type parameters in your call as you like.
addTwoEach(10, 2, 4, 6)
whereas with the second form you have to use an array as parameter
addTwoEach(new int[] {10,2,4,6})
Installing NuGet package ASP.NET.MVC solved the issue for me.
To install package.
- Right click on project
- Select "Manage NuGet Packages"
- Select Online->Nuget.org from left menu
- select "Microsoft ASP.NET MVC"
- Click Install
If you have already installed package earlier, please update the package by selecting Updates from left menu and then selecting "Microsoft ASP.NET" and click Update.
I also got a similar error
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\authentication.py", line 191, in get_auth_plugin
"Authentication plugin '{0}' is not supported".format(plugin_name))
mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported
You have probably installed mysql-connector instead of mysql-connector-python. So you need to install it again for python3:
pip3 install mysql-connector-python
Looks like Firebug (Firefox add-on) has the answer:
Log Events
Closed
(manually)there will be something like this in Console tab:
...
mousemove clientX=1097, clientY=292
popupshowing
mousedown clientX=1097, clientY=292
focus
mouseup clientX=1097, clientY=292
click clientX=1097, clientY=292
mousemove clientX=1096, clientY=293
...
Source: Firebug Tip: Log Events
You are trying to pass pointers (which you do not delete, thus leaking memory) where references are needed. You do not really need pointers here:
Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
cout << "Numarul complex este: " << firstComplexNumber << endl;
// ^^^^^^^^^^^^^^^^^^ No need to dereference now
// ...
Complex::distanta(firstComplexNumber, secondComplexNumber);
Take a look on life cycle of Activity
Where
***onCreate()***
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
***onStart()***
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
And you can write your simple class to take a look when these methods call
public class TestActivity extends Activity {
/** Called when the activity is first created. */
private final static String TAG = "TestActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "On Create .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onDestroy()
*/
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "On Destroy .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "On Pause .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onRestart()
*/
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "On Restart .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "On Resume .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "On Start .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStop()
*/
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "On Stop .....");
}
}
Hope this will clear your confusion.
And take a look here for details.
Lifecycle Methods in Details is a very good example and demo application, which is a very good article to understand the life cycle.
Cannot be done. MsgBox buttons can only have specific values.
You'll have to roll your own form for this.
To create a MsgBox with two options (Yes/No):
MsgBox("Some Text", vbYesNo)
Decompile a g++
generated binary to see what is going on
main.cpp
void f() {}
void g();
extern "C" {
void ef() {}
void eg();
}
/* Prevent g and eg from being optimized away. */
void h() { g(); eg(); }
Compile and disassemble the generated ELF output:
g++ -c -std=c++11 -Wall -Wextra -pedantic -o main.o main.cpp
readelf -s main.o
The output contains:
8: 0000000000000000 7 FUNC GLOBAL DEFAULT 1 _Z1fv
9: 0000000000000007 7 FUNC GLOBAL DEFAULT 1 ef
10: 000000000000000e 17 FUNC GLOBAL DEFAULT 1 _Z1hv
11: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND _GLOBAL_OFFSET_TABLE_
12: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND _Z1gv
13: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND eg
Interpretation
We see that:
ef
and eg
were stored in symbols with the same name as in the code
the other symbols were mangled. Let's unmangle them:
$ c++filt _Z1fv
f()
$ c++filt _Z1hv
h()
$ c++filt _Z1gv
g()
Conclusion: both of the following symbol types were not mangled:
Ndx = UND
), to be provided at link or run time from another object fileSo you will need extern "C"
both when calling:
g++
to expect unmangled symbols produced by gcc
g++
to generate unmangled symbols for gcc
to useThings that do not work in extern C
It becomes obvious that any C++ feature that requires name mangling will not work inside extern C
:
extern "C" {
// Overloading.
// error: declaration of C function ‘void f(int)’ conflicts with
void f();
void f(int i);
// Templates.
// error: template with C linkage
template <class C> void f(C i) { }
}
Minimal runnable C from C++ example
For the sake of completeness and for the newbs out there, see also: How to use C source files in a C++ project?
Calling C from C++ is pretty easy: each C function only has one possible non-mangled symbol, so no extra work is required.
main.cpp
#include <cassert>
#include "c.h"
int main() {
assert(f() == 1);
}
c.h
#ifndef C_H
#define C_H
/* This ifdef allows the header to be used from both C and C++
* because C does not know what this extern "C" thing is. */
#ifdef __cplusplus
extern "C" {
#endif
int f();
#ifdef __cplusplus
}
#endif
#endif
c.c
#include "c.h"
int f(void) { return 1; }
Run:
g++ -c -o main.o -std=c++98 main.cpp
gcc -c -o c.o -std=c89 c.c
g++ -o main.out main.o c.o
./main.out
Without extern "C"
the link fails with:
main.cpp:6: undefined reference to `f()'
because g++
expects to find a mangled f
, which gcc
did not produce.
Minimal runnable C++ from C example
Calling C++ from C is a bit harder: we have to manually create non-mangled versions of each function we want to expose.
Here we illustrate how to expose C++ function overloads to C.
main.c
#include <assert.h>
#include "cpp.h"
int main(void) {
assert(f_int(1) == 2);
assert(f_float(1.0) == 3);
return 0;
}
cpp.h
#ifndef CPP_H
#define CPP_H
#ifdef __cplusplus
// C cannot see these overloaded prototypes, or else it would get confused.
int f(int i);
int f(float i);
extern "C" {
#endif
int f_int(int i);
int f_float(float i);
#ifdef __cplusplus
}
#endif
#endif
cpp.cpp
#include "cpp.h"
int f(int i) {
return i + 1;
}
int f(float i) {
return i + 2;
}
int f_int(int i) {
return f(i);
}
int f_float(float i) {
return f(i);
}
Run:
gcc -c -o main.o -std=c89 -Wextra main.c
g++ -c -o cpp.o -std=c++98 cpp.cpp
g++ -o main.out main.o cpp.o
./main.out
Without extern "C"
it fails with:
main.c:6: undefined reference to `f_int'
main.c:7: undefined reference to `f_float'
because g++
generated mangled symbols which gcc
cannot find.
Where is the extern "c"
when I include C headers from C++?
cstdio
might be relying on #pragma GCC system_header
which https://gcc.gnu.org/onlinedocs/cpp/System-Headers.html mentions: "On some targets, such as RS/6000 AIX, GCC implicitly surrounds all system headers with an 'extern "C"' block when compiling as C++.", but I didn't fully confirm it./usr/include/unistd.h
are covered at: Do I need an extern "C" block to include standard POSIX C headers? via __BEGIN_DECLS
, reproduced on Ubuntu 20.04. __BEGIN_DECLS
is included via #include <features.h>
.Tested in Ubuntu 18.04.
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
E.g. thenReturn() may be missing.
For mocking of void methods try out below:
//Kotlin Syntax
Mockito.`when`(voidMethodCall())
.then {
Unit //Do Nothing
}
At a minimum, change this:
function BlockID() {
var IDs = new Array();
images['s'] = "Images/Block_01.png";
images['g'] = "Images/Block_02.png";
images['C'] = "Images/Block_03.png";
images['d'] = "Images/Block_04.png";
return IDs;
}
To this:
function BlockID() {
var IDs = new Object();
IDs['s'] = "Images/Block_01.png";
IDs['g'] = "Images/Block_02.png";
IDs['C'] = "Images/Block_03.png";
IDs['d'] = "Images/Block_04.png";
return IDs;
}
There are a couple fixes to point out. First, images
is not defined in your original function, so assigning property values to it will throw an error. We correct that by changing images
to IDs
. Second, you want to return an Object
, not an Array
. An object can be assigned property values akin to an associative array or hash -- an array cannot. So we change the declaration of var IDs = new Array();
to var IDs = new Object();
.
After those changes your code will run fine, but it can be simplified further. You can use shorthand notation (i.e., object literal property value shorthand) to create the object and return it immediately:
function BlockID() {
return {
"s":"Images/Block_01.png"
,"g":"Images/Block_02.png"
,"C":"Images/Block_03.png"
,"d":"Images/Block_04.png"
};
}
w/o flip:
<?php
foreach ($items as $key => $value) {
if ($id === $value) {
unset($items[$key]);
}
}
This worked for me:
<div class="text-right">
<button type="button">Button 1</button>
<button type="button">Button 2</button>
</div>
You need to enable SQL Server Authentication:
To get the smallest or largest item in a list, use the built-in min and max functions:
lo = min(L)
hi = max(L)
As with sort, you can pass in a "key" argument that is used to map the list items before they are compared:
lo = min(L, key=int)
hi = max(L, key=int)
http://effbot.org/zone/python-list.htm
Looks like you could use the max function if you map it correctly for strings and use that as the comparison. I would recommend just finding the max once though of course, not for each element in the list.
Refer: http://www.wellho.net/mouth/754_tar-jar-war-ear-sar-files.html
tar (tape archives) - Format used is file written in serial units of fileName, fileSize, fileData - no compression. can be huge
Jar (java archive) - compression techniques used - generally contains java information like class/java files. But can contain any files and directory structure
war (web application archives) - similar like jar files only have specific directory structure as per JSP/Servlet spec for deployment purposes
ear (enterprise archives) - similar like jar files. have directory structure following J2EE requirements so that it can be deployed on J2EE application servers. - can contain multiple JAR and WAR files
Team Foundation Server (TFS) keeps track of its local copy in a hidden directory called $TF.When you issue the "get Latest Version", TFS looks into this folder and see weather I have the latest copy or not. If it does it will not download the latest copy. It does not matter if you have the original file or not. In fact you might have deleted the entire folder (as in my case) and TFS won't fetch the latest copy because it does not look into the actual file but the hidden directory where it records changes. The flaw with this design is, anything done outside the system will not be recorded in TFS. For example, you may go into Windows explorer, delete a folder or file and TFS wont recognize it. It will be totally blind. At least I would expect there Windows would not let you delete this file but it does!
One way to enforce the latest copy is to delete the hidden $TF folder manually. To do that, go to command prompt and navigate to the root folder where you project was checked out and issue this command
rd/s $tf // remove $TF folder and everything inside it
If you want to just check the hidden folder, you can do it using
dir /ah // display hidden files and folders
Note: If you do it, the tf will think you do not have any local copy even though you have it in files and it will sync up everything again.
Caution: Use this method at your own risk. Please do not use it on critical work.
If you use sizeof()
then a char *str
and char str[]
will return different answers. char str[]
will return the length of the string(including the string terminator) while char *str
will return the size of the pointer(differs as per compiler).
Committing .gitignore can be very useful but you want to make sure you don't modify it too much thereafter especially if you regularly switch between branches. If you do you might get cases where files are ignored in a branch and not in the other, forcing you to go manually delete or rename files in your work directory because a checkout failed as it would overwrite a non-tracked file.
Therefore yes, do commit your .gitignore, but not before you are reasonably sure it won't change that much thereafter.
How about using StringComparison.CurrentCultureIgnoreCase
instead?
VTD-XML is the heavy duty XML parsing lib... it is better than others in virtually every way... here is a 2013 paper that analyzes all XML processing frameworks available in java platform...
http://sdiwc.us/digitlib/journal_paper.php?paper=00000582.pdf
Here is a method that recursively replaces all scripts with executable ones:
function nodeScriptReplace(node) {
if ( nodeScriptIs(node) === true ) {
node.parentNode.replaceChild( nodeScriptClone(node) , node );
}
else {
var i = -1, children = node.childNodes;
while ( ++i < children.length ) {
nodeScriptReplace( children[i] );
}
}
return node;
}
function nodeScriptClone(node){
var script = document.createElement("script");
script.text = node.innerHTML;
var i = -1, attrs = node.attributes, attr;
while ( ++i < attrs.length ) {
script.setAttribute( (attr = attrs[i]).name, attr.value );
}
return script;
}
function nodeScriptIs(node) {
return node.tagName === 'SCRIPT';
}
Example call:
nodeScriptReplace(document.getElementsByTagName("body")[0]);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();
Above format seems better to me as it has precision up to millis.
According to http://api.jquery.com/jquery.ajax/
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
Per Mozilla's Map documentation, you can initialize as follows:
private _gridOptions:Map<string, Array<string>> =
new Map([
["1", ["test"]],
["2", ["test2"]]
]);
This was very simple now that I realize how to do it, thanks to all the answers for leading me to the solution. I had to abandon $.getScript() in order to specify the source of the script...sometimes doing things manually is best.
Solution
//great suggestion @Jasper
var len = $('script[src*="Javascript/MyScript.js"]').length;
if (len === 0) {
alert('script not loaded');
loadScript('Javascript/MyScript.js');
if ($('script[src*="Javascript/MyScript.js"]').length === 0) {
alert('still not loaded');
}
else {
alert('loaded now');
}
}
else {
alert('script loaded');
}
function loadScript(scriptLocationAndName) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
I tried subtract, but the result was not consistent.
If I run df1.subtract(df2)
, not all lines of df1 are shown on the result dataframe, probably due distinct
cited on the docs.
This solved my problem:
df1.exceptAll(df2)
hasOwnProperty
is a normal JavaScript function that takes a string argument.
When you call shape1.hasOwnProperty(name)
you are passing it the value of the name
variable (which doesn't exist), just as it would if you wrote alert(name)
.
You need to call hasOwnProperty
with a string containing name
, like this: shape1.hasOwnProperty("name")
.
Here is the complete Implementation of Binary Search Tree In Java insert,search,countNodes,traversal,delete,empty,maximum & minimum node,find parent node,print all leaf node, get level,get height, get depth,print left view, mirror view
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.junit.experimental.max.MaxCore;
class BSTNode {
BSTNode left = null;
BSTNode rigth = null;
int data = 0;
public BSTNode() {
super();
}
public BSTNode(int data) {
this.left = null;
this.rigth = null;
this.data = data;
}
@Override
public String toString() {
return "BSTNode [left=" + left + ", rigth=" + rigth + ", data=" + data + "]";
}
}
class BinarySearchTree {
BSTNode root = null;
public BinarySearchTree() {
}
public void insert(int data) {
BSTNode node = new BSTNode(data);
if (root == null) {
root = node;
return;
}
BSTNode currentNode = root;
BSTNode parentNode = null;
while (true) {
parentNode = currentNode;
if (currentNode.data == data)
throw new IllegalArgumentException("Duplicates nodes note allowed in Binary Search Tree");
if (currentNode.data > data) {
currentNode = currentNode.left;
if (currentNode == null) {
parentNode.left = node;
return;
}
} else {
currentNode = currentNode.rigth;
if (currentNode == null) {
parentNode.rigth = node;
return;
}
}
}
}
public int countNodes() {
return countNodes(root);
}
private int countNodes(BSTNode node) {
if (node == null) {
return 0;
} else {
int count = 1;
count += countNodes(node.left);
count += countNodes(node.rigth);
return count;
}
}
public boolean searchNode(int data) {
if (empty())
return empty();
return searchNode(data, root);
}
public boolean searchNode(int data, BSTNode node) {
if (node != null) {
if (node.data == data)
return true;
else if (node.data > data)
return searchNode(data, node.left);
else if (node.data < data)
return searchNode(data, node.rigth);
}
return false;
}
public boolean delete(int data) {
if (empty())
throw new NoSuchElementException("Tree is Empty");
BSTNode currentNode = root;
BSTNode parentNode = root;
boolean isLeftChild = false;
while (currentNode.data != data) {
parentNode = currentNode;
if (currentNode.data > data) {
isLeftChild = true;
currentNode = currentNode.left;
} else if (currentNode.data < data) {
isLeftChild = false;
currentNode = currentNode.rigth;
}
if (currentNode == null)
return false;
}
// CASE 1: node with no child
if (currentNode.left == null && currentNode.rigth == null) {
if (currentNode == root)
root = null;
if (isLeftChild)
parentNode.left = null;
else
parentNode.rigth = null;
}
// CASE 2: if node with only one child
else if (currentNode.left != null && currentNode.rigth == null) {
if (root == currentNode) {
root = currentNode.left;
}
if (isLeftChild)
parentNode.left = currentNode.left;
else
parentNode.rigth = currentNode.left;
} else if (currentNode.rigth != null && currentNode.left == null) {
if (root == currentNode)
root = currentNode.rigth;
if (isLeftChild)
parentNode.left = currentNode.rigth;
else
parentNode.rigth = currentNode.rigth;
}
// CASE 3: node with two child
else if (currentNode.left != null && currentNode.rigth != null) {
// Now we have to find minimum element in rigth sub tree
// that is called successor
BSTNode successor = getSuccessor(currentNode);
if (currentNode == root)
root = successor;
if (isLeftChild)
parentNode.left = successor;
else
parentNode.rigth = successor;
successor.left = currentNode.left;
}
return true;
}
private BSTNode getSuccessor(BSTNode deleteNode) {
BSTNode successor = null;
BSTNode parentSuccessor = null;
BSTNode currentNode = deleteNode.left;
while (currentNode != null) {
parentSuccessor = successor;
successor = currentNode;
currentNode = currentNode.left;
}
if (successor != deleteNode.rigth) {
parentSuccessor.left = successor.left;
successor.rigth = deleteNode.rigth;
}
return successor;
}
public int nodeWithMinimumValue() {
return nodeWithMinimumValue(root);
}
private int nodeWithMinimumValue(BSTNode node) {
if (node.left != null)
return nodeWithMinimumValue(node.left);
return node.data;
}
public int nodewithMaximumValue() {
return nodewithMaximumValue(root);
}
private int nodewithMaximumValue(BSTNode node) {
if (node.rigth != null)
return nodewithMaximumValue(node.rigth);
return node.data;
}
public int parent(int data) {
return parent(root, data);
}
private int parent(BSTNode node, int data) {
if (empty())
throw new IllegalArgumentException("Empty");
if (root.data == data)
throw new IllegalArgumentException("No Parent node found");
BSTNode parent = null;
BSTNode current = node;
while (current.data != data) {
parent = current;
if (current.data > data)
current = current.left;
else
current = current.rigth;
if (current == null)
throw new IllegalArgumentException(data + " is not a node in tree");
}
return parent.data;
}
public int sibling(int data) {
return sibling(root, data);
}
private int sibling(BSTNode node, int data) {
if (empty())
throw new IllegalArgumentException("Empty");
if (root.data == data)
throw new IllegalArgumentException("No Parent node found");
BSTNode cureent = node;
BSTNode parent = null;
boolean isLeft = false;
while (cureent.data != data) {
parent = cureent;
if (cureent.data > data) {
cureent = cureent.left;
isLeft = true;
} else {
cureent = cureent.rigth;
isLeft = false;
}
if (cureent == null)
throw new IllegalArgumentException("No Parent node found");
}
if (isLeft) {
if (parent.rigth != null) {
return parent.rigth.data;
} else
throw new IllegalArgumentException("No Sibling is there");
} else {
if (parent.left != null)
return parent.left.data;
else
throw new IllegalArgumentException("No Sibling is there");
}
}
public void leafNodes() {
if (empty())
throw new IllegalArgumentException("Empty");
leafNode(root);
}
private void leafNode(BSTNode node) {
if (node == null)
return;
if (node.rigth == null && node.left == null)
System.out.print(node.data + " ");
leafNode(node.left);
leafNode(node.rigth);
}
public int level(int data) {
if (empty())
throw new IllegalArgumentException("Empty");
return level(root, data, 1);
}
private int level(BSTNode node, int data, int level) {
if (node == null)
return 0;
if (node.data == data)
return level;
int result = level(node.left, data, level + 1);
if (result != 0)
return result;
result = level(node.rigth, data, level + 1);
return result;
}
public int depth() {
return depth(root);
}
private int depth(BSTNode node) {
if (node == null)
return 0;
else
return 1 + Math.max(depth(node.left), depth(node.rigth));
}
public int height() {
return height(root);
}
private int height(BSTNode node) {
if (node == null)
return 0;
else
return 1 + Math.max(height(node.left), height(node.rigth));
}
public void leftView() {
leftView(root);
}
private void leftView(BSTNode node) {
if (node == null)
return;
int height = height(node);
for (int i = 1; i <= height; i++) {
printLeftView(node, i);
}
}
private boolean printLeftView(BSTNode node, int level) {
if (node == null)
return false;
if (level == 1) {
System.out.print(node.data + " ");
return true;
} else {
boolean left = printLeftView(node.left, level - 1);
if (left)
return true;
else
return printLeftView(node.rigth, level - 1);
}
}
public void mirroeView() {
BSTNode node = mirroeView(root);
preorder(node);
System.out.println();
inorder(node);
System.out.println();
postorder(node);
System.out.println();
}
private BSTNode mirroeView(BSTNode node) {
if (node == null || (node.left == null && node.rigth == null))
return node;
BSTNode temp = node.left;
node.left = node.rigth;
node.rigth = temp;
mirroeView(node.left);
mirroeView(node.rigth);
return node;
}
public void preorder() {
preorder(root);
}
private void preorder(BSTNode node) {
if (node != null) {
System.out.print(node.data + " ");
preorder(node.left);
preorder(node.rigth);
}
}
public void inorder() {
inorder(root);
}
private void inorder(BSTNode node) {
if (node != null) {
inorder(node.left);
System.out.print(node.data + " ");
inorder(node.rigth);
}
}
public void postorder() {
postorder(root);
}
private void postorder(BSTNode node) {
if (node != null) {
postorder(node.left);
postorder(node.rigth);
System.out.print(node.data + " ");
}
}
public boolean empty() {
return root == null;
}
}
public class BinarySearchTreeTest {
public static void main(String[] l) {
System.out.println("Weleome to Binary Search Tree");
Scanner scanner = new Scanner(System.in);
boolean yes = true;
BinarySearchTree tree = new BinarySearchTree();
do {
System.out.println("\n1. Insert");
System.out.println("2. Search Node");
System.out.println("3. Count Node");
System.out.println("4. Empty Status");
System.out.println("5. Delete Node");
System.out.println("6. Node with Minimum Value");
System.out.println("7. Node with Maximum Value");
System.out.println("8. Find Parent node");
System.out.println("9. Count no of links");
System.out.println("10. Get the sibling of any node");
System.out.println("11. Print all the leaf node");
System.out.println("12. Get the level of node");
System.out.println("13. Depth of the tree");
System.out.println("14. Height of Binary Tree");
System.out.println("15. Left View");
System.out.println("16. Mirror Image of Binary Tree");
System.out.println("Enter Your Choice :: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
try {
System.out.println("Enter Value");
tree.insert(scanner.nextInt());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 2:
System.out.println("Enter the node");
System.out.println(tree.searchNode(scanner.nextInt()));
break;
case 3:
System.out.println(tree.countNodes());
break;
case 4:
System.out.println(tree.empty());
break;
case 5:
try {
System.out.println("Enter the node");
System.out.println(tree.delete(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
case 6:
try {
System.out.println(tree.nodeWithMinimumValue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 7:
try {
System.out.println(tree.nodewithMaximumValue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 8:
try {
System.out.println("Enter the node");
System.out.println(tree.parent(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 9:
try {
System.out.println(tree.countNodes() - 1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 10:
try {
System.out.println("Enter the node");
System.out.println(tree.sibling(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 11:
try {
tree.leafNodes();
} catch (Exception e) {
System.out.println(e.getMessage());
}
case 12:
try {
System.out.println("Enter the node");
System.out.println("Level is : " + tree.level(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 13:
try {
System.out.println(tree.depth());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 14:
try {
System.out.println(tree.height());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 15:
try {
tree.leftView();
System.out.println();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 16:
try {
tree.mirroeView();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
default:
break;
}
tree.preorder();
System.out.println();
tree.inorder();
System.out.println();
tree.postorder();
} while (yes);
scanner.close();
}
}
The VH
unit can be used to fill the background of the viewport, aka the browser window.
(height:100vh;)
html{
height:100%;
}
.body {
background: url(image.jpg) no-repeat center top;
background-size: cover;
height:100vh;
}
Two years late but I just began reading the Firestore documentation recently cover to cover for fun and found withConverter
which I saw wasn't posted in any of the above answers. Thus:
If you want to include ids and also use withConverter
(Firestore's version of ORMs, like ActiveRecord for Ruby on Rails, Entity Framework for .NET, etc), then this might be useful for you:
Somewhere in your project, you probably have your Event
model properly defined. For example, something like:
Your model (in TypeScript
):
./models/Event.js
export class Event {
constructor (
public id: string,
public title: string,
public datetime: Date
)
}
export const eventConverter = {
toFirestore: function (event: Event) {
return {
// id: event.id, // Note! Not in ".data()" of the model!
title: event.title,
datetime: event.datetime
}
},
fromFirestore: function (snapshot: any, options: any) {
const data = snapshot.data(options)
const id = snapshot.id
return new Event(id, data.title, data.datetime)
}
}
And then your client-side TypeScript
code:
import { eventConverter } from './models/Event.js'
...
async function loadEvents () {
const qs = await firebase.firestore().collection('events')
.orderBy('datetime').limit(3) // Remember to limit return sizes!
.withConverter(eventConverter).get()
const events = qs.docs.map((doc: any) => doc.data())
...
}
Two interesting quirks of Firestore to notice (or at least, I thought were interesting):
Your event.id
is actually stored "one-level-up" in snapshot.id
and not snapshot.data()
.
If you're using TypeScript, the TS linter (or whatever it's called) sadly isn't smart enough to understand:
const events = qs.docs.map((doc: Event) => doc.data())
even though right above it you explicitly stated:
.withConverter(eventConverter)
Which is why it needs to be doc: any
.
(But! You will actually get Array<Event>
back! (Not Array<Map>
back.) That's the entire point of withConverter
... That way if you have any object methods (not shown here in this example), you can immediately use them.)
It makes sense to me but I guess I've gotten so greedy/spoiled that I just kinda expect my VS Code, ESLint, and the TS Watcher to literally do everything for me. Oh well.
Formal docs (about withConverter
and more) here: https://firebase.google.com/docs/firestore/query-data/get-data#custom_objects
According to Java Persistence with Hibernate
mapping collections of value types with annotations [...]. At the time of writing it isn't part of the Java Persistence standard
If you were using Hibernate, you could do something like:
@org.hibernate.annotations.CollectionOfElements(
targetElement = java.lang.String.class
)
@JoinTable(
name = "foo",
joinColumns = @JoinColumn(name = "foo_id")
)
@org.hibernate.annotations.IndexColumn(
name = "POSITION", base = 1
)
@Column(name = "baz", nullable = false)
private List<String> arguments = new ArrayList<String>();
Update: Note, this is now available in JPA2.
I think we should use the following rule to determine when we talk about Design vs Architecture: If the elements of a software picture you created can be mapped one to one to a programming language syntactical construction, then is Design, if not is Architecture.
So, for example, if you are seeing a class diagram or a sequence diagram, you are able to map a class and their relationships to an Object Oriented Programming language using the Class syntactical construction. This is clearly Design. In addition, this might bring to the table that this discussion has a relation with the programming language you will use to implement a software system. If you use Java, the previous example applies, as Java is an Object Oriented Programming Language. If you come up with a diagram that shows packages and its dependencies, that is Design too. You can map the element (a package in this case) to a Java syntactical construction.
Now, suppose your Java application is divided in modules, and each module is a set of packages (represented as a jar file deployment unit), and you are presented with a diagram containing modules and its dependencies, then, that is Architecture. There isn’t a way in Java (at least not until Java 7) to map a module (a set of packages) to a syntactical construction. You might also notice that this diagram represents a step higher in the level of abstraction of your software model. Any diagram above (coarse grained than) a package diagram, represents an Architectural view when developing in the Java programming language. On the other hand, if you are developing in Modula-2, then, a module diagram represents a Design.
(A fragment from http://www.copypasteisforword.com/notes/software-architecture-vs-software-design)
Status 422 (RFC 4918, Section 11.2) comes to mind:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
I am on Mac Os. In my case, my host file was black. I added following entries (these entries should be there by default, but they weren't).
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
After re-running android studio, it prompted the sdk download.
Simply remove the server in Eclipse and add tomcat server again. than shutdown the tomcat in tomcat/bin/shutdown.bat file and start the server in eclipse.
When you use the start command to a website it will use the default browser by default but if you want to use a specific browser then use start iexplorer.exe www.website.com
Also you cannot have http://
in the url.
Sourcetree
Because you not commit your merge, then just double click on another branch (which mean checkout it) and when sourcetree ask you about discarding all changes then agree :)
Update
I see many down-votes but any commet... I will left this answer which is addressed for those who use SourceTree as git client (as I - when I looking for solution for question asked by OP)
git revert -m 1 88113a64a21bf8a51409ee2a1321442fd08db705
But may have unexpected side-effects. See --mainline parent-number
option in git-scm.com/docs/git-revert
Perhaps a brute but effective way would be to check out the left parent of that commit, make a copy of all the files, checkout HEAD
again, and replace all the contents with the old files. Then git will tell you what is being rolled back and you create your own revert commit :) !
The following solution works well when you want to move the text closer to the bullet and even if you have multiple lines of text.
margin-right
allows you to move the text closer to the bullet
text-indent
ensures that multiple lines of text still line up correctly
li:before {_x000D_
content: "";_x000D_
margin-right: -5px; /* Adjust this to move text closer to the bullet */_x000D_
}_x000D_
_x000D_
li {_x000D_
text-indent: 5px; /* Aligns second line of text */_x000D_
}
_x000D_
<ul>_x000D_
<li> Item 1 ... </li>_x000D_
<li> Item 2 ... this item has tons and tons of text that causes a second line! Notice how even the second line is lined up with the first!</li>_x000D_
<li> Item 3 ... </li>_x000D_
</ul>
_x000D_
As simple as the following:
let elements = document.querySelectorAll('.custom-class')
elements.forEach((item: any) => {
item.style.display = 'none'
})
With that, you avoid all the looping, indexing, and such.
OS X is "LP64". This means that:
int
is always 32-bits.
long long
is always 64-bits.
NSInteger
and long
are always pointer-sized. That means they're 32-bits on 32-bit systems, and 64 bits on 64-bit systems.
The reason NSInteger exists is because many legacy APIs incorrectly used int
instead of long
to hold pointer-sized variables, which meant that the APIs had to change from int
to long
in their 64-bit versions. In other words, an API would have different function signatures depending on whether you're compiling for 32-bit or 64-bit architectures. NSInteger
intends to mask this problem with these legacy APIs.
In your new code, use int
if you need a 32-bit variable, long long
if you need a 64-bit integer, and long
or NSInteger
if you need a pointer-sized variable.
I've being going round in circles with Firefox 43, El Capitan and WHM/cPanel SSL installation continually getting the Untrusted site error - I didn't buy the certificate it was handed over to me to install as the last guy walked out the door. Turns out I was installing under the wrong domain because I missed off the www - but the certificate still installed against the domain, when I installed the certificate in WHM using www.domain.com.au it installed now worries and the FF error has gone - the certificate works fine for both www and non-www.
> df <- data.frame(matrix(ncol = 300, nrow = 100))
> dim(df)
[1] 100 300
You can use the utility method in Collections
class
public static <T extends Comparable<? super T>> void sort(List<T> list)
or
public static <T> void sort(List<T> list,Comparator<? super T> c)
Refer to Comparable
and Comparator
interfaces for more flexibility on sorting the object.
This looked ok:
function gup( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
From http://www.netlobo.com/url_query_string_javascript.html
Very few posts suggest using LOGON_TYPE_NEW_CREDENTIALS
instead of LOGON_TYPE_NETWORK
or LOGON_TYPE_INTERACTIVE
. I had an impersonation issue with one machine connected to a domain and one not, and this fixed it.
The last code snippet in this post suggests that impersonating across a forest does work, but it doesn't specifically say anything about trust being set up. So this may be worth trying:
const int LOGON_TYPE_NEW_CREDENTIALS = 9;
const int LOGON32_PROVIDER_WINNT50 = 3;
bool returnValue = LogonUser(user, domain, password,
LOGON_TYPE_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50,
ref tokenHandle);
MSDN says that LOGON_TYPE_NEW_CREDENTIALS
only works when using LOGON32_PROVIDER_WINNT50
.
Use angular-busy:
Add cgBusy as to your app / module:
angular.module('your_app', ['cgBusy']);
Add your promise to scope
:
function MyCtrl($http, User) {
//using $http
this.isBusy = $http.get('...');
//if you have a User class based on $resource
this.isBusy = User.$save();
}
In your html template:
<div cg-busy="$ctrl.isBusy"></div>
Old topic, but I was recently affected by this.
Using a class "row-fluid" instead of "row" worked fine for me but I'm not sure if it's fully supported going forward.
So after reading Why does the bootstrap .row has a default margin-left of -30px I just used the <div>
(without any row class) and it behaved exactly like <div class="row-fluid">
Whoa. You're really over-complicating it by a very long distance. Try:
>>> print hex(0x12ef ^ 0xabcd)
0xb922
You seem to be ignoring these handy facts, at least:
0x
prefix.hex()
function can be used to convert any number into a hexadecimal string for display.If you already have the numbers as strings, you can use the int()
function to convert to numbers, by providing the expected base (16 for hexadecimal numbers):
>>> print int("12ef", 16)
4874
So you can do two conversions, perform the XOR, and then convert back to hex:
>>> print hex(int("12ef", 16) ^ int("abcd", 16))
0xb922
Instead of typedef struct { ... } pos;
you should be doing struct pos { ... };
. The issue here is that you are using the pos
type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.
Further, the typedef struct { ... } name;
pattern is a C-ism, and doesn't have much place in C++.
To answer your question about inline
, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline
, the compiler effectively ignores it because the method is already declared inline.
(inline
methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)
ngOnInit()
is called after ngOnChanges()
was called the first time. ngOnChanges()
is called every time inputs are updated by change detection.
ngAfterViewInit()
is called after the view is initially rendered. This is why @ViewChild()
depends on it. You can't access view members before they are rendered.
Preferences -> General -> Load preferences from a custom folder or URL
First time you choose this, it will automatically save a preferences file into this folder called "com.googlecode.iterm2.plist"
I believe this to be the cleanest and readable option:
var empty = [];
empty.some(x => x); //returns false
There is a simple work around. The alert only comes up when you have a large amount of data in your clipboard. Just copy a random cell before you close the workbook and it won't show up anymore!
Check this sample out from the Highcharts API.
Replace this
return Highcharts.dateFormat('%a %d %b', this.value);
With this
return Highcharts.dateFormat('%a %d %b %H:%M:%S', this.value);
Look here about the dateFormat()
function.
Also see - tickInterval and pointInterval
I had the same situation and I found a way around with a bit of engineering as follows - -
You have to have your method in parent class without any parameter and use - -
Class<? extends Person> cl = this.getClass(); // inside parent class
Now, with 'cl' you can access all child class fields with their name and initialized values by using - -
cl.getDeclaredFields(); cl.getField("myfield"); // and many more
In this situation your 'this' pointer will reference your child class object if you are calling parent method through your child class object.
Another thing you might need to use is Object obj = cl.newInstance();
Let me know if still you got stucked somewhere.
You have asked two questions, one in the title about the difference between PNG8 and PNG24, which has received a few answers, namely that PNG24 has 8-bit red, green, and blue channels, and PNG-8 has a single 8-bit index into a palette. Naturally, PNG24 usually has a larger filesize than PNG8. Furthermore, PNG8 usually means that it is opaque or has only binary transparency (like GIF); it's defined that way in ImageMagick/GraphicsMagick.
This is an answer to the other one, "I would like to know that if I use either type in my html page, will there be any error? Or is this only quality matter?"
You can put either type on an HTML page and no, this won't cause an error; the files should all be named with the ".png" extension and referred to that way in your HTML. Years ago, early versions of Internet Explorer would not handle PNG with an alpha channel (PNG32) or indexed-color PNG with translucent pixels properly, so it was useful to convert such images to PNG8 (indexed-color with binary transparency conveyed via a PNG tRNS chunk) -- but still use the .png extension, to be sure they would display properly on IE. I think PNG24 was always OK on Internet Explorer because PNG24 is either opaque or has GIF-like single-color transparency conveyed via a PNG tRNS chunk.
The names PNG8 and PNG24 aren't mentioned in the PNG specification, which simply calls them all "PNG". Other names, invented by others, include
There are many more possible combinations including grayscale with 1, 2, 4, 8, or 16-bit samples and indexed PNG with 1, 2, or 4-bit samples (and any of those with transparent or translucent pixels), but those don't have special names.
May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly. Please find the code: I am using moment.js format function on a current date as (today is 29-06-2020) var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20
what happening is it retains only the year part :20 as "06/28/20", after If I run the statement : new Date(startDate) The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",
Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result. And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE. For clear understanding please find my question in the link: Date went wrong when using Momentjs date format in IE 11
As myJSON
is an object you can just set its properties, for example:
myJSON.list1 = ["1","2"];
If you dont know the name of the properties, you have to use the array access syntax:
myJSON['list'+listnum] = ["1","2"];
If you want to add an element to one of the properties, you can do;
myJSON.list1.push("3");
In similar situations, I've done well by putting something like the following into /etc/rc.local:
cd /path/to/my/script
./my_script.py &
cd -
echo `date +%Y-%b-%d_%H:%M:%S` > /tmp/ran_rc_local # check that rc.local ran
This has worked on multiple versions of Fedora and on Ubuntu 14.04 LTS, for both python and perl scripts.
There are three way to generate unique id in java.
1) the UUID class provides a simple means for generating unique ids.
UUID id = UUID.randomUUID();
System.out.println(id);
2) SecureRandom and MessageDigest
//initialization of the application
SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
//generate a random number
String randomNum = new Integer(prng.nextInt()).toString();
//get its digest
MessageDigest sha = MessageDigest.getInstance("SHA-1");
byte[] result = sha.digest(randomNum.getBytes());
System.out.println("Random number: " + randomNum);
System.out.println("Message digest: " + new String(result));
3) using a java.rmi.server.UID
UID userId = new UID();
System.out.println("userId: " + userId);
There is also a built-in function for this task:
variable = lines( itab_name ).
Just like the "pure" ABAP syntax described by IronGoofy, the function "lines( )" writes the number of lines of table itab_name into the variable.
For the simple email like [email protected], below code is sufficient.
public static bool ValidateEmail(string email)
{
System.Text.RegularExpressions.Regex emailRegex = new System.Text.RegularExpressions.Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
System.Text.RegularExpressions.Match emailMatch = emailRegex.Match(email);
return emailMatch.Success;
}
Here's a simple example of how to load JSON data into an Angular model.
I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.
http://www.iNorthwind.com/Service1.svc/getAllCustomers
It returns some JSON data which looks like this:
{
"GetAllCustomersResult" :
[
{
"CompanyName": "Alfreds Futterkiste",
"CustomerID": "ALFKI"
},
{
"CompanyName": "Ana Trujillo Emparedados y helados",
"CustomerID": "ANATR"
},
{
"CompanyName": "Antonio Moreno Taquería",
"CustomerID": "ANTON"
}
]
}
..and I want to populate a drop down list with this data, to look like this...
I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.
How would I do it ?
My Angular controller would look like this:
function MikesAngularController($scope, $http) {
$scope.listOfCustomers = null;
$http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
.success(function (data) {
$scope.listOfCustomers = data.GetAllCustomersResult;
})
.error(function (data, status, headers, config) {
// Do some error handling here
});
}
... which fills a "listOfCustomers" variable with this set of JSON data.
Then, in my HTML page, I'd use this:
<div ng-controller='MikesAngularController'>
<span>Please select a customer:</span>
<select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>
And that's it. We can now see a list of our JSON data on a web page, ready to be used.
The key to this is in the "ng-options" tag:
customer.CustomerID as customer.CompanyName for customer in listOfCustomers
It's a strange syntax to get your head around !
When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.
The full script for this example can be found here:
Mike
The following SQL lists all object dependencies across all databases and servers:
IF(OBJECT_ID('tempdb..#Obj_Dep_Details') IS NOT NULL)
BEGIN
DROP TABLE #Obj_Dep_Details
END
CREATE TABLE #Obj_Dep_Details
(
[Database] nvarchar(128)
,[Schema] nvarchar(128)
,dependent_object nvarchar(128)
,dependent_object_type nvarchar(60)
,referenced_server_name nvarchar(128)
,referenced_database_name nvarchar(128)
,referenced_schema_name nvarchar(128)
,referenced_entity_name nvarchar(128)
,referenced_id int
,referenced_object_db nvarchar(128)
,referenced_object_type nvarchar(60)
,referencing_id int
,SchemaDep nvarchar(128)
)
EXEC sp_MSForEachDB @command1='USE [?];
INSERT INTO #Obj_Dep_Details
SELECT DISTINCT
DB_NAME() AS [Database]
,SCHEMA_NAME(od.[schema_id]) AS [Schema]
,OBJECT_NAME(d1.referencing_id) AS dependent_object
,od.[type_desc] AS dependent_object_type
,COALESCE(d1.referenced_server_name, @@SERVERNAME) AS referenced_server_name
,COALESCE(d1.referenced_database_name, DB_NAME()) AS referenced_database_name
,COALESCE(d1.referenced_schema_name, SCHEMA_NAME(ro.[schema_id])) AS referenced_schema_name
,d1.referenced_entity_name
,d1.referenced_id
,DB_NAME(ro.parent_object_id) AS referenced_object_db
,ro.[type_desc] AS referenced_object_type
,d1.referencing_id
,SCHEMA_NAME(od.[schema_id]) AS SchemaDep
FROM sys.sql_expression_dependencies d1
LEFT OUTER JOIN sys.all_objects od
ON d1.referencing_id = od.[object_id]
LEFT OUTER JOIN sys.objects ro
ON d1.referenced_id = ro.[object_id]'
SELECT [Database] AS [Dep_Object_DB]
,[Schema] AS [Dep_Object_Schema]
,dependent_object AS [Dep_Object_Name]
,LOWER(REPLACE(dependent_object_type, '_', ' ')) AS [Dep_Object_Type]
,referenced_server_name AS [Ref_Object_Server_Name]
,referenced_database_name AS [Ref_Object_DB]
,referenced_schema_name AS [Ref_Object_Schema]
,referenced_entity_name AS [Ref_Object_Name]
,referenced_id AS [Ref_Object_ID]
,LOWER(REPLACE(referenced_object_type, '_', ' ')) AS [Ref_Object_Type]
,referencing_id AS [Dep_Object_ID]
FROM #Obj_Dep_Details WITH(NOLOCK)
WHERE referenced_entity_name = 'TableName'
ORDER BY [Dep_Object_DB]
,[Dep_Object_Name]
,[Ref_Object_Name]
,[Ref_Object_DB]
max = input("enter the maximum limit to check prime number");
if max>1 :
for i in range (2,max):
prime=0;
for j in range (2,i):
if(i%j==0):
prime=1;
break
if(prime==0 and i!=0):
print(i,"is prime number");
else:
print("prime no start from 2");
Before Java 7 you could also:
File folder = File.createTempFile("testFileUtils", ""); // no suffix
folder.delete();
folder.mkdirs();
folder.deleteOnExit();
The shortest possible way to test if the value contained in a variable $v
can be used as a number is:
number($v) = number($v)
You only need to substitute the $v
above with the expression whose value you want to test.
Explanation:
number($v) = number($v)
is obviously true, if $v
is a number, or a string that represents a number.
It is true also for a boolean value, because a number(true())
is 1 and number(false)
is 0.
Whenever $v
cannot be used as a number, then number($v)
is NaN
and NaN is not equal to any other value, even to itself.
Thus, the above expression is true only for $v
whose value can be used as a number, and false otherwise.
Yes, we can assign variables from child controller to the variables in parent controller. This is one possible way:
Overview: The main aim of the code, below, is to assign child controller's $scope.variable to parent controller's $scope.assign
Explanation: There are two controllers. In the html, notice that the parent controller encloses the child controller. That means the parent controller will be executed before child controller. So, first setValue() will be defined and then the control will go to the child controller. $scope.variable will be assigned as "child". Then this child scope will be passed as an argument to the function of parent controller, where $scope.assign will get the value as "child"
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('myApp',[]);
app.controller('child',function($scope){
$scope.variable = "child";
$scope.$parent.setValue($scope);
});
app.controller('parent',function($scope){
$scope.setValue = function(childscope) {
$scope.assign = childscope.variable;
}
});
</script>
<body ng-app="myApp">
<div ng-controller="parent">
<p>this is parent: {{assign}}</p>
<div ng-controller="child">
<p>this is {{variable}}</p>
</div>
</div>
</body>
</html>
Scanner input = new Scanner(System.in);
System.out.print("Enter number :");
int num = input.nextInt();
System.out.print("Reverse number :");
int value;
while( num > 0){
value = num % 10;
num /= 10;
System.out.print(value); //value = Reverse
}
Highlight an interface and use Ctrl+T to open "Quick Type Hierarchy".
They are not identical. Memcache is older but it has some limitations. I was using just fine in my application until I realized you can't store literal FALSE
in cache. Value FALSE
returned from the cache is the same as FALSE returned when a value is not found in the cache. There is no way to check which is which. Memcached has additional method (among others) Memcached::getResultCode
that will tell you whether key was found.
Because of this limitation I switched to storing empty arrays instead of FALSE
in cache. I am still using Memcache, but I just wanted to put this info out there for people who are deciding.
from app import SQLAlchemyDB as db
Chance.query.filter(Chance.repo_id==repo_id,
Chance.status=="1",
db.func.date(Chance.apply_time)<=end,
db.func.date(Chance.apply_time)>=start).count()
it is equal to:
select
count(id)
from
Chance
where
repo_id=:repo_id
and status='1'
and date(apple_time) <= end
and date(apple_time) >= start
wish can help you.
For those of you who use SnapKit, just like me, the solution is anchoring your constraints to view.safeAreaLayoutGuide
like so:
yourView.snp.makeConstraints { (make) in
if #available(iOS 11.0, *) {
//Bottom guide
make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottomMargin)
//Top guide
make.top.equalTo(view.safeAreaLayoutGuide.snp.topMargin)
//Leading guide
make.leading.equalTo(view.safeAreaLayoutGuide.snp.leadingMargin)
//Trailing guide
make.trailing.equalTo(view.safeAreaLayoutGuide.snp.trailingMargin)
} else {
make.edges.equalToSuperview()
}
}
The change event is triggered on the <select>
element, not the <option>
element. However, that's not the only problem. The way you defined the change
function won't cause a rerender of the component. It seems like you might not have fully grasped the concept of React yet, so maybe "Thinking in React" helps.
You have to store the selected value as state and update the state when the value changes. Updating the state will trigger a rerender of the component.
var MySelect = React.createClass({
getInitialState: function() {
return {
value: 'select'
}
},
change: function(event){
this.setState({value: event.target.value});
},
render: function(){
return(
<div>
<select id="lang" onChange={this.change} value={this.state.value}>
<option value="select">Select</option>
<option value="Java">Java</option>
<option value="C++">C++</option>
</select>
<p></p>
<p>{this.state.value}</p>
</div>
);
}
});
React.render(<MySelect />, document.body);
Also note that <p>
elements don't have a value
attribute. React/JSX simply replicates the well-known HTML syntax, it doesn't introduce custom attributes (with the exception of key
and ref
). If you want the selected value to be the content of the <p>
element then simply put inside of it, like you would do with any static content.
Learn more about event handling, state and form controls:
You have to specify that test1 is global:
test1 = 0
def testFunc():
global test1
test1 += 1
testFunc()
Create directory "bin" in
D:\sqldeveloper\jdk\ Copy
msvcr100.dll from
D:\sqldeveloper\jdk\jre\bin to
D:\sqldeveloper\jdk\bin
Setting the pointer to NULL before and after using is a good technique. This is easy to do in C++ if you manage pointers within a class for example (a string):
class SomeClass
{
public:
SomeClass();
~SomeClass();
void SetText( const char *text);
char *GetText() const { return MyText; }
void Clear();
private:
char * MyText;
};
SomeClass::SomeClass()
{
MyText = NULL;
}
SomeClass::~SomeClass()
{
Clear();
}
void SomeClass::Clear()
{
if (MyText)
free( MyText);
MyText = NULL;
}
void SomeClass::Settext( const char *text)
{
Clear();
MyText = malloc( strlen(text));
if (MyText)
strcpy( MyText, text);
}
This is what a constant expression in Java looks like:
package com.mycompany.mypackage;
public class MyLinks {
// constant expression
public static final String GUESTBOOK_URL = "/guestbook";
}
You can use it with annotations as following:
import com.mycompany.mypackage.MyLinks;
@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
// ...
}
Here is the correct code for Swift 3, with comments for instructional purposes:
override func viewDidLoad()
{
super.viewDidLoad()
// CGRectMake has been deprecated - and should be let, not var
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
// you will probably want to set the font (remember to use Dynamic Type!)
label.font = UIFont.preferredFont(forTextStyle: .footnote)
// and set the text color too - remember good contrast
label.textColor = .black
// may not be necessary (e.g., if the width & height match the superview)
// if you do need to center, CGPointMake has been deprecated, so use this
label.center = CGPoint(x: 160, y: 284)
// this changed in Swift 3 (much better, no?)
label.textAlignment = .center
label.text = "I am a test label"
self.view.addSubview(label)
}
let its required n bit then 2^n=(base)^digit and then take log and count no. for n
Simple extension for local gifs. Gets all the images from the gif and adds it to the imageView animationImages.
extension UIImageView {
static func fromGif(frame: CGRect, resourceName: String) -> UIImageView? {
guard let path = Bundle.main.path(forResource: resourceName, ofType: "gif") else {
print("Gif does not exist at that path")
return nil
}
let url = URL(fileURLWithPath: path)
guard let gifData = try? Data(contentsOf: url),
let source = CGImageSourceCreateWithData(gifData as CFData, nil) else { return nil }
var images = [UIImage]()
let imageCount = CGImageSourceGetCount(source)
for i in 0 ..< imageCount {
if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
images.append(UIImage(cgImage: image))
}
}
let gifImageView = UIImageView(frame: frame)
gifImageView.animationImages = images
return gifImageView
}
}
To Use:
guard let confettiImageView = UIImageView.fromGif(frame: view.frame, resourceName: "confetti") else { return }
view.addSubview(confettiImageView)
confettiImageView.startAnimating()
Repeat and duration customizations using UIImageView APIs.
confettiImageView.animationDuration = 3
confettiImageView.animationRepeatCount = 1
When you are done animating the gif and want to release the memory.
confettiImageView.animationImages = nil