If you need to pass the asterisk symbol, you have to wrap it with quotes.
In my case, I need to configure cors for websockets. So, I decided to put cors urls into application.yml. For prod env I'll use specific urls, but for dev it's ok to use just *.
In yml file I have:
websocket:
cors: "*"
In Config class I have:
@Value("${websocket.cors}")
private String[] cors;
This answer to a similar question describes how to extend the properties plugin so it can use a remote descriptor for the properties file. The descriptor is basically a jar artifact containing a properties file (the properties file is included under src/main/resources).
The descriptor is added as a dependency to the extended properties plugin so it is on the plugin's classpath. The plugin will search the classpath for the properties file, read the file''s contents into a Properties instance, and apply those properties to the project's configuration so they can be used elsewhere.
In configuration class
@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {
@Autowired
Environment env;
@Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}
Word of warning: if you put config files in your WEB-INF/classes
folder, and your IDE, say Eclipse, does a clean/rebuild, it will nuke your conf files unless they were in the Java source directory. BalusC's great answer alludes to that in option 1 but I wanted to add emphasis.
I learned the hard way that if you "copy" a web project in Eclipse, it does a clean/rebuild from any source folders. In my case I had added a "linked source dir" from our POJO java library, it would compile to the WEB-INF/classes
folder. Doing a clean/rebuild in that project (not the web app project) caused the same problem.
I thought about putting my confs in the POJO src folder, but these confs are all for 3rd party libs (like Quartz or URLRewrite) that are in the WEB-INF/lib
folder, so that didn't make sense. I plan to test putting it in the web projects "src" folder when i get around to it, but that folder is currently empty and having conf files in it seems inelegant.
So I vote for putting conf files in WEB-INF/commonConfFolder/filename.properties
, next to the classes folder, which is Balus option 2.
To add to Joachim Sauer's answer, if you ever need to do this in a static context, you can do something like the following:
static {
Properties prop = new Properties();
InputStream in = CurrentClassName.class.getResourceAsStream("foo.properties");
prop.load(in);
in.close()
}
(Exception handling elided, as before.)
Writing the properties file with multiple comments is not supported. Why ?
PropertyFile.java
public class PropertyFile extends Task {
/* ========================================================================
*
* Instance variables.
*/
// Use this to prepend a message to the properties file
private String comment;
private Properties properties;
The ant property file task is backed by a java.util.Properties
class which stores comments using the store() method. Only one comment is taken from the task and that is passed on to the Properties
class to save into the file.
The way to get around this is to write your own task that is backed by commons properties instead of java.util.Properties
. The commons properties file is backed by a property layout which allows settings comments for individual keys in the properties file. Save the properties file with the save() method and modify the new task to accept multiple comments through <comment>
elements.
@Value Spring annotation is used for injecting values into fields in Spring-manged beans, and it can be applied to the field or constructor/method parameter level.
Examples
@Value("string value identifire in property file")
private String stringValue;
We can also use the @Value annotation to inject a Map property.
First, we'll need to define the property in the {key: ‘value' }
form in our properties file:
valuesMap={key1: '1', key2: '2', key3: '3'}
Not that the values in the Map must be in single quotes.
Now inject this value from the property file as a Map:
@Value("#{${valuesMap}}")
private Map<String, Integer> valuesMap;
To get the value of a specific key
@Value("#{${valuesMap}.key1}")
private Integer valuesMapKey1;
@Value("#{'${listOfValues}'.split(',')}")
private List<String> valuesList;
Warning!
This is a list of random books of diverse quality. In the view of some people (with some justification), it is no longer a list of recommended books. Some of the listed books contain blatantly incorrect statements or teach wrong/harmful practices. People who are aware of such books can edit this answer to help improve it. See The C book list has gone haywire. What to do with it?, and also Deleted question audit 2018.
The C Programming Language (2nd Edition) - Brian W. Kernighan and Dennis M. Ritchie (1988). Still a good, short but complete introduction to C (C90, not C99 or later versions), written by the inventor of C. However, the language has changed and good C style has developed in the last 25 years, and there are parts of the book that show its age.
C: A Reference Manual (5th Edition) - Samuel P. Harbison and Guy R. Steele (2002). An excellent reference book on C, up to and including C99. It is not a tutorial, and probably unfit for beginners. It's great if you need to write a compiler for C, as the authors had to do when they started.
C Pocket Reference (O'Reilly) - Peter Prinz and Ulla Kirch-Prinz (2002).
The comp.lang.c FAQ - Steve Summit. Web site with answers to many questions about C.
Various versions of the C language standards can be found here. There is an online version of the draft C11 standard.
The new C standard - an annotated reference (Free PDF) - Derek M. Jones (2009). The "new standard" referred to is the old C99 standard rather than C11.
C Programming: A Modern Approach (2nd Edition) - K. N. King (2008). A good book for learning C.
Programming in C (4th Edition) - Stephen Kochan (2014). A good general introduction and tutorial.
C Primer Plus (5th Edition) - Stephen Prata (2004)
A Book on C - Al Kelley/Ira Pohl (1998).
The C Book (Free Online) - Mike Banahan, Declan Brady, and Mark Doran (1991).
C: How to Program (8th Edition) - Paul Deitel and Harvey M. Deitel (2015). Lots of good tips and best practices for beginners. The index is very good and serves as a decent reference (just not fully comprehensive, and very shallow).
Head First C - David Griffiths and Dawn Griffiths (2012).
Beginning C (5th Edition) - Ivor Horton (2013). Very good explanation of pointers, using lots of small but complete programs.
Sams Teach Yourself C in 21 Days - Bradley L. Jones and Peter Aitken (2002). Very good introductory stuff.
C In Easy Steps (5th Edition) - Mike McGrath (2018). It is a good book for learning and referencing C.
Effective C - Robert C Seacord (2020). A good introduction to modern C, including chapters on dynamic memory allocation, on program structure, and on debugging, testing and analysis. It has some pointers toward probable C2x features.
Modern C — Jens Gustedt (2017 1st Edn; 2020 2nd Edn). Covers C in 5 levels (encounter, acquaintance, cognition, experience, ambition) from beginning C to advanced C. It covers C11 and C17, including threads and atomic access, which few other books do. Not all compilers recognize these features in all environments.
C Interfaces and Implementations - David R. Hanson (1997). Provides information on how to define a boundary between an interface and implementation in C in a generic and reusable fashion. It also demonstrates this principle by applying it to the implementation of common mechanisms and data structures in C, such as lists, sets, exceptions, string manipulation, memory allocators, and more. Basically, Hanson took all the code he'd written as part of building Icon and lcc and pulled out the best bits in a form that other people could reuse for their own projects. It's a model of good C programming using modern design techniques (including Liskov's data abstraction), showing how to organize a big C project as a bunch of useful libraries.
The C Puzzle Book - Alan R. Feuer (1998)
The Standard C Library - P.J. Plauger (1992). It contains the complete source code to an implementation of the C89 standard library, along with extensive discussions about the design and why the code is designed as shown.
21st Century C: C Tips from the New School - Ben Klemens (2012). In addition to the C language, the book explains gdb, valgrind, autotools, and git. The comments on style are found in the last part (Chapter 6 and beyond).
Algorithms in C - Robert Sedgewick (1997). Gives you a real grasp of implementing algorithms in C. Very lucid and clear; will probably make you want to throw away all of your other algorithms books and keep this one.
Problem Solving and Program Design in C (6th Edition) - Jeri R. Hanly and Elliot B. Koffman (2009).
Data Structures - An Advanced Approach Using C - Jeffrey Esakov and Tom Weiss (1989).
C Unleashed - Richard Heathfield, Lawrence Kirby, et al. (2000). Not ideal, but it is worth intermediate programmers practicing problems written in this book. This is a good cookbook-like approach suggested by comp.lang.c contributors.
Expert C Programming: Deep C Secrets - Peter van der Linden (1994). Lots of interesting information and war stories from the Sun compiler team, but a little dated in places.
Advanced C Programming by Example - John W. Perry (1998).
Advanced Programming in the UNIX Environment - Richard W. Stevens and Stephen A. Rago (2013). Comprehensive description of how to use the Unix APIs from C code, but not so much about the mechanics of C coding.
Essential C (Free PDF) - Nick Parlante (2003). Note that this describes the C90 language at several points (e.g., in discussing //
comments and placement of variable declarations at arbitrary points in the code), so it should be treated with some caution.
C Programming FAQs: Frequently Asked Questions - Steve Summit (1995). This is the book of the web site listed earlier. It doesn't cover C99 or the later standards.
C in a Nutshell - Peter Prinz and Tony Crawford (2005). Excellent book if you need a reference for C99.
Functional C - Pieter Hartel and Henk Muller (1997). Teaches modern practices that are invaluable for low-level programming, with concurrency and modularity in mind.
The Practice of Programming - Brian W. Kernighan and Rob Pike (1999). A very good book to accompany K&R. It uses C++ and Java too.
C Traps and Pitfalls by A. Koenig (1989). Very good, but the C style pre-dates standard C, which makes it less recommendable these days.
Some have argued for the removal of 'Traps and Pitfalls' from this list because it has trapped some people into making mistakes; others continue to argue for its inclusion. Perhaps it should be regarded as an 'expert' book because it requires a moderately extensive knowledge of C to understand what's changed since it was published.
MISRA-C - industry standard published and maintained by the Motor Industry Software Reliability Association. Covers C89 and C99.
Although this isn't a book as such, many programmers recommend reading and implementing as much of it as possible. MISRA-C was originally intended as guidelines for safety-critical applications in particular, but it applies to any area of application where stable, bug-free C code is desired (who doesn't want fewer bugs?). MISRA-C is becoming the de facto standard in the whole embedded industry and is getting increasingly popular even in other programming branches. There are (at least) three publications of the standard (1998, 2004, and the current version from 2012). There is also a MISRA Compliance Guidelines document from 2016, and MISRA C:2012 Amendment 1 — Additional Security Guidelines for MISRA C:2012 (published in April 2016).
Note that some of the strictures in the MISRA rules are not appropriate to every context. For example, directive 4.12 states "Dynamic memory allocation shall not be used". This is appropriate in the embedded systems for which the MISRA rules are designed; it is not appropriate everywhere. (Compilers, for instance, generally use dynamic memory allocation for things like symbol tables, and to do without dynamic memory allocation would be difficult, if not preposterous.)
Archived lists of ACCU-reviewed books on Beginner's C (116 titles) from 2007 and Advanced C (76 titles) from 2008. Most of these don't look to be on the main site anymore, and you can't browse that by subject anyway.
There is a list of books and tutorials to be cautious about at the ISO 9899 Wiki, which is not itself formally associated with ISO or the C standard, but contains information about the C standard (though it hails the release of ISO 9899:2011 and does not mention the release of ISO 9899:2018).
Be wary of books written by Herbert Schildt. In particular, you should stay away from C: The Complete Reference (4th Edition, 2000), known in some circles as C: The Complete Nonsense.
Also do not use the book Let Us C (16th Edition, 2017) by Yashwant Kanetkar. Many people view it as an outdated book that teaches Turbo C and has lots of obsolete, misleading and incorrect material. For example, page 137 discusses the expected output from printf("%d %d %d\n", a, ++a, a++)
and does not categorize it as undefined behaviour as it should. It also consistently promotes unportable and buggy coding practices, such as using gets
, %[\n]s
in scanf
, storing return value of getchar
in a variable of type char
or using fflush
on stdin
.
Learn C The Hard Way (2015) by Zed Shaw. A book with mixed reviews. A critique of this book by Tim Hentenaar:
To summarize my views, which are laid out below, the author presents the material in a greatly oversimplified and misleading way, the whole corpus is a bundled mess, and some of the opinions and analyses he offers are just plain wrong. I've tried to view this book through the eyes of a novice, but unfortunately I am biased by years of experience writing code in C. It's obvious to me that either the author has a flawed understanding of C, or he's deliberately oversimplifying to the point where he's actually misleading the reader (intentionally or otherwise).
"Learn C The Hard Way" is not a book that I could recommend to someone who is both learning to program and learning C. If you're already a competent programmer in some other related language, then it represents an interesting and unusual exposition on C, though I have reservations about parts of the book. Jonathan Leffler
Other contributors, not necessarily credited in the revision history, include:
Alex Lockwood,
Ben Jackson,
Bubbles,
claws,
coledot,
Dana Robinson,
Daniel Holden,
desbest,
Dervin Thunk,
dwc,
Erci Hou,
Garen,
haziz,
Johan Bezem,
Jonathan Leffler,
Joshua Partogi,
Lucas,
Lundin,
Matt K.,
mossplix,
Matthieu M.,
midor,
Nietzche-jou,
Norman Ramsey,
r3st0r3,
ridthyself,
Robert S. Barnes,
Steve Summit,
Tim Ring,
Tony Bai,
VMAtm
Don't use fixed:
.myimage {
background:url(admin-user-bg.png) no-repeat top center;
background: transparent url("yourimage.png") no-repeat top center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: 100%;
height: 500px;
}
The principles of good commenting are fairly subjective, but here are some guidelines:
object explorer > right-click a table > Script table as > SELECT to > Clipboard
Then you can just paste in the section where you want that as a sub query.
Create you own templates with only a code snippet. Then instead opening the template as a new document just drag it to you current query to insert the snippet.
A snippet can simply be a set of header with comments or just some simple piece of code.
If you wont remember to start a transaction before your delete statemens you can go to options and set implicit transactions by default in all your queries. They require always an explicit commit / rollback.
Go to options and set isolation level to READ_UNCOMMITED by default. This way you dont need to type a NOLOCK in all your ad hoc queries. Just dont forget to place the table hint when writing a new view or stored procedure.
Your login has a default database set by the DBA (To me is usually the undesired one almost every time).
If you want it to be a different one because of the project you are currently working on.
In 'Registered Servers pane' > Right click > Properties > Connection properties tab > connect to database.
(These you might already have done though)
Register the server multiple times, each with a different login. You can then have the same server in the object browser open multiple times (each with a different login).
To execute the same query you already wrote with a different login, instead of copying the query just do a right click over the query pane > Connection > Change connection.
I am not sure you can dynamically change profiles.
Why not just have an internal properties file with the spring.config.location property set to your desired outside location, and the properties file at that location (outside the jar) have the spring.profiles.active property set?
Better yet, have an internal properties file, specific to dev profile (has spring.profiles.active=dev) and leave it like that, and when you want to deploy in production, specify a new location for your properties file, which has spring.profiles.active=prod:
java -jar myjar.jar --spring.config.location=D:\wherever\application.properties
KISS : Keep it simple, stupid
Way A: Implement an own SortableBindingList class when like to use DataBinding and sorting.
Way B: Use a List<string> sorting works also but does not work with DataBinding.
Just use a if() { } else if () { }
chain. Using a hash value is going to be a maintenance nightmare. switch
is intended to be a low-level statement which would not be appropriate for string comparisons.
You can use below code. Here in this example I have used h1
tag and added an attribute data-title-text="Display Text"
which will appear with different color text on h1
tag text element, which gives effect halfcolored text as shown in below example
body {_x000D_
text-align: center;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
color: #111;_x000D_
font-family: arial;_x000D_
position: relative;_x000D_
font-family: 'Oswald', sans-serif;_x000D_
display: inline-block;_x000D_
font-size: 2.5em;_x000D_
}_x000D_
_x000D_
h1::after {_x000D_
content: attr(data-title-text);_x000D_
color: #e5554e;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
clip: rect(0, 1000px, 30px, 0);_x000D_
}
_x000D_
<h1 data-title-text="Display Text">Display Text</h1>
_x000D_
For linux users, you should know the following:
$CLASSPATH is specifically what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override). Using -cp (--classpath) requires that you keep track of all the directories manually and copy-paste that line every time you run the program (not preferable IMO).
The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:
export CLASSPATH=.
export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.
echo $CLASSPATH
is super handy, and what it returns should read like a colon-separated list of all the directories you want java looking in for what it needs to run your script.
Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html
Good question... I find that coders typically use the declaration to declare defaults. I've been held to one way (or warned) or the other too based on the compiler
void testFunct(int nVal1, int nVal2=500);
void testFunct(int nVal1, int nVal2)
{
using namespace std;
cout << nVal1 << << nVal2 << endl;
}
Presently I am working on web services where my function is defined and it was throwing an error undefined function.I just added this in autoload.php in codeigniter
$autoload['helper'] = array('common','security','url');
common is the name of my controller.
"copysign" is defined by IEEE 754, and part of the C99 specification. That's why it's in Python. The function cannot be implemented in full by abs(x) * sign(y) because of how it's supposed to handle NaN values.
>>> import math
>>> math.copysign(1, float("nan"))
1.0
>>> math.copysign(1, float("-nan"))
-1.0
>>> math.copysign(float("nan"), 1)
nan
>>> math.copysign(float("nan"), -1)
nan
>>> float("nan") * -1
nan
>>> float("nan") * 1
nan
>>>
That makes copysign() a more useful function than sign().
As to specific reasons why IEEE's signbit(x) is not available in standard Python, I don't know. I can make assumptions, but it would be guessing.
The math module itself uses copysign(1, x) as a way to check if x is negative or non-negative. For most cases dealing with mathematical functions that seems more useful than having a sign(x) which returns 1, 0, or -1 because there's one less case to consider. For example, the following is from Python's math module:
static double
m_atan2(double y, double x)
{
if (Py_IS_NAN(x) || Py_IS_NAN(y))
return Py_NAN;
if (Py_IS_INFINITY(y)) {
if (Py_IS_INFINITY(x)) {
if (copysign(1., x) == 1.)
/* atan2(+-inf, +inf) == +-pi/4 */
return copysign(0.25*Py_MATH_PI, y);
else
/* atan2(+-inf, -inf) == +-pi*3/4 */
return copysign(0.75*Py_MATH_PI, y);
}
/* atan2(+-inf, x) == +-pi/2 for finite x */
return copysign(0.5*Py_MATH_PI, y);
There you can clearly see that copysign() is a more effective function than a three-valued sign() function.
You wrote:
If I were a python designer, I would been the other way around: no cmp() builtin, but a sign()
That means you don't know that cmp() is used for things besides numbers. cmp("This", "That") cannot be implemented with a sign() function.
Edit to collate my additional answers elsewhere:
You base your justifications on how abs() and sign() are often seen together. As the C standard library does not contain a 'sign(x)' function of any sort, I don't know how you justify your views. There's an abs(int) and fabs(double) and fabsf(float) and fabsl(long) but no mention of sign. There is "copysign()" and "signbit()" but those only apply to IEEE 754 numbers.
With complex numbers, what would sign(-3+4j) return in Python, were it to be implemented? abs(-3+4j) return 5.0. That's a clear example of how abs() can be used in places where sign() makes no sense.
Suppose sign(x) were added to Python, as a complement to abs(x). If 'x' is an instance of a user-defined class which implements the __abs__(self) method then abs(x) will call x.__abs__(). In order to work correctly, to handle abs(x) in the same way then Python will have to gain a sign(x) slot.
This is excessive for a relatively unneeded function. Besides, why should sign(x) exist and nonnegative(x) and nonpositive(x) not exist? My snippet from Python's math module implementation shows how copybit(x, y) can be used to implement nonnegative(), which a simple sign(x) cannot do.
Python should support have better support for IEEE 754/C99 math function. That would add a signbit(x) function, which would do what you want in the case of floats. It would not work for integers or complex numbers, much less strings, and it wouldn't have the name you are looking for.
You ask "why", and the answer is "sign(x) isn't useful." You assert that it is useful. Yet your comments show that you do not know enough to be able to make that assertion, which means you would have to show convincing evidence of its need. Saying that NumPy implements it is not convincing enough. You would need to show cases of how existing code would be improved with a sign function.
And that it outside the scope of StackOverflow. Take it instead to one of the Python lists.
Here's a stored procedure that will put the first word found into First Name, the last word into Last Name and everything in between into Middle Name.
create procedure [dbo].[import_ParseName]
(
@FullName nvarchar(max),
@FirstName nvarchar(255) output,
@MiddleName nvarchar(255) output,
@LastName nvarchar(255) output
)
as
begin
set @FirstName = ''
set @MiddleName = ''
set @LastName = ''
set @FullName = ltrim(rtrim(@FullName))
declare @ReverseFullName nvarchar(max)
set @ReverseFullName = reverse(@FullName)
declare @lengthOfFullName int
declare @endOfFirstName int
declare @beginningOfLastName int
set @lengthOfFullName = len(@FullName)
set @endOfFirstName = charindex(' ', @FullName)
set @beginningOfLastName = @lengthOfFullName - charindex(' ', @ReverseFullName) + 1
set @FirstName = case when @endOfFirstName <> 0
then substring(@FullName, 1, @endOfFirstName - 1)
else ''
end
set @MiddleName = case when (@endOfFirstName <> 0 and @beginningOfLastName <> 0 and @beginningOfLastName > @endOfFirstName)
then ltrim(rtrim(substring(@FullName, @endOfFirstName , @beginningOfLastName - @endOfFirstName)))
else ''
end
set @LastName = case when @beginningOfLastName <> 0
then substring(@FullName, @beginningOfLastName + 1 , @lengthOfFullName - @beginningOfLastName)
else ''
end
return
end
And here's me calling it.
DECLARE @FirstName nvarchar(255),
@MiddleName nvarchar(255),
@LastName nvarchar(255)
EXEC [dbo].[import_ParseName]
@FullName = N'Scott The Other Scott Kowalczyk',
@FirstName = @FirstName OUTPUT,
@MiddleName = @MiddleName OUTPUT,
@LastName = @LastName OUTPUT
print @FirstName
print @MiddleName
print @LastName
output:
Scott
The Other Scott
Kowalczyk
As long as you go into the IIS configuration and change the default location from %SystemDrive%\InetPub to %SystemDrive%\www for each of the services (web, ftp) there shouldn't be any problems. Of course, you can't protect against other applications that might install stuff into that directory by default, instead of checking the configuration.
My recommendation? Don't change it -- it's not that hard to live with, and it reduces the confusion level for the next person who has to administrate the machine.
Applets from what I remember do not need a main method, though I am not sure they are technically a program.
Actually, the first one is a bad idea. Use either the second one, or this:
struct greater
{
template<class T>
bool operator()(T const &a, T const &b) const { return a > b; }
};
std::sort(numbers.begin(), numbers.end(), greater());
That way your code won't silently break when someone decides numbers
should hold long
or long long
instead of int
.
If you take advantage of width: 100vw;
and height: 100vh;
, the object with these styles applied will stretch to the full width and height of the device.
Also note, there are times padding and margins can get added to your view, by browsers and the like. I added a *
global no padding and margins so you can see the difference. Keep this in mind.
*{_x000D_
box-sizing: border-box;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
display: grid;_x000D_
border-style: solid;_x000D_
border-color: red;_x000D_
grid-template-columns: repeat(3, 1fr);_x000D_
grid-template-rows: repeat(3, 1fr);_x000D_
grid-gap: 10px;_x000D_
width: 100vw;_x000D_
height: 100vh;_x000D_
}_x000D_
.one {_x000D_
border-style: solid;_x000D_
border-color: blue;_x000D_
grid-column: 1 / 3;_x000D_
grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
border-style: solid;_x000D_
border-color: yellow;_x000D_
grid-column: 2 / 4;_x000D_
grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
border-style: solid;_x000D_
border-color: violet;_x000D_
grid-row: 2 / 5;_x000D_
grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
border-style: solid;_x000D_
border-color: aqua;_x000D_
grid-column: 3;_x000D_
grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
border-style: solid;_x000D_
border-color: green;_x000D_
grid-column: 2;_x000D_
grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
border-style: solid;_x000D_
border-color: purple;_x000D_
grid-column: 3;_x000D_
grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
<div class="one">One</div>_x000D_
<div class="two">Two</div>_x000D_
<div class="three">Three</div>_x000D_
<div class="four">Four</div>_x000D_
<div class="five">Five</div>_x000D_
<div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
I believe that the configure method expects an absolute path. Anyhow, you may also try to load a Properties object first:
Properties props = new Properties();
props.load(new FileInputStream("log4j.properties"));
PropertyConfigurator.configure(props);
If the properties file is in the jar, then you could do something like this:
Properties props = new Properties();
props.load(getClass().getResourceAsStream("/log4j.properties"));
PropertyConfigurator.configure(props);
The above assumes that the log4j.properties is in the root folder of the jar file.
Here is how to do dump the database (with just the schema):
mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql
If you also want the data, remove the --no-data
option.
HTML has little to no vertical positioning due to typographic nature of content layout. Vertical Rule just doesn't fit its semantics.
You can use this:
#!/bin/bash
file="file_you_want_to_delete"
if [ -f "$file" ] ; then
rm "$file"
fi
#!/bin/bash
variable=`ps -ef | grep "port 10 -" | grep -v "grep port 10 -" | awk '{printf $12}'`
echo $variable
Notice that there's no space after the equal sign.
You can also use $()
which allows nesting and is readable.
Seems that currently SWIG is best solution for this:
http://www.swig.org/Doc2.0/Go.html
It supports inheritance and even allows to subclass C++ class with Go struct so when overridden methods are called in C++ code, Go code is fired.
Section about C++ in Go FAQ is updated and now mentions SWIG and no longer says "because Go is garbage-collected it will be unwise to do so, at least naively".
In case of a range
or any other linearly increasing array you can simply calculate the index programmatically, no need to actually iterate over the array at all:
def first_index_calculate_range_like(val, arr):
if len(arr) == 0:
raise ValueError('no value greater than {}'.format(val))
elif len(arr) == 1:
if arr[0] > val:
return 0
else:
raise ValueError('no value greater than {}'.format(val))
first_value = arr[0]
step = arr[1] - first_value
# For linearly decreasing arrays or constant arrays we only need to check
# the first element, because if that does not satisfy the condition
# no other element will.
if step <= 0:
if first_value > val:
return 0
else:
raise ValueError('no value greater than {}'.format(val))
calculated_position = (val - first_value) / step
if calculated_position < 0:
return 0
elif calculated_position > len(arr) - 1:
raise ValueError('no value greater than {}'.format(val))
return int(calculated_position) + 1
One could probably improve that a bit. I have made sure it works correctly for a few sample arrays and values but that doesn't mean there couldn't be mistakes in there, especially considering that it uses floats...
>>> import numpy as np
>>> first_index_calculate_range_like(5, np.arange(-10, 10))
16
>>> np.arange(-10, 10)[16] # double check
6
>>> first_index_calculate_range_like(4.8, np.arange(-10, 10))
15
Given that it can calculate the position without any iteration it will be constant time (O(1)
) and can probably beat all other mentioned approaches. However it requires a constant step in the array, otherwise it will produce wrong results.
A more general approach would be using a numba function:
@nb.njit
def first_index_numba(val, arr):
for idx in range(len(arr)):
if arr[idx] > val:
return idx
return -1
That will work for any array but it has to iterate over the array, so in the average case it will be O(n)
:
>>> first_index_numba(4.8, np.arange(-10, 10))
15
>>> first_index_numba(5, np.arange(-10, 10))
16
Even though Nico Schlömer already provided some benchmarks I thought it might be useful to include my new solutions and to test for different "values".
The test setup:
import numpy as np
import math
import numba as nb
def first_index_using_argmax(val, arr):
return np.argmax(arr > val)
def first_index_using_where(val, arr):
return np.where(arr > val)[0][0]
def first_index_using_nonzero(val, arr):
return np.nonzero(arr > val)[0][0]
def first_index_using_searchsorted(val, arr):
return np.searchsorted(arr, val) + 1
def first_index_using_min(val, arr):
return np.min(np.where(arr > val))
def first_index_calculate_range_like(val, arr):
if len(arr) == 0:
raise ValueError('empty array')
elif len(arr) == 1:
if arr[0] > val:
return 0
else:
raise ValueError('no value greater than {}'.format(val))
first_value = arr[0]
step = arr[1] - first_value
if step <= 0:
if first_value > val:
return 0
else:
raise ValueError('no value greater than {}'.format(val))
calculated_position = (val - first_value) / step
if calculated_position < 0:
return 0
elif calculated_position > len(arr) - 1:
raise ValueError('no value greater than {}'.format(val))
return int(calculated_position) + 1
@nb.njit
def first_index_numba(val, arr):
for idx in range(len(arr)):
if arr[idx] > val:
return idx
return -1
funcs = [
first_index_using_argmax,
first_index_using_min,
first_index_using_nonzero,
first_index_calculate_range_like,
first_index_numba,
first_index_using_searchsorted,
first_index_using_where
]
from simple_benchmark import benchmark, MultiArgument
and the plots were generated using:
%matplotlib notebook
b.plot()
b = benchmark(
funcs,
{2**i: MultiArgument([0, np.arange(2**i)]) for i in range(2, 20)},
argument_name="array size")
The numba function performs best followed by the calculate-function and the searchsorted function. The other solutions perform much worse.
b = benchmark(
funcs,
{2**i: MultiArgument([2**i-2, np.arange(2**i)]) for i in range(2, 20)},
argument_name="array size")
For small arrays the numba function performs amazingly fast, however for bigger arrays it's outperformed by the calculate-function and the searchsorted function.
b = benchmark(
funcs,
{2**i: MultiArgument([np.sqrt(2**i), np.arange(2**i)]) for i in range(2, 20)},
argument_name="array size")
This is more interesting. Again numba and the calculate function perform great, however this is actually triggering the worst case of searchsorted which really doesn't work well in this case.
Another interesting point is how these function behave if there is no value whose index should be returned:
arr = np.ones(100)
value = 2
for func in funcs:
print(func.__name__)
try:
print('-->', func(value, arr))
except Exception as e:
print('-->', e)
With this result:
first_index_using_argmax
--> 0
first_index_using_min
--> zero-size array to reduction operation minimum which has no identity
first_index_using_nonzero
--> index 0 is out of bounds for axis 0 with size 0
first_index_calculate_range_like
--> no value greater than 2
first_index_numba
--> -1
first_index_using_searchsorted
--> 101
first_index_using_where
--> index 0 is out of bounds for axis 0 with size 0
Searchsorted, argmax, and numba simply return a wrong value. However searchsorted
and numba
return an index that is not a valid index for the array.
The functions where
, min
, nonzero
and calculate
throw an exception. However only the exception for calculate
actually says anything helpful.
That means one actually has to wrap these calls in an appropriate wrapper function that catches exceptions or invalid return values and handle appropriately, at least if you aren't sure if the value could be in the array.
Note: The calculate and searchsorted
options only work in special conditions. The "calculate" function requires a constant step and the searchsorted requires the array to be sorted. So these could be useful in the right circumstances but aren't general solutions for this problem. In case you're dealing with sorted Python lists you might want to take a look at the bisect module instead of using Numpys searchsorted.
It's not a cut and paste. The CASE
expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:
SELECT * FROM [Purchasing].[Vendor] WHERE
CASE
WHEN @url IS null OR @url = '' OR @url = 'ALL'
THEN PurchasingWebServiceURL LIKE '%'
WHEN @url = 'blank'
THEN PurchasingWebServiceURL = ''
WHEN @url = 'fail'
THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
ELSE PurchasingWebServiceURL = '%' + @url + '%'
END
I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.
However, since @url
is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?
Following works in Java 8..
List<String[]> addresses = new ArrayList<>();
#include <chrono>
#include <iostream>
int main()
{
std::time_t ct = std::time(0);
char* cc = ctime(&ct);
std::cout << cc << std::endl;
return 0;
}
I encountered a similar problem where SDK manager would flash a command window and die.
This is what worked for me: My processor and OS both are 64-bit. I had installed 64-bit JDK version. The problem wouldn't go away with reinstalling JDK or modifying path. My theory was that SDK Manager may be needed 32-bit version of JDK. Don't know why that should matter but I ended up installing 32-bit version of JDK and magic. And SDK Manager successfully launched.
On Windows 10, cygwin's chmod and chgrp weren't enough for me. I had to right click on the file -> Properties -> Security (tab) and remove all users and groups except for my active user.
Just as an alternative, you can use ancestor
.
//*[title="50"]/ancestor::store
It's more powerful than parent
since it can get even the grandparent or great great grandparent
To break a loop, use break
instead of return
.
Or put the loop or control construct into a function, only functions can return values.
With PostgreSQL 8.4 or newer there is no need to specify the WITH 1
anymore. The start value that was recorded by CREATE SEQUENCE
or last set by ALTER SEQUENCE START WITH
will be used (most probably this will be 1).
Reset the sequence:
ALTER SEQUENCE seq RESTART;
Then update the table's ID column:
UPDATE foo SET id = DEFAULT;
Source: PostgreSQL Docs
Here is an alternative.
var condition = true;
var props = {
value: 'foo',
...( condition && { disabled: true } )
};
var component = <div { ...props } />;
Or its inline version
var condition = true;
var component = (
<div
value="foo"
{ ...( condition && { disabled: true } ) } />
);
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
As part of htmlAttributes,e.g.
Html.BeginForm(
action, controller, FormMethod.Post, new { enctype="multipart/form-data"})
Or you can pass null
for action and controller to get the same default target as for BeginForm() without any parameters:
Html.BeginForm(
null, null, FormMethod.Post, new { enctype="multipart/form-data"})
Try this code,
public void ConnectToAccess()
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data source= C:\Documents and Settings\username\" +
@"My Documents\AccessFile.mdb";
try
{
conn.Open();
// Insert code to process data.
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}
}
http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx
This is an updated version of aphoria's Answer.
I Replaced PSLIST and PSEXEC with TASKKILL and TASKLIST`. As they seem to work better, I couldn't get PSLIST to run in Windows 7.
Also replaced Sleep with TIMEOUT.
This Was everything i needed to get the script running well, and all the additions was provided by the great guys who posted the comments.
Also if there is a delay before the .exe starts it might be worth inserting a Timeout before the :loop.
@ECHO OFF
TASKKILL NOTEPAD
START "" "C:\Program Files\Windows NT\Accessories\wordpad.exe"
:LOOP
tasklist | find /i "WORDPAD" >nul 2>&1
IF ERRORLEVEL 1 (
GOTO CONTINUE
) ELSE (
ECHO Wordpad is still running
Timeout /T 5 /Nobreak
GOTO LOOP
)
:CONTINUE
NOTEPAD
I currently use Corona for business applications with great success. As far as games go, I'm under the impression that it doesn't provide the performance that some of the other cross-platform development engines do. It is worth noting that Carlos (founder of Ansca Mobile/Corona SDK) has started another company on a competing engine; Lanica Platino Engine for Appcelerator Titanium. While I haven't worked with this personally, it does look promising. Keep in mind, however, that it comes with a $999/yr price tag.
All that said, I have been researching Moai for a little while now (since I am already familiar with Lua syntax) and it does seem promising. The fact that it can compile for multiple platforms, not limited to mobile environments, is appealing.
Multimedia Fusion 2 is also a worth contender, considering the complexity of games produced and the performance realized from them. Vincere Totus Astrum (http://gamesare.com) comes to mind.
Assuming that you're constrained to using Date
, you can do the following:
Date diff = new Date(d2.getTime() - d1.getTime());
Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch. Like others have said: the answers in the duplicate question are probably better alternatives (if you aren't tied down to Date
).
Chances are, you'll have cut
as well. If so:
[me@home]$ echo "pid: 1234" | cut -d" " -f2
1234
Try this:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
I got this issue when installing Bootstrap.
The following commands are what worked for me:
npm uninstall @angular-devkit/build-angular
npm install @angular-devkit/[email protected]
urllib
and Django-like regexThe Django URL validation regex was actually pretty good but I needed to tweak it a little bit for my use case. Feel free to adapt it to yours!
import re
import urllib
# Check https://regex101.com/r/A326u1/5 for reference
DOMAIN_FORMAT = re.compile(
r"(?:^(\w{1,255}):(.{1,255})@|^)" # http basic authentication [optional]
r"(?:(?:(?=\S{0,253}(?:$|:))" # check full domain length to be less than or equal to 253 (starting after http basic auth, stopping before port)
r"((?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+" # check for at least one subdomain (maximum length per subdomain: 63 characters), dashes in between allowed
r"(?:[a-z0-9]{1,63})))" # check for top level domain, no dashes allowed
r"|localhost)" # accept also "localhost" only
r"(:\d{1,5})?", # port [optional]
re.IGNORECASE
)
SCHEME_FORMAT = re.compile(
r"^(http|hxxp|ftp|fxp)s?$", # scheme: http(s) or ftp(s)
re.IGNORECASE
)
def validate_url(url: str):
url = url.strip()
if not url:
raise Exception("No URL specified")
if len(url) > 2048:
raise Exception("URL exceeds its maximum length of 2048 characters (given length={})".format(len(url)))
result = urllib.parse.urlparse(url)
scheme = result.scheme
domain = result.netloc
if not scheme:
raise Exception("No URL scheme specified")
if not re.fullmatch(SCHEME_FORMAT, scheme):
raise Exception("URL scheme must either be http(s) or ftp(s) (given scheme={})".format(scheme))
if not domain:
raise Exception("No URL domain specified")
if not re.fullmatch(DOMAIN_FORMAT, domain):
raise Exception("URL domain malformed (domain={})".format(domain))
return url
scheme
and netloc
part of a given URL. (To do this properly, I split the URL with urllib.parse.urlparse()
in the two according parts which are then matched with the corresponding regex terms.)The netloc
part stops before the first occurrence of a slash /
, so port
numbers are still part of the netloc
, e.g.:
https://www.google.com:80/search?q=python
^^^^^ ^^^^^^^^^^^^^^^^^
| |
| +-- netloc (aka "domain" in my code)
+-- scheme
IPv4 addresses are also validated
If you want the URL validator to also work with IPv6 addresses, do the following:
is_valid_ipv6(ip)
from Markus Jarderot's answer, which has a really good IPv6 validator regexand not is_valid_ipv6(domain)
to the last if
Here are some examples of the regex for the netloc
(aka domain
) part in action:
You can use cat
if installed, with the >
caracter.
Here is the manipulation :
cat > file_to_edit
#1 Write or Paste you text
#2 don't forget to leave a blank line at the end of file
#3 Ctrl + C to apply configuration
Now you can see the result with the command
cat file
In the first line of your JS code:
select.addEventListener('change', getSelection(this), false);
you're invoking getSelection by placing (this)
behind the function reference. That is most likely not what you want, because you're now passing the return value of that call to addEventListener, instead of a reference to the actual function itself.
In a function invoked by addEventListener
the value for this
will automatically be set to the object the listener is attached to, productLineSelect
in this case.
If that is what you want, you can just pass the function reference and this
will in this example be select
in invocations from addEventListener:
select.addEventListener('change', getSelection, false);
If that is not what you want, you'd best bind
your value for this to the function you're passing to addEventListener
:
var thisArg = { custom: 'object' };
select.addEventListener('change', getSelection.bind(thisArg), false);
The .bind
part is also a call, but this call just returns the same function we're calling bind
on, with the value for this
inside that function scope fixed to thisArg
, effectively overriding the dynamic nature of this-binding.
To get to your actual question: "How to pass parameters to function in addEventListener?"
You would have to use an additional function definition:
var globalVar = 'global';
productLineSelect.addEventListener('change', function(event) {
var localVar = 'local';
getSelection(event, this, globalVar, localVar);
}, false);
Now we pass the event object, a reference to the value of this
inside the callback of addEventListener, a variable defined and initialised inside that callback, and a variable from outside the entire addEventListener call to your own getSelection
function.
We also might again have an object of our choice to be this
inside the outer callback:
var thisArg = { custom: 'object' };
var globalVar = 'global';
productLineSelect.addEventListener('change', function(event) {
var localVar = 'local';
getSelection(event, this, globalVar, localVar);
}.bind(thisArg), false);
I got the following message, similar to your one:
program: malloc.c:2372: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
Made a mistake some method call before, when using malloc. Erroneously overwrote the multiplication sign '*' with a '+', when updating the factor after sizeof()-operator on adding a field to unsigned char array.
Here is the code responsible for the error in my case:
UCHAR* b=(UCHAR*)malloc(sizeof(UCHAR)+5); b[INTBITS]=(some calculation); b[BUFSPC]=(some calculation); b[BUFOVR]=(some calculation); b[BUFMEM]=(some calculation); b[MATCHBITS]=(some calculation);
In another method later, I used malloc again and it produced the error message shown above. The call was (simple enough):
UCHAR* b=(UCHAR*)malloc(sizeof(UCHAR)*50);
Think using the '+'-sign on the 1st call, which lead to mis-calculus in combination with immediate initialization of the array after (overwriting memory that was not allocated to the array), brought some confusion to malloc's memory map. Therefore the 2nd call went wrong.
Let me help in updating the answers here since new users will find it useful. I believe the aim is to delete the database itself and recreate it using EF Code First approach. 1.Open your project in Visual Studio using the ".sln" extention. 2.Select Server Explorer( it is oftentimes on the left) 3.Select SQL Server Object Explorer. 4.The database you want to delete would be listed under any of the localDB. Right-Click it and select delete.
I find it useful because it allows me to create APIs that are easy to use (you have some callable object that requires some specific arguments), and are easy to implement because you can use Object Oriented practices.
The following is code I wrote yesterday that makes a version of the hashlib.foo
methods that hash entire files rather than strings:
# filehash.py
import hashlib
class Hasher(object):
"""
A wrapper around the hashlib hash algorithms that allows an entire file to
be hashed in a chunked manner.
"""
def __init__(self, algorithm):
self.algorithm = algorithm
def __call__(self, file):
hash = self.algorithm()
with open(file, 'rb') as f:
for chunk in iter(lambda: f.read(4096), ''):
hash.update(chunk)
return hash.hexdigest()
md5 = Hasher(hashlib.md5)
sha1 = Hasher(hashlib.sha1)
sha224 = Hasher(hashlib.sha224)
sha256 = Hasher(hashlib.sha256)
sha384 = Hasher(hashlib.sha384)
sha512 = Hasher(hashlib.sha512)
This implementation allows me to use the functions in a similar fashion to the hashlib.foo
functions:
from filehash import sha1
print sha1('somefile.txt')
Of course I could have implemented it a different way, but in this case it seemed like a simple approach.
Related to this:
If you have something on your canvas and you want to draw something at the back of it - you can do it by changing the context.globalCompositeOperation setting to 'destination-over' - and then return it to 'source-over' when you're done.
var context = document.getElementById('cvs').getContext('2d');_x000D_
_x000D_
// Draw a red square_x000D_
context.fillStyle = 'red';_x000D_
context.fillRect(50,50,100,100);_x000D_
_x000D_
_x000D_
_x000D_
// Change the globalCompositeOperation to destination-over so that anything_x000D_
// that is drawn on to the canvas from this point on is drawn at the back_x000D_
// of what's already on the canvas_x000D_
context.globalCompositeOperation = 'destination-over';_x000D_
_x000D_
_x000D_
_x000D_
// Draw a big yellow rectangle_x000D_
context.fillStyle = 'yellow';_x000D_
context.fillRect(0,0,600,250);_x000D_
_x000D_
_x000D_
// Now return the globalCompositeOperation to source-over and draw a_x000D_
// blue rectangle_x000D_
context.globalCompositeOperation = 'source-over';_x000D_
_x000D_
// Draw a blue rectangle_x000D_
context.fillStyle = 'blue';_x000D_
context.fillRect(75,75,100,100);
_x000D_
<canvas id="cvs" />
_x000D_
No need of storing resultSet values into String and again setting into POJO class. Instead set at the time you are retrieving.
Or best way switch to ORM tools like hibernate instead of JDBC which maps your POJO object direct to database.
But as of now use this:
List<User> users=new ArrayList<User>();
while(rs.next()) {
User user = new User();
user.setUserId(rs.getString("UserId"));
user.setFName(rs.getString("FirstName"));
...
...
...
users.add(user);
}
If you want a generic error you can setup all $.ajax()
(which $.get()
uses underneath) requests jQuery makes to display an error using $.ajaxSetup()
, for example:
$.ajaxSetup({
error: function(xhr, status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error);
}
});
Just run this once before making any AJAX calls (no changes to your current code, just stick this before somewhere). This sets the error
option to default to the handler/function above, if you made a full $.ajax()
call and specified the error
handler then what you had would override the above.
<input type="text" (keypress)="myMethod(myInput.value)" #myInput />
archive .ts
myMethod(value:string){
...
...
}
i fixed my problem by this code on linux file system
if (!file.exists())
Files.createFile(file.toPath());
I wanted a profile picture of size 96x96 with data from api. The following solution worked for me in project Angular 7.
.ts:
@Input() profile;
.html:
<span class="avatar" [ngStyle]="{'background-image': 'url('+ profile?.public_picture +')'}"></span>
.scss:
.avatar {
border-radius: 100%;
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
width: 96px;
height: 96px;
}
Please note that if you write background
instead of 'background-image'
in [ngStyle]
, the styles you write (even in style
of element) for other background properties like background-position/size, etc. won't work. Because you will already fix it's properties with background: 'url(+ property +) (no providers for size, position, etc. !)'
. The [ngStyle]
priority is higher than style
of element. In background
here, only url() property will work. Be sure to use 'background-image'
instead of 'background'
in case you want to write more properties to background image.
Just write the command "ping your server IP" without the double quote. save file name as filename.bat and then run the batch file as administrator
Since String
IS-A CharSequence
, you can pass a String
wherever you need a CharSequence
, or assign a String
to a CharSequence
:
CharSequence cs = "string";
String s = cs.toString();
foo(s); // prints "string"
public void foo(CharSequence cs) {
System.out.println(cs);
}
If you want to convert a CharSequence
to a String
, just use the toString
method that must be implemented by every concrete implementation of CharSequence
.
Hope it helps.
This is a slight modification from a previous solution. My example looks for stderr redirection in bash scripts:
grep '2>' $(find . -name "*.bash")
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
...
@Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
}
find . -type f -printf '%h\n' | sort | uniq -c
gives for example:
5 .
4 ./aln
5 ./aln/iq
4 ./bs
4 ./ft
6 ./hot
Node-sass tries to download the binary for you platform when installing. Node 5 is supported by 3.8 https://github.com/sass/node-sass/releases/tag/v3.8.0 If your Jenkins can't download the prebuilt binary, then you need to follow the platform requirements on Node-gyp README (Python2, VS or MSBuild, ...) If possible I'd suggest updating your Node to at least 6 since 5 isn't supported by Node anymore. If you want to upgrade to 8, you'll need to update node-sass to 4.5.3
Did you update the project (right-click on the project, "Maven" > "Update project...")? Otherwise, you need to check if pom.xml
contains the necessary slf4j dependencies, e.g.:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
I tried the following and it works for me better
Code:
.unstyled-link{
color: inherit;
text-decoration: inherit;
&:link,
&:hover {
color: inherit;
text-decoration: inherit;
}
}
i come across this problem cause my debug.keystore is expired, so i deleted the debug.keystore under .android folder, and the eclipse will regenerate a new debug.keystore, then i fixed th
In case anyone else faces this, it's a case of PHP not having access to the mysql client libraries. Having a MySQL server on the system is not the correct fix. Fix for ubuntu (and PHP 5):
sudo apt-get install php5-mysql
After installing the client, the webserver should be restarted. In case you're using apache, the following should work:
sudo service apache2 restart
I've made a very simple extension method to wait for all threads of a collection:
using System.Collections.Generic;
using System.Threading;
namespace Extensions
{
public static class ThreadExtension
{
public static void WaitAll(this IEnumerable<Thread> threads)
{
if(threads!=null)
{
foreach(Thread thread in threads)
{ thread.Join(); }
}
}
}
}
Then you simply call:
List<Thread> threads=new List<Thread>();
// Add your threads to this collection
threads.WaitAll();
<table style="width: auto;" ...
works fine. Tested in Chrome 38 , IE 11 and Firefox 34.
jsfiddle : http://jsfiddle.net/rpaul/taqodr8o/
Class selectors are prefixed with a dot. Your .find()
is missing that so jQuery thinks you're looking for <myClass>
elements.
var myVar = $("#start").find('.myClass').val();
In my experience, to use wmic
in a script, you need to get the nested quoting right:
wmic product where "name = 'Windows Azure Authoring Tools - v2.3'" call uninstall /nointeractive
quoting both the query and the name. But wmic will only uninstall things installed via windows installer.
With File::Slurp:
use File::Slurp;
my $text = read_file('index.html');
The problem is you're not doing anything with the result of replace
. In Python strings are immutable so anything that manipulates a string returns a new string instead of modifying the original string.
line[8] = line[8].replace(letter, "")
This is an old post, but I was looking for answer to this same question,
Why not try something like:
scale_color_manual(values = c("foo" = "#999999", "bar" = "#E69F00"))
If you have categorical values, I don't see a reason why this should not work.
Yes it is possible without using MySQLi extension.
Simply use CLIENT_MULTI_STATEMENTS
in mysql_connect
's 5th argument.
Refer to the comments below Husni's post for more information.
Steps to create Hash Key.
1: Download openssl from Openssl for Windows . I downloaded the Win64 version
2:Unzip and copy all the files in the bin folder including openssl.exe(All file of bin folder)
3:Goto to the folder where you installed JDK for me it’s C:\Program Files\Java\jdk1.8.0_05\bin
4:Paste all the files you copied from Openssl’s bin folder to the Jdk folder.
then go C:\Program Files\Java\jdk1.8.0_05\bin and press shift key and right click and open cmd
C:\Program Files\Java\jdk1.8.0_05\bin>//cmd path
that is for Sha1 past this
keytool -exportcert -alias androiddebugkey -keystore "C:\User\ABC\.android.keystore" | openssl sha1 -binary | openssl base64
//and ABC is system name put own system name
Other than the builtin developer tools, there is none that i know of. You might, however, be able to use Firebug Lite.
Well, I had the same issue as I have two postgress versions installed.
Just use the proper pg_dump and you don't need to change anything, in your case:
$> /usr/lib/postgresql/9.2/bin/pg_dump books > books.out
Turns out, as is often the case, it was a stupid error on my part. The way I was testing this, I wasn't rebuilding the Department table after changing the data type from varchar(50) to varchar(200); I was just re-running the insert command, still with the column as varchar(50).
Check and Try the below script (Unit Tested)-
--Declaring
DECLARE @Tbl TABLE(col_1 VARCHAR(100));
--Test Samples
INSERT INTO @Tbl (col_1)
VALUES
(' EY y
Salem')
, (' EY P ort Chennai ')
, (' EY Old Park ')
, (' EY ')
, (' EY ')
,(''),(null),('d
f');
SELECT col_1 AS INPUT,
LTRIM(RTRIM(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(col_1,CHAR(10),' ')
,CHAR(11),' ')
,CHAR(12),' ')
,CHAR(13),' ')
,CHAR(14),' ')
,CHAR(160),' ')
,CHAR(13)+CHAR(10),' ')
,CHAR(9),' ')
,' ',CHAR(17)+CHAR(18))
,CHAR(18)+CHAR(17),'')
,CHAR(17)+CHAR(18),' ')
)) AS [OUTPUT]
FROM @Tbl;
Comment.find(:all, :conditions =>["date(created_at) BETWEEN ? AND ? ", '2011-11-01','2011-11-15'])
To simulate an event, you could to use trigger
JQuery functionnality.
$('#foo').on('click', function() {
alert($(this).text());
});
$('#foo').trigger('click');
You have to insert the elements using the insert method present in vectors STL, check the below program to add the elements to it, and you can use in the same way in your program.
#include <iostream>
#include <vector>
#include <string.h>
int main ()
{
std::vector<std::string> myvector ;
std::vector<std::string>::iterator it;
it = myvector.begin();
std::string myarray [] = { "Hi","hello","wassup" };
myvector.insert (myvector.begin(), myarray, myarray+3);
std::cout << "myvector contains:";
for (it=myvector.begin(); it<myvector.end(); it++)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
ProgressBar is very simple and easy to use, i am intending to make this same as simple progress dialog. first step is that you can make xml layout of the dialog that you want to show, let say we name this layout
layout_loading_dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="20dp">
<ProgressBar
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4"
android:gravity="center"
android:text="Please wait! This may take a moment." />
</LinearLayout>
next step is create AlertDialog which will show this layout with ProgressBar
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false); // if you want user to wait for some process to finish,
builder.setView(R.layout.layout_loading_dialog);
AlertDialog dialog = builder.create();
now all that is left is to show and hide this dialog in our click events like this
dialog.show(); // to show this dialog
dialog.dismiss(); // to hide this dialog
and thats it, it should work, as you can see it is farely simple and easy to implement ProgressBar instead of ProgressDialog. now you can show/dismiss this dialog box in either Handler or ASyncTask, its up to your need
Add /Y to the command line
In Java script you declare array as below:
var array=[];
array.push();
and for arraylist or object or array you have to use json; and Serialize it using json by using following code:
var serializedMyObj = JSON.stringify(myObj);
Create a function that addresses all the whitespace possibilites and enable only those that seem appropriate:
SELECT dbo.ShowWhiteSpace(myfield) from mytable
Uncomment only those whitespace cases you want to test for:
CREATE FUNCTION dbo.ShowWhiteSpace (@str varchar(8000))
RETURNS varchar(8000)
AS
BEGIN
DECLARE @ShowWhiteSpace varchar(8000);
SET @ShowWhiteSpace = @str
SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(32), '[?]')
SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(13), '[CR]')
SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(10), '[LF]')
SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(9), '[TAB]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(1), '[SOH]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(2), '[STX]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(3), '[ETX]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(4), '[EOT]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(5), '[ENQ]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(6), '[ACK]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(7), '[BEL]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(8), '[BS]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(11), '[VT]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(12), '[FF]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(14), '[SO]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(15), '[SI]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(16), '[DLE]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(17), '[DC1]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(18), '[DC2]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(19), '[DC3]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(20), '[DC4]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(21), '[NAK]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(22), '[SYN]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(23), '[ETB]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(24), '[CAN]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(25), '[EM]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(26), '[SUB]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(27), '[ESC]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(28), '[FS]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(29), '[GS]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(30), '[RS]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(31), '[US]')
RETURN(@ShowWhiteSpace)
END
Any problems with the following way of doing it?
int CharToInt(const char c)
{
switch (c)
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
default:
return 0;
}
}
By adding a custom view with the background color of your own you can have a custom selection style in table view.
let customBGColorView = UIView()
customBGColorView.backgroundColor = UIColor(hexString: "#FFF900")
cellObj.selectedBackgroundView = customBGColorView
Add this 3 line code in cellForRowAt method of TableView. I have used an extension in UIColor to add color with hexcode. Put this extension code at the end of any Class(Outside the class's body).
extension UIColor {
convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
Very simple , using Alt fragment
Lets take an example of sequence diagram for an ATM machine.Let's say here you want
IF card inserted is valid then prompt "Enter Pin"....ELSE prompt "Invalid Pin"
Then here is the sequence diagram for the same
Hope this helps!
Because of changes to how tracking branches are created and pushed I no longer recommend renaming branches. This is what I recommend now:
Make a copy of the branch at its current state:
git branch crazyexperiment
(The git branch <name>
command will leave you with your current branch still checked out.)
Reset your current branch to your desired commit with git reset
:
git reset --hard c2e7af2b51
(Replace c2e7af2b51
with the commit that you want to go back to.)
When you decide that your crazy experiment branch doesn't contain anything useful, you can delete it with:
git branch -D crazyexperiment
It's always nice when you're starting out with history-modifying git commands (reset, rebase) to create backup branches before you run them. Eventually once you're comfortable you won't find it necessary. If you do modify your history in a way that you don't want and haven't created a backup branch, look into git reflog
. Git keeps commits around for quite a while even if there are no branches or tags pointing to them.
A slightly less scary way to do this than the git reset --hard
method is to create a new branch. Let's assume that you're on the master
branch and the commit you want to go back to is c2e7af2b51
.
Rename your current master branch:
git branch -m crazyexperiment
Check out your good commit:
git checkout c2e7af2b51
Make your new master branch here:
git checkout -b master
Now you still have your crazy experiment around if you want to look at it later, but your master branch is back at your last known good point, ready to be added to. If you really want to throw away your experiment, you can use:
git branch -D crazyexperiment
First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.
Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.
Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.
Some other things you can check would be to run the following query while the CPU load is high:
SHOW PROCESSLIST;
This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).
You'll also want to keep an eye on things like your buffer sizes, table cache, query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.
You'll also probably want to give the following a read over as they contain some good information.
It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.
You can also add --disable-session-crashed-bubble to eliminate the errors that come up after a crash or improper shutdown.
Have a look at content negotiation in the WebAPI. These (Part 1 & Part 2) wonderfully detailed and thorough blog posts explain how it works.
In short, you are right, and just need to set the Accept
or Content-Type
request headers. Given your Action isn't coded to return a specific format, you can set Accept: application/json
.
@Tim's answer only does half the work -- that gets it into a datetime.datetime object.
To get it into the string format you require, you use datetime.strftime:
print(datetime.strftime('%b %d,%Y'))
this work for me..
var xml = parser.parseFromString('<?xml version="1.0" encoding="utf-8"?><root></root>', "application/xml");
You can do that using your application.properties.
logging.level.=ERROR
-> Sets the root logging level to error
...
logging.level.=DEBUG
-> Sets the root logging level to DEBUG
logging.file=${java.io.tmpdir}/myapp.log
-> Sets the absolute log file path to TMPDIR/myapp.log
A sane default set of application.properties regarding logging using profiles would be:
application.properties:
spring.application.name=<your app name here>
logging.level.=ERROR
logging.file=${java.io.tmpdir}/${spring.application.name}.log
application-dev.properties:
logging.level.=DEBUG
logging.file=
When you develop inside your favourite IDE you just add a -Dspring.profiles.active=dev
as VM argument to the run/debug configuration of your app.
This will give you error only logging in production and debug logging during development WITHOUT writing the output to a log file. This will improve the performance during development ( and save SSD drives some hours of operation ;) ).
correct typo of
struct xyz a;
to
struct xyx a;
Better you can try typedef, easy to b
In Java I'd use Guava's Optional type. Being an actual type you get compiler guarantees about its use. It's easy to bypass it and obtain a NullPointerException
, but at least the signature of the method clearly communicates what it expects as an argument or what it might return.
The simplest way seems to be :
@Around("execution(@MyHandling * com.exemple.YourService.*(..))")
public Object aroundServiceMethodAdvice(final ProceedingJoinPoint pjp)
throws Throwable {
// perform actions before
return pjp.proceed();
// perform actions after
}
It will intercept execution of all methods specifically annotated with '@MyHandling' in 'YourService' class. To intercept all methods without exception, just put the annotation directly on the class.
No matter of the private / public scope here, but keep in mind that spring-aop cannot use aspect for method calls in same instance (typically private ones), because it doesn't use the proxy class in this case.
We use @Around advice here, but it's basically the same syntax with @Before, @After or any advice.
By the way, @MyHandling annotation must be configured like this :
@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.METHOD, ElementType.TYPE })
public @interface MyHandling {
}
Updated 2018-06-08: My previous answer was a bit of hack so I have come back and looked at this again. This is a cleaner Jinja2 approach.
- name: Set fact 4
set_fact:
foo: "{% for i in foo_result.results %}{% do foo.append(i) %}{% endfor %}{{ foo }}"
I am adding this answer as current best answer for Ansible 2.2+ does not completely cover the original question. Thanks to Russ Huguley for your answer this got me headed in the right direction but it left me with a concatenated string not a list. This solution gets a list but becomes even more hacky. I hope this gets resolved in a cleaner manner.
- name: build foo_string
set_fact:
foo_string: "{% for i in foo_result.results %}{{ i.ansible_facts.foo_item }}{% if not loop.last %},{% endif %}{%endfor%}"
- name: set fact foo
set_fact:
foo: "{{ foo_string.split(',') }}"
In case entire entity is being return, better solution in spring JPA is use @Query(value = "from entity where Id in :ids")
This return entity type rather than object type
Assuming your byteData
array is biger than 32 + byteSalt.length()
...you're going to it's length, not byteSalt.length
. You're trying to copy from beyond the array end.
in my.cnf file , please change the following
## Instead of skip-networking the default is now to listen only on ## localhost which is more compatible and is not less secure. ## bind-address = 127.0.0.1
The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.
Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.
If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/
is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/
or http://s3-external-1.amazonaws.com/bucket/
.¹
The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].
S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com
. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.
If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.
However... the two endpoints do not offer the same functionality.
Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.
Choose the correct type of endpoint (REST or web site) for your application:
http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff
¹ s3-external-1.amazonaws.com
has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com
. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2
had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1
so s3-external-2
appears to have no purpose except backwards-compatibility.
I knew that i am too late for this answer, but i hope this will help to other who are facing and who will face.
As you have written h_url is global var like var = h_url;
so you can use that variable anywhere in your file.
h_url=document.getElementById("u").value;
Here h_url contain value of your search box text value whatever user has typed.
document.getElementById("u");
This is the identifier of your form field with some specific ID
.
Your Search Field without id
<input type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
Alter Search Field with id
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
When you click on submit that will try to fetch value from document.getElementById("u").value;
which is syntactically right but you haven't define id so that will return null
.
So, Just make sure while you use form fields first define that ID and do other task letter.
I hope this helps you and never get Cannot set property 'value' of null
Error.
[^a-zA-Z0-9]
is a character class matches any non-alphanumeric characters.
Alternatively, [^\w\d]
does the same thing.
Usage:
string regExp = "[^\w\d]";
string tmp = Regex.Replace(n, regExp, "");
Use -->
comboBox1.DataSource = colors.ToList();
Unless the dictionary is converted to list, combo-box can't recognize its members.
Why don't you create a function or class for this navigation and put there active page as a parameter? This way you'd call it as, for example:
$navigation = new Navigation( 1 );
or
$navigation = navigation( 1 );
In general, the most appropriated way to avoid this problem, (also because of better Mockito integration in JUnit) is to use the Setter/Field Injection as described at https://www.baeldung.com/circular-dependencies-in-spring and at https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html
@Component("bean1")
@Scope("view")
public class Bean1 {
private Bean2 bean2;
@Autowired
public void setBean2(Bean2 bean2) {
this.bean2 = bean2;
}
}
@Component("bean2")
@Scope("view")
public class Bean2 {
private Bean1 bean1;
@Autowired
public void setBean1(Bean1 bean1) {
this.bean1 = bean1;
}
}
.table-striped > tbody > tr:nth-child(2n+1) > td, .table-striped > tbody > tr:nth-child(2n+1) > th {
background-color: red;
}
change this line in bootstrap.css or you could use (odd) or (even) instead of (2n+1)
I had this problem because I configured my WCF Service to return a System.Data.DataTable.
It worked fine in my test HTML page, but blew up when I put this in my Windows Form application.
I had to go in and change the Service's Operational Contract signature from DataTable to DataSet and return the data accordingly.
If you have this problem, you may want to add an additional Operational Contract to your Service so you do not have to worry about breaking code that rely on existing Services.
Both of the above answers assume that you only have one row for each user and time_stamp. Depending on the application and the granularity of your time_stamp this may not be a valid assumption. If you need to deal with ties of time_stamp for a given user, you'd need to extend one of the answers given above.
To write this in one query would require another nested sub-query - things will start getting more messy and performance may suffer.
I would have loved to have added this as a comment but I don't yet have 50 reputation so sorry for posting as a new answer!
An old thread, but since I didn't find it elsewhere, here is one more possibility:
If you're using servlet-api 3.0+, then your web.xml must NOT include metadata-complete="true"
attribute
This tells tomcat to map the servlets using data given in web.xml
instead of using the @WebServlet
annotation.
The easiest way to overwrite a text file is to use a public static field.
this will overwrite the file every time because your only using false the first time through.`
public static boolean appendFile;
Use it to allow only one time through the write sequence for the append field of the write code to be false.
// use your field before processing the write code
appendFile = False;
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;
try {
//change this line to read this
// f2 = new FileWriter(fnew,false);
// to read this
f2 = new FileWriter(fnew,appendFile); // important part
f2.write(source);
// change field back to true so the rest of the new data will
// append to the new file.
appendFile = true;
f2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:
MS SQL Server 2012 Schema Setup:
Query 1:
CREATE TABLE #Names
(
Name1 VARCHAR(100),
Name2 VARCHAR(100)
)
INSERT INTO #Names
(Name1, Name2)
VALUES
('Matt', 'Matthew'),
('Matt', 'Marshal'),
('Matt', 'Mattison')
SELECT * FROM #NAMES
| NAME1 | NAME2 |
--------------------
| Matt | Matthew |
| Matt | Marshal |
| Matt | Mattison |
Here a SSMS 2012 screenshot:
Enter the date as a native value 'yyyymmdd'
to avoid regional issues:
select cast('17530101' as datetime)
Yes, it would be great if TSQL had MinDate() = '00010101'
, but no such luck.
You can wrap those elements in anchor tag
like this
<a href="your link here"> <i class="fa fa-dribbble fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-behance-square fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-linkedin-square fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-twitter-square fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-facebook-square fa-4x"></i></a>
Note: Replace href="your link here"
with your desired link e.g. href="https://www.stackoverflow.com"
.
Beside sys.argv
, also take a look at the argparse module, which helps define options and arguments for scripts.
The argparse module makes it easy to write user-friendly command-line interfaces.
Wrapping Richy's code I created a custom UIScrollView class that automates content resizing completely!
SBScrollView.h
@interface SBScrollView : UIScrollView
@end
SBScrollView.m:
@implementation SBScrollView
- (void) layoutSubviews
{
CGFloat scrollViewHeight = 0.0f;
self.showsHorizontalScrollIndicator = NO;
self.showsVerticalScrollIndicator = NO;
for (UIView* view in self.subviews)
{
if (!view.hidden)
{
CGFloat y = view.frame.origin.y;
CGFloat h = view.frame.size.height;
if (y + h > scrollViewHeight)
{
scrollViewHeight = h + y;
}
}
}
self.showsHorizontalScrollIndicator = YES;
self.showsVerticalScrollIndicator = YES;
[self setContentSize:(CGSizeMake(self.frame.size.width, scrollViewHeight))];
}
@end
How to use:
Simply import the .h file to your view controller and
declare a SBScrollView instance instead of the normal UIScrollView one.
This is answered in some of the answers to Can't find how to use HttpContent as well as in this blog post.
In summary, you can't directly set up an instance of HttpContent
because it is an abstract class. You need to use one the classes derived from it depending on your need. Most likely StringContent
, which lets you set the string value of the response, the encoding, and the media type in the constructor. See: http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx
Spring security is a filter based framework, it plants a WALL(HttpFireWall) before your application in terms of proxy filters or spring managed beans. Your request has to pass through multiple filters to reach your API.
WebAsyncManagerIntegrationFilter
Provides integration between the SecurityContext and Spring Web's WebAsyncManager.
SecurityContextPersistenceFilter
This filter will only execute once per request, Populates the SecurityContextHolder with information obtained from the configured SecurityContextRepository prior to the request and stores it back in the repository once the request has completed and clearing the context holder.
Request is checked for existing session. If new request, SecurityContext will be created else if request has session then existing security-context will be obtained from respository.
HeaderWriterFilter
Filter implementation to add headers to the current response.
LogoutFilter
If request url is /logout
(for default configuration) or if request url mathces RequestMatcher
configured in LogoutConfigurer
then
LogoutConfigurer
/
or logout success url configured or invokes logoutSuccessHandler configured.UsernamePasswordAuthenticationFilter
HTTP POST
) default /login
or matches .loginProcessingUrl()
configured in FormLoginConfigurer
then UsernamePasswordAuthenticationFilter
attempts authentication.usernameParameter(String)
, passwordParameter(String)
..loginPage()
overrides defaults Authentication
object(UsernamePasswordAuthenticationToken
or any implementation of Authentication
in case of your custom auth filter) is created. authenticationManager.authenticate(authToken)
will be invokedAuthenticationProvider
authenticate method tries all auth providers and checks any of the auth provider supports
authToken/authentication object, supporting auth provider will be used for authenticating. and returns Authentication object in case of successful authentication else throws AuthenticationException
.authenticationSuccessHandler
will be invoked which redirects to the target url configured(default is /
)SecurityContextHolderAwareRequestFilter
, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container
AnonymousAuthenticationFilter
Detects if there is no Authentication object in the SecurityContextHolder, if no authentication object found, creates Authentication
object (AnonymousAuthenticationToken
) with granted authority ROLE_ANONYMOUS
. Here AnonymousAuthenticationToken
facilitates identifying un-authenticated users subsequent requests.
DEBUG - /app/admin/app-config at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@aeef7b36: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
ExceptionTranslationFilter
, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched
FilterSecurityInterceptor
There will be FilterSecurityInterceptor
which comes almost last in the filter chain which gets Authentication object from SecurityContext
and gets granted authorities list(roles granted) and it will make a decision whether to allow this request to reach the requested resource or not, decision is made by matching with the allowed AntMatchers
configured in HttpSecurityConfiguration
.
Consider the exceptions 401-UnAuthorized and 403-Forbidden. These decisions will be done at the last in the filter chain
Note: User Request flows not only in above mentioned filters, but there are others filters too not shown here.(ConcurrentSessionFilter
,RequestCacheAwareFilter
,SessionManagementFilter
...)
It will be different when you use your custom auth filter instead of UsernamePasswordAuthenticationFilter
.
It will be different if you configure JWT auth filter and omit .formLogin() i.e, UsernamePasswordAuthenticationFilter
it will become entirely different case.
From Documentation ordering of filters is given as
- ChannelProcessingFilter
- ConcurrentSessionFilter
- SecurityContextPersistenceFilter
- LogoutFilter
- X509AuthenticationFilter
- AbstractPreAuthenticatedProcessingFilter
- CasAuthenticationFilter
- UsernamePasswordAuthenticationFilter
- ConcurrentSessionFilter
- OpenIDAuthenticationFilter
- DefaultLoginPageGeneratingFilter
- DefaultLogoutPageGeneratingFilter
- ConcurrentSessionFilter
- DigestAuthenticationFilter
- BearerTokenAuthenticationFilter
- BasicAuthenticationFilter
- RequestCacheAwareFilter
- SecurityContextHolderAwareRequestFilter
- JaasApiIntegrationFilter
- RememberMeAuthenticationFilter
- AnonymousAuthenticationFilter
- SessionManagementFilter
- ExceptionTranslationFilter
- FilterSecurityInterceptor
- SwitchUserFilter
You can also refer
most common way to authenticate a modern web app?
difference between authentication and authorization in context of Spring Security?
With no additional plugin required, this bootstrap solution works great for me:
<div style="position:relative;">
<a class='btn btn-primary' href='javascript:;'>
Choose File...
<input type="file" style='position:absolute;z-index:2;top:0;left:0;filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";opacity:0;background-color:transparent;color:transparent;' name="file_source" size="40" onchange='$("#upload-file-info").html($(this).val());'>
</a>
<span class='label label-info' id="upload-file-info"></span>
</div>
demo:
http://jsfiddle.net/haisumbhatti/cAXFA/1/ (bootstrap 2)
http://jsfiddle.net/haisumbhatti/y3xyU/ (bootstrap 3)
Use double quote to enclose the quote or escape it.
newTemp = mystring.replace(/"/g, "'");
or
newTemp = mystring.replace(/"/g, '\'');
..NET provides cryptographics services in class contained in the System.Security.Cryptography namespace.
Three ways you can do this - from the form designer, select the form, and where you normally see the list of properties, just above it there should be a little lightning symbol - this shows you all the events of the form. Find the form load event in the list, and you should be able to pick ProgramViwer_Load
from the dropdown.
A second way to do it is programmatically - somewhere (constructor maybe) you'd need to add it, something like: ProgramViwer.Load += new EventHandler(ProgramViwer_Load);
A third way using the designer (probably the quickest) - when you create a new form, double click on the middle of it on it in design mode. It'll create a Form load event for you, hook it in, and take you to the event handler code. Then you can just add your two lines and you're good to go!
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
I use Weinre, part of Apache Cordova.
With Weinre, I get Google Chrome's debug console in my desktop browser, and can connect Android to that debug console, and debug HTML and CSS. I can execute Javascript commands in the console, and they affect the Web page in the Android browser. Log messages from Android appear in the desktop debug console.
However I think it's not possible to view or step through the actual Javascript code. So I combine Weinre with log messages.
(I don't know much about JConsole but it seems to me that HTML and CSS inspection isn't possible with JConsole, only Javascript commands and logging (?).)
There are two way you can check condition.
if ($("#checkSurfaceEnvironment-1").is(":checked")) {
// Put your code here if checkbox is checked
}
OR you can use this one also
if($("#checkSurfaceEnvironment-1").prop('checked') == true){
// Put your code here if checkbox is checked
}
I hope this is useful for you.
I used RESTful API in my services, and here is my opinion:
First we must get to a common view: PUT
is used to update an resource not create or get.
I defined resources with: Stateless resource
and Stateful resource
:
Stateless resources For these resources, just return the HttpCode with empty body, it's enough.
Stateful resources For example: the resource's version. For this kind of resources, you must provide the version when you want to change it, so return the full resource or return the version to the client, so the client need't to send a get request after the update action.
But, for a service or system, keep it simple
, clearly
, easy to use and maintain
is the most important thing.
We just started using this slick tool: https://plugins.jquery.com/tablesorter/
There is a video on its use at: http://www.highoncoding.com/Articles/695_Sorting_GridView_Using_JQuery_TableSorter_Plug_in.aspx
$('#tableRoster').tablesorter({
headers: {
0: { sorter: false },
4: { sorter: false }
}
});
With a simple table
<table id="tableRoster">
<thead>
<tr>
<th><input type="checkbox" class="rCheckBox" value="all" id="rAll" ></th>
<th>User</th>
<th>Verified</th>
<th>Recently Accessed</th>
<th> </th>
</tr>
</thead>
hex_map = {0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:'A', 11:'B', 12:'C', 13:'D', 14:'E', 15:'F'}
def to_hex(n):
result = ""
if n == 0:
return '0'
while n != 0:
result += str(hex_map[(n % 16)])
n = n // 16
return '0x'+result[::-1]
Looks like PILlow may have changed tostring()
to tobytes()
. When trying to extract RGBA pixels to get them into an OpenGL texture, the following worked for me (within the glTexImage2D
call which I omit for brevity).
from PIL import Image
img = Image.open("mandrill.png").rotate(180).transpose(Image.FLIP_LEFT_RIGHT)
# use img.convert("RGBA").tobytes() as texels
You can call any language from java using Java Native Interface
bootstrap.js is using jquery library so you need to add jquery library before bootstrap js.
so please add it jquery library like
Note : Please maintain order of js file. html page use top to bottom approach for compilation
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
When trying to set up a .NET Core 1.0 website I got this error, and tried everything else I could find with no luck, including checking the web.config file, IIS_IUSRS permissions, IIS URL rewrite module, etc. In the end, I installed DotNetCore.1.0.0-WindowsHosting.exe from this page: https://www.microsoft.com/net/download and it started working right away.
Specific link to download: https://go.microsoft.com/fwlink/?LinkId=817246
PHPSESSID
reveals you are using PHP. If you don't want this you can easily change the name using the session.name
in your php.ini file or using the session_name()
function.
Really stupid solution but I'll add it here in case anyone gets here from a Google search.
I'd just restarted the SQL service and was getting this error and in my case, just waiting 10 minutes was enough and it was fine again. Seems this is the error you get when it is just starting up.
I was struggling to find a solution for arbitrary length byte sequences that would work under Python 2.x. Finally I wrote this one, it's a bit hacky because it performs a string conversion, but it works.
def signedbytes(data):
"""Convert a bytearray into an integer, considering the first bit as
sign. The data must be big-endian."""
negative = data[0] & 0x80 > 0
if negative:
inverted = bytearray(~d % 256 for d in data)
return -signedbytes(inverted) - 1
encoded = str(data).encode('hex')
return int(encoded, 16)
This function has two requirements:
The input data
needs to be a bytearray
. You may call the function like this:
s = 'y\xcc\xa6\xbb'
n = signedbytes(s)
The data needs to be big-endian. In case you have a little-endian value, you should reverse it first:
n = signedbytes(s[::-1])
Of course, this should be used only if arbitrary length is needed. Otherwise, stick with more standard ways (e.g. struct
).
A couple of things might affect the results you're seeing:
clock_t
as a floating-point type, I don't think it is.1^4
) to do something else than compute the bitwise XOR of 1 and 4., i.e. it's 5.You're not specifying how fast your machine is, but it's not unreasonable for this to run very quickly on modern hardware, no.
If you have it, try adding a call to sleep()
between the start/stop snapshots. Note that sleep()
is POSIX though, not standard C.
For Oracle 11g:
SELECT COL1
FROM TABLE1
WHERE length(COL1) = (SELECT max(length(COL1)) FROM TABLE1);
Please download the latest device from this URL and add to devices.
https://github.com/iGhibli/iOS-DeviceSupport/blob/master/DeviceSupport/
Though this is an old post and have many answers, but here I have my version of code to upload the file to sharepoint 2013 using CSOM(c#)
I hope if you are working with downloading and uploading files then you know how to create Clientcontext
object and Web
object
/* Assuming you have created ClientContext object and Web object*/
string listTitle = "List title where you want your file to upload";
string filePath = "your file physical path";
List oList = web.Lists.GetByTitle(listTitle);
clientContext.Load(oList.RootFolder);//to load the folder where you will upload the file
FileCreationInformation fileInfo = new FileCreationInformation();
fileInfo.Overwrite = true;
fileInfo.Content = System.IO.File.ReadAllBytes(filePath);
fileInfo.Url = fileName;
File fileToUpload = fileCollection.Add(fileInfo);
clientContext.ExecuteQuery();
fileToUpload.CheckIn("your checkin comment", CheckinType.MajorCheckIn);
if (oList.EnableMinorVersions)
{
fileToUpload.Publish("your publish comment");
clientContext.ExecuteQuery();
}
if (oList.EnableModeration)
{
fileToUpload.Approve("your approve comment");
}
clientContext.ExecuteQuery();
And here is the code for download
List oList = web.Lists.GetByTitle("ListNameWhereFileExist");
clientContext.Load(oList);
clientContext.Load(oList.RootFolder);
clientContext.Load(oList.RootFolder.Files);
clientContext.ExecuteQuery();
FileCollection fileCollection = oList.RootFolder.Files;
File SP_file = fileCollection.GetByUrl("fileNameToDownloadWithExtension");
clientContext.Load(SP_file);
clientContext.ExecuteQuery();
var Local_stream = System.IO.File.Open("c:/testing/" + SP_file.Name, System.IO.FileMode.CreateNew);
var fileInformation = File.OpenBinaryDirect(clientContext, SP_file.ServerRelativeUrl);
var Sp_Stream = fileInformation.Stream;
Sp_Stream.CopyTo(Local_stream);
Still there are different ways I believe that can be used to upload and download.
UIStackView
uses constraints internally to position its arranged subviews. Exactly what constraints are created depends on how the stack view itself is configured. By default, a stack view will create constraints that lay out its arranged subviews in a horizontal line, pinning the leading and trailing views to its own leading and trailing edges. So your code would produce a layout that looks like this:
|[view1][view2]|
The space that is allocated to each subview is determined by a number of factors including the subview's intrinsic content size and it's compression resistance and content hugging priorities. By default, UIView
instances don't define an intrinsic content size. This is something that is generally provided by a subclass, such as UILabel
or UIButton
.
Since the content compression resistance and content hugging priorities of two new UIView
instances will be the same, and neither view provides an intrinsic content size, the layout engine must make its best guess as to what size should be allocated to each view. In your case, it is assigning the first view 100% of the available space, and nothing to the second view.
If you modify your code to use UILabel
instances instead, you will get better results:
UILabel *label1 = [UILabel new];
label1.text = @"Label 1";
label1.backgroundColor = [UIColor blueColor];
UILabel *label2 = [UILabel new];
label2.text = @"Label 2";
label2.backgroundColor = [UIColor greenColor];
[self.stack1 addArrangedSubview:label1];
[self.stack1 addArrangedSubview:label2];
Note that it is not necessary to explictly create any constraints yourself. This is the main benefit of using UIStackView
- it hides the (often ugly) details of constraint management from the developer.
You can find a few examples here:
// Fill the DataSet. DataSet ds = new DataSet(); ds.Locale = CultureInfo.InvariantCulture; FillDataSet(ds); DataTable contacts = ds.Tables["Contact"]; DataTable orders = ds.Tables["SalesOrderHeader"]; var query = contacts.AsEnumerable().Join(orders.AsEnumerable(), order => order.Field<Int32>("ContactID"), contact => contact.Field<Int32>("ContactID"), (contact, order) => new { ContactID = contact.Field<Int32>("ContactID"), SalesOrderID = order.Field<Int32>("SalesOrderID"), FirstName = contact.Field<string>("FirstName"), Lastname = contact.Field<string>("Lastname"), TotalDue = order.Field<decimal>("TotalDue") }); foreach (var contact_order in query) { Console.WriteLine("ContactID: {0} " + "SalesOrderID: {1} " + "FirstName: {2} " + "Lastname: {3} " + "TotalDue: {4}", contact_order.ContactID, contact_order.SalesOrderID, contact_order.FirstName, contact_order.Lastname, contact_order.TotalDue); }
Or just google for 'linq join method syntax'.
You can try to implement something like that, look at:
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("juan", 2);
map.put("pedro", 3);
map.put("pablo", 5);
map.put("iphoncio",9)
List<String> indexes = new ArrayList<String>(map.keySet()); // <== Parse
System.out.println(indexes.indexOf("juan")); // ==> 0
System.out.println(indexes.indexOf("iphoncio")); // ==> 3
I hope this works for you.
Debug your CSS for Ghost CSS Elements.
Use this bookmark to debug your CSS: https://blog.wernull.com/2013/04/debug-ghost-css-elements-causing-unwanted-scrolling/
Or add the CSS directly yourself:
* {
background: #000 !important;
color: #0f0 !important;
outline: solid #f00 1px !important;
}
In my case a Facebook Like Button caused the problem.
With ES6 you can simply do:
for(const element of Results) {
element.Active = "false";
}
From the composer site (it's clear enough)
require#
Lists packages required by this package. The package will not be installed unless those requirements can be met.
require-dev (root-only)#
Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the --no-dev option that prevents dev dependencies from being installed.
Using require-dev in Composer you can declare the dependencies you need for development/testing the project but don't need in production. When you upload the project to your production server (using git) require-dev
part would be ignored.
Also check this answer posted by the author and this post as well.
The problem is caused by your #grid
having a width:1140px
.
You need to set a min-width:1140px
on the body
.
This will stop the body
from getting smaller than the #grid
. Remove width:100%
as block level elements take up the available width by default. Live example: http://jsfiddle.net/tw16/LX8R3/
html, body{
margin:0;
padding:0;
min-width: 1140px; /* this is the important part*/
}
#grid-container{
background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
}
#grid{
width:1140px;
margin:0px auto;
}
I had the same problem. The only thing that solved it was merge the content of META-INF/spring.handler and META-INF/spring.schemas of each spring jar file into same file names under my META-INF project.
This two threads explain it better:
http://fortawesome.github.io/Font-Awesome/examples/
<i class="icon-thumbs-up icon-3x main-color"></i>
Here I have defined a global style in my CSS where main-color is a class, in my case it is a light blue hue. I find that using inline styles on Icons with Font Awesome works well, esp in the case when you name your colors semantically, i.e. nav-color if you want a separate color for that, etc.
In this example on their website, and how I have written in my example as well, the newest version of Font Awesome has changed the syntax slightly of adjusting the size.Before it used to be:
icon-xxlarge
where now I have to use:
icon-3x
Of course, this all depends on what version of Font Awesome you have installed on your environment. Hope this helps.
In 2020:
If none of the 30+ answers has worked, you probably need to run git push origin main
(master has been renamed to main at the time of writing this answer)
As the OP references Number of commits on branch in git I want to add that the given answers there also work with any other branch, at least since git version 2.17.1 (and seemingly more reliably than the answer by Peter van der Does):
working correctly:
git checkout current-development-branch
git rev-list --no-merges --count master..
62
git checkout -b testbranch_2
git rev-list --no-merges --count current-development-branch..
0
The last command gives zero commits as expected since I just created the branch. The command before gives me the real number of commits on my development-branch minus the merge-commit(s)
not working correctly:
git checkout current-development-branch
git rev-list --no-merges --count HEAD
361
git checkout -b testbranch_1
git rev-list --no-merges --count HEAD
361
In both cases I get the number of all commits in the development branch and master from which the branches (indirectly) descend.
Consider this example:
public class StringSplit {
public static void main(String args[]) throws Exception{
String testString = "Real|How|To|||";
System.out.println
(java.util.Arrays.toString(testString.split("\\|")));
// output : [Real, How, To]
}
}
The result does not include the empty strings between the "|" separator. To keep the empty strings :
public class StringSplit {
public static void main(String args[]) throws Exception{
String testString = "Real|How|To|||";
System.out.println
(java.util.Arrays.toString(testString.split("\\|", -1)));
// output : [Real, How, To, , , ]
}
}
For more details go to this website: http://www.rgagnon.com/javadetails/java-0438.html
Yes reinstall and select command line to get the svn in Program Files-> Tortoise SVN folder.
create a macro like this
Option Compare Database
Sub a()
DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"
DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"
End Sub
Copy in plain notepad (git clone https://github.com/./Spoon-Knife.git) and paste it in cmd. now it will work.
To make life easier when entering multiple dates/times it is possible to use a custom format to remove the need to enter the colon, and the leading "hour" 0. This however requires a second field for the numerical date to be stored, as the displayed date from the custom format is in base 10.
Displaying a number as a time (no need to enter colons, but no time conversion)
For displaying the times on the sheet, and for entering them without having to type the colon set the cell format to custom and use:
0/:00
Then enter your time. For example, if you wanted to enter 62:30, then you would simply type 6230 and your custom format would visually insert a colon 2 decimal points from the right.
If you only need to display the times, stop here.
Converting number to time
If you need to be able to calculate with the times, you will need to convert them from base 10 into the time format.
This can be done with the following formula (change A2
to the relevant cell reference):
=TIME(0,TRUNC(A2/100),MOD(A2,100))
=TIME
starts the number to time conversion0,
at the beginning of the formula, as the format is always hh,mm,ss
(to display hours and minutes instead of minutes and seconds, place the 0 at the end of the formula).TRUNC(A2/100),
discards the rightmost 2 digits.MOD(A2,100)
keeps the rightmost 2 digits and discards everything to the left.The above formula was found and adapted from this article: PC Mag.com - Easy Date and Time Entry in Excel
Alternatively, you could skip the 0/:00
custom formatting, and just enter your time in a cell to be referenced of the edge of the visible workspace or on another sheet as you would for the custom formatting (ie: 6230 for 62:30)
Then change the display format of the cells with the formula to [m]:ss
as @Sean Chessire suggested.
Here is a screen shot to show what I mean.
On socket.io >=1.0, after the connect event has triggered:
var socket = io('localhost');
var id = socket.io.engine.id
From the definition in objc.h
:
#if (TARGET_OS_IPHONE && __LP64__) || TARGET_OS_WATCH
typedef bool BOOL;
#else
typedef signed char BOOL;
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C"
// even if -funsigned-char is used.
#endif
#define YES ((BOOL)1)
#define NO ((BOOL)0)
So, yes, you can assume that BOOL is a char. You can use the (C99) bool
type, but all of Apple's Objective-C frameworks and most Objective-C/Cocoa code uses BOOL, so you'll save yourself headache if the typedef ever changes by just using BOOL.
I used docker-entrypoint-initdb.d approach (Thanks to @Kuhess) But in my case I want to create my DB based on some parameters I defined in .env file so I did these
1) First I define .env file something like this in my docker root project directory
MYSQL_DATABASE=my_db_name
MYSQL_USER=user_test
MYSQL_PASSWORD=test
MYSQL_ROOT_PASSWORD=test
MYSQL_PORT=3306
2) Then I define my docker-compose.yml file. So I used the args directive to define my environment variables and I set them from .env file
version: '2'
services:
### MySQL Container
mysql:
build:
context: ./mysql
args:
- MYSQL_DATABASE=${MYSQL_DATABASE}
- MYSQL_USER=${MYSQL_USER}
- MYSQL_PASSWORD=${MYSQL_PASSWORD}
- MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
ports:
- "${MYSQL_PORT}:3306"
3) Then I define a mysql folder that includes a Dockerfile. So the Dockerfile is this
FROM mysql:5.7
RUN chown -R mysql:root /var/lib/mysql/
ARG MYSQL_DATABASE
ARG MYSQL_USER
ARG MYSQL_PASSWORD
ARG MYSQL_ROOT_PASSWORD
ENV MYSQL_DATABASE=$MYSQL_DATABASE
ENV MYSQL_USER=$MYSQL_USER
ENV MYSQL_PASSWORD=$MYSQL_PASSWORD
ENV MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD
ADD data.sql /etc/mysql/data.sql
RUN sed -i 's/MYSQL_DATABASE/'$MYSQL_DATABASE'/g' /etc/mysql/data.sql
RUN cp /etc/mysql/data.sql /docker-entrypoint-initdb.d
EXPOSE 3306
4) Now I use mysqldump to dump my db and put the data.sql inside mysql folder
mysqldump -h <server name> -u<user> -p <db name> > data.sql
The file is just a normal sql dump file but I add 2 lines at the beginning so the file would look like this
--
-- Create a database using `MYSQL_DATABASE` placeholder
--
CREATE DATABASE IF NOT EXISTS `MYSQL_DATABASE`;
USE `MYSQL_DATABASE`;
-- Rest of queries
DROP TABLE IF EXISTS `x`;
CREATE TABLE `x` (..)
LOCK TABLES `x` WRITE;
INSERT INTO `x` VALUES ...;
...
...
...
So what happening is that I used "RUN sed -i 's/MYSQL_DATABASE/'$MYSQL_DATABASE'/g' /etc/mysql/data.sql" command to replace the MYSQL_DATABASE
placeholder with the name of my DB that I have set it in .env file.
|- docker-compose.yml
|- .env
|- mysql
|- Dockerfile
|- data.sql
Now you are ready to build and run your container
you can write the function in a separate file (say common-functions.php) and include it wherever needed.
function getEmployeeFullName($employeeId) {
// Write code to return full name based on $employeeId
}
You can include common-functions.php in another file as below.
include('common-functions.php');
echo 'Name of first employee is ' . getEmployeeFullName(1);
You can include any number of files to another file. But including comes with a little performance cost. Therefore include only the files which are really required.
This worked for me
<select ng-init="basicProfile.casteId" ng-model="basicProfile.casteId" class="form-control">
<option value="0">Select Caste....</option>
<option data-ng-repeat="option in formCastes" value="{{option.id}}">{{option.casteName}}</option>
</select>
Check the jQuery FAQ...
You can use the length property of the jQuery collection returned by your selector:
if ( $('#myDiv').length ){}
React + TypeScript inline util method:
const navigateToExternalUrl = (url: string, shouldOpenNewTab: boolean = true) =>
shouldOpenNewTab ? window.open(url, "_blank") : window.location.href = url;
Just for completeness, there has recently been a question on the Jython mailinglist where one of the answers referred to this thread.
The question was how to call a Python script that is contained in a .jar file from within Jython, the suggested answer is as follows (with "InputStream" as explained in one of the answers above:
PythonInterpreter.execfile(InputStream)
By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).
Let's do some examples, from simpler to more difficult.
The view
method returns a tensor with the same data as the self
tensor (which means that the returned tensor has the same number of elements), but with a different shape. For example:
a = torch.arange(1, 17) # a's shape is (16,)
a.view(4, 4) # output below
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
[torch.FloatTensor of size 4x4]
a.view(2, 2, 4) # output below
(0 ,.,.) =
1 2 3 4
5 6 7 8
(1 ,.,.) =
9 10 11 12
13 14 15 16
[torch.FloatTensor of size 2x2x4]
Assuming that -1
is not one of the parameters, when you multiply them together, the result must be equal to the number of elements in the tensor. If you do: a.view(3, 3)
, it will raise a RuntimeError
because shape (3 x 3) is invalid for input with 16 elements. In other words: 3 x 3 does not equal 16 but 9.
You can use -1
as one of the parameters that you pass to the function, but only once. All that happens is that the method will do the math for you on how to fill that dimension. For example a.view(2, -1, 4)
is equivalent to a.view(2, 2, 4)
. [16 / (2 x 4) = 2]
Notice that the returned tensor shares the same data. If you make a change in the "view" you are changing the original tensor's data:
b = a.view(4, 4)
b[0, 2] = 2
a[2] == 3.0
False
Now, for a more complex use case. The documentation says that each new view dimension must either be a subspace of an original dimension, or only span d, d + 1, ..., d + k that satisfy the following contiguity-like condition that for all i = 0, ..., k - 1, stride[i] = stride[i + 1] x size[i + 1]. Otherwise, contiguous()
needs to be called before the tensor can be viewed. For example:
a = torch.rand(5, 4, 3, 2) # size (5, 4, 3, 2)
a_t = a.permute(0, 2, 3, 1) # size (5, 3, 2, 4)
# The commented line below will raise a RuntimeError, because one dimension
# spans across two contiguous subspaces
# a_t.view(-1, 4)
# instead do:
a_t.contiguous().view(-1, 4)
# To see why the first one does not work and the second does,
# compare a.stride() and a_t.stride()
a.stride() # (24, 6, 2, 1)
a_t.stride() # (24, 2, 1, 6)
Notice that for a_t
, stride[0] != stride[1] x size[1] since 24 != 2 x 3
Just in case if any one is stuck like me. After going though the post and some hit and trial this worked for me.
input:not([type="checkbox"])input:not([type="radio"])
N.B. - this question and answer relate to the 2000 version of SQL Server. In later versions, the restriction on INSERT INTO @table_variable ... EXEC ...
were lifted and so it doesn't apply for those later versions.
You'll have to switch to a temp table:
CREATE TABLE #tmp (code varchar(50), mount money)
DECLARE @q nvarchar(4000)
SET @q = 'SELECT coa_code, amount FROM T_Ledger_detail'
INSERT INTO #tmp (code, mount)
EXEC sp_executesql (@q)
SELECT * from #tmp
From the documentation:
A table variable behaves like a local variable. It has a well-defined scope, which is the function, stored procedure, or batch in which it is declared.
Within its scope, a table variable may be used like a regular table. It may be applied anywhere a table or table expression is used in SELECT, INSERT, UPDATE, and DELETE statements. However, table may not be used in the following statements:
INSERT INTO table_variable EXEC stored_procedure
SELECT select_list INTO table_variable statements.
Create a new folder, let's say local-maven-repo
at the root of your Maven project.
Just add a local repo iside your <project>
of your pom.xml
:
<repositories>
<repository>
<id>local-maven-repo</id>
<url>file:///${project.basedir}/local-maven-repo</url>
</repository>
</repositories>
Then for each external jar you want to install, go at the root of your project and execute:
mvn deploy:deploy-file -DgroupId=[GROUP] -DartifactId=[ARTIFACT] -Dversion=[VERS] -Durl=file:./local-maven-repo/ -DrepositoryId=local-maven-repo -DupdateReleaseInfo=true -Dfile=[FILE_PATH]
(Copied from my reply on a similar question)
For anybody else looking, here is a decent set of steps. http://forums.asp.net/t/1678976.aspx/1
Don't forget to manually add your key in OnActionExecuting() like I did.
Works only in Chrome but it can be adapted to other modern browsers. Table falls back to common table with scroll bar in other brws. Uses CSS3 FLEX property.
<table border="1px" class="flexy">
<caption>Lista Sumnjivih vozila:</caption>
<thead>
<tr>
<td>Opis Sumnje</td>
<td>Registarski<br>broj vozila</td>
<td>Datum<br>Vreme</td>
<td>Brzina<br>(km/h)</td>
<td>Lokacija</td>
<td>Status</td>
<td>Akcija</td>
</tr>
</thead>
<tbody>
<tr>
<td>Osumnjicen tranzit</td>
<td>NS182TP</td>
<td>23-03-2014 20:48:08</td>
<td>11.3</td>
<td>Raskrsnica kod pumpe<br></td>
<td></td>
<td>Prikaz</td>
</tr>
<tr>
<tr>
<td>Osumnjicen tranzit</td>
<td>NS182TP</td>
<td>23-03-2014 20:48:08</td>
<td>11.3</td>
<td>Raskrsnica kod pumpe<br></td>
<td></td>
<td>Prikaz</td>
</tr>
<tr>
<tr>
<td>Osumnjicen tranzit</td>
<td>NS182TP</td>
<td>23-03-2014 20:48:08</td>
<td>11.3</td>
<td>Raskrsnica kod pumpe<br></td>
<td></td>
<td>Prikaz</td>
</tr>
<tr>
<tr>
<td>Osumnjicen tranzit</td>
<td>NS182TP</td>
<td>23-03-2014 20:48:08</td>
<td>11.3</td>
<td>Raskrsnica kod pumpe<br></td>
<td></td>
<td>Prikaz</td>
</tr>
</tbody>
</table>
Style (CSS 3):
caption {
display: block;
line-height: 3em;
width: 100%;
-webkit-align-items: stretch;
border: 1px solid #eee;
}
.flexy {
display: block;
width: 90%;
border: 1px solid #eee;
max-height: 320px;
overflow: auto;
}
.flexy thead {
display: -webkit-flex;
-webkit-flex-flow: row;
}
.flexy thead tr {
padding-right: 15px;
display: -webkit-flex;
width: 100%;
-webkit-align-items: stretch;
}
.flexy tbody {
display: -webkit-flex;
height: 100px;
overflow: auto;
-webkit-flex-flow: row wrap;
}
.flexy tbody tr{
display: -webkit-flex;
width: 100%;
}
.flexy tr td {
width: 15%;
}
You can bypass https using below commands:
npm config set strict-ssl false
or set the registry URL from https or http like below:
npm config set registry="http://registry.npmjs.org/"
However, Personally I believe bypassing https is not the real solution, but we can use it as a workaround.
u can also try from yours design
<div <%=If(True = True, "style='display: none;'", "")%> >True</div>
<div <%=If(True = False, "style='display: none;'", "")%> >False</div>
<div <%=If(Session.Item("NameExist") IsNot Nothing, "style='display: none;'", "")%> >NameExist</div>
<div <%=If(Session.Item("NameNotExist") IsNot Nothing, "style='display: none;'", "")%> >NameNotExist</div>
Output html
<div style='display: none;' > True</div>
<div >False</div>
<div style='display: none;' >NameExist</div>
<div >NameNotExist</div>
json-schema-generator is a neat Ruby based JSON schema generator. It supports both draft 3 and 4 of the JSON schema. It can be run as a standalone executable, or it can be embedded inside of a Ruby script.
Then you can use json-schema to validate JSON samples against your newly generated schema if you want.
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:
using System;
using System.Linq;
namespace CheckStringContent
{
class Program
{
static void Main(string[] args)
{
//Get a password to check
Console.WriteLine("Please input a Password: ");
string userPassword = Console.ReadLine();
//Check the string
bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));
//Write results to console
Console.WriteLine($"Symbols are present: {symbolCheck}");
}
}
}
This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.
When an asynchronous task is executed, the task goes through four steps:
Below is a demo example:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled())
break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
And once you created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);
$(document).ready(function() {
var referrer = document.referrer;
if(referrer.equals("Setting.jsp")){
function goBack() {
window.history.go();
}
}
if(referrer.equals("http://localhost:8080/Ads/Terms.jsp")){
window.history.forward();
function noBack() {
window.history.forward();
}
}
});
using this you can avoid load previous page load
If you want to reset every RowId via content provider try this
rowCounter=1;
do {
rowId = cursor.getInt(0);
ContentValues values;
values = new ContentValues();
values.put(Table_Health.COLUMN_ID,
rowCounter);
updateData2DB(context, values, rowId);
rowCounter++;
while (cursor.moveToNext());
public static void updateData2DB(Context context, ContentValues values, int rowId) {
Uri uri;
uri = Uri.parseContentProvider.CONTENT_URI_HEALTH + "/" + rowId);
context.getContentResolver().update(uri, values, null, null);
}
Basically, if you're on a 64-bit machine, IIS 7 is not (by default) serving 32-bit apps, which the database engine operates on. So here is exactly what you do:
1) ensure that the 2007 database engine is installed, this can be downloaded at: http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
2) open IIS7 manager, and open the Application Pools area. On the right sidebar, you will see an option that says "Set application pool defaults". Click it, and a window will pop up with the options.
3) the second field down, which says 'Enable 32-bit applications' is probably set to FALSE by default. Simply click where it says 'false' to change it to 'true'.
4) Restart your app pool (you can do this by hitting RECYCLE instead of STOP then START, which will also work).
5) done, and your error message will go away.
On the client side you can add and remove websites to be displayed in Compatibility View from Compatibility View Settings window of IE:
Tools-> Compatibility View Settings
It is possible to do with CSS only by selecting active and focus pseudo element of the button.
button:active{
background:olive;
}
button:focus{
background:olive;
}
See codepen: http://codepen.io/fennefoss/pen/Bpqdqx
You could also write a simple jQuery click function which changes the background color.
HTML:
<button class="js-click">Click me!</button>
CSS:
button {
background: none;
}
JavaScript:
$( ".js-click" ).click(function() {
$( ".js-click" ).css('background', 'green');
});
Check out this codepen: http://codepen.io/fennefoss/pen/pRxrVG
As Andrew Brower says, but adding a trim
ALTER PROCEDURE <Name>
(
@PartialName VARCHAR(50) = NULL
)
SELECT Name
FROM <table>
WHERE Name LIKE '%' + LTRIM(RTRIM(@PartialName)) + '%'
Also, make sure you dont have a space after \ in previous line Else this is the error
Note: Use CSS counters
to create nested numbering in a modern browser. See the accepted answer. The following is for historical interest only.
If the browser supports content
and counter
,
.foo {_x000D_
counter-reset: foo;_x000D_
}_x000D_
.foo li {_x000D_
list-style-type: none;_x000D_
}_x000D_
.foo li::before {_x000D_
counter-increment: foo;_x000D_
content: "1." counter(foo) " ";_x000D_
}
_x000D_
<ol class="foo">_x000D_
<li>uno</li>_x000D_
<li>dos</li>_x000D_
<li>tres</li>_x000D_
<li>cuatro</li>_x000D_
</ol>
_x000D_
Both methods have their problems.
If the subclass changes the identity, then you need to compare their actual classes. Otherwise, you violate the symmetric property. For instance, different types of Person
s should not be considered equivalent, even if they have the same name.
However, some subclasses don't change identity and these need to use instanceof
. For instance, if we have a bunch of immutable Shape
objects, then a Rectangle
with length and width of 1 should be equal to the unit Square
.
In practice, I think the former case is more likely to be true. Usually, subclassing is a fundamental part of your identity and being exactly like your parent except you can do one little thing does not make you equal.
Machine learning packages like tensorflow 2.x are designed to work only on 64 bit Python as they are memory intensive.
Using the Interop you get a range of cells and call the .Merge()
method on that range.
eWSheet.Range[eWSheet.Cells[1, 1], eWSheet.Cells[4, 1]].Merge();
The move_uploaded_file
will return false if the file was not successfully moved you can put something into your code to alert you in a log if that happens, that should help you figure out why your having trouble renaming the file
In general, this depends what your map contains. If it has null values, things can get tricky and containsKey(key)
or get(key, default)
should be used to detect of the element really exists. In many cases the code can become simpler you can define a default value:
def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x1 = mymap.get('likes', '[nothing specified]')
println "x value: ${x}" }
Note also that containsKey()
or get()
are much faster than setting up a closure to check the element mymap.find{ it.key == "likes" }
. Using closure only makes sense if you really do something more complex in there. You could e.g. do this:
mymap.find{ // "it" is the default parameter
if (it.key != "likes") return false
println "x value: ${it.value}"
return true // stop searching
}
Or with explicit parameters:
mymap.find{ key,value ->
(key != "likes") return false
println "x value: ${value}"
return true // stop searching
}
I imagine this forum posting, which I quote fully below, should answer the question.
Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):
BEGIN ATOMIC
DECLARE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
END
or (in any environment):
WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM tablename, t
WHERE column1 = example
or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):
CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
another way to single instance an application is to check their hash sums. after messing around with mutex (didn't work as i want) i got it working this way:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
public Main()
{
InitializeComponent();
Process current = Process.GetCurrentProcess();
string currentmd5 = md5hash(current.MainModule.FileName);
Process[] processlist = Process.GetProcesses();
foreach (Process process in processlist)
{
if (process.Id != current.Id)
{
try
{
if (currentmd5 == md5hash(process.MainModule.FileName))
{
SetForegroundWindow(process.MainWindowHandle);
Environment.Exit(0);
}
}
catch (/* your exception */) { /* your exception goes here */ }
}
}
}
private string md5hash(string file)
{
string check;
using (FileStream FileCheck = File.OpenRead(file))
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] md5Hash = md5.ComputeHash(FileCheck);
check = BitConverter.ToString(md5Hash).Replace("-", "").ToLower();
}
return check;
}
it checks only md5 sums by process id.
if an instance of this application was found, it focuses the running application and exit itself.
you can rename it or do what you want with your file. it wont open twice if the md5 hash is the same.
may someone has suggestions to it? i know it is answered, but maybe someone is looking for a mutex alternative.
While several answers are similar, I still had an issue - the user would click the button several times, playing the audio over itself (either it was clicked by accident or they were just 'playing'....)
An easy fix:
var music = new Audio();
function playMusic(file) {
music.pause();
music = new Audio(file);
music.play();
}
Setting up the audio on load allowed 'music' to be paused every time the function is called - effectively stopping the 'noise' even if they user clicks the button several times (and there is also no need to turn off the button, though for user experience it may be something you want to do).
I just wrote array intersection that correctly handles also duplicates
https://gist.github.com/gkucmierz/8ee04544fa842411f7553ef66ac2fcf0
// array intersection that correctly handles also duplicates_x000D_
_x000D_
const intersection = (a1, a2) => {_x000D_
const cnt = new Map();_x000D_
a2.map(el => cnt[el] = el in cnt ? cnt[el] + 1 : 1);_x000D_
return a1.filter(el => el in cnt && 0 < cnt[el]--);_x000D_
};_x000D_
_x000D_
const l = console.log;_x000D_
l(intersection('1234'.split``, '3456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('12344'.split``, '3456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('1234'.split``, '33456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('12334'.split``, '33456'.split``)); // [ '3', '3', '4' ]
_x000D_
Here is my workaround,
In your example you can add a third element
with "same styles" of .one & .two elements, but without the absolute position and with hidden visibility:
HTML
<article>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</article>
CSS
.three{
height: 30px;
z-index: -1;
visibility: hidden;
}
Maybe something like this ?
Create a batch to connect to telnet and run a script to issue commands ? source
:: Open a Telnet window
start telnet.exe 192.168.1.1
:: Run the script
cscript SendKeys.vbs
set OBJECT=WScript.CreateObject("WScript.Shell")
WScript.sleep 50
OBJECT.SendKeys "mylogin{ENTER}"
WScript.sleep 50
OBJECT.SendKeys "mypassword{ENTER}"
WScript.sleep 50
OBJECT.SendKeys " cd /var/tmp{ENTER}"
WScript.sleep 50
OBJECT.SendKeys " rm log_web_activity{ENTER}"
WScript.sleep 50
OBJECT.SendKeys " ln -s /dev/null log_web_activity{ENTER}"
WScript.sleep 50
OBJECT.SendKeys "exit{ENTER}"
WScript.sleep 50
OBJECT.SendKeys " "
The quick answer is no, then you are probably asking why can't I do that with php. OK here is a longer answer. PHP is a serverside scripting language and therefor has nothing to do with the type of a specific client. Then you might ask "why can I then get the browser agent from php?", thats because that information is sent with the initial HTTP headers upon request to the server. So if you want client information that's not sent with the HTTP header you must you a client scripting language like javascript.
"N/A" is not a string it is an error, try this:
=if(ISNA(A1),C1)
you have to place this fomula in cell B1 so it will get the value of your formula