To avoid some of the problems mentioned above (not robust for nulls etc etc), to get first and last element in a list an approach could be
import java.util.List;
public static final <A> A getLastElement(List<A> list) {
return list != null ? getElement(list, list.size() - 1) : null;
}
public static final <A> A getFirstElement(List<A> list) {
return list != null ? getElement(list, 0) : null;
}
private static final <A> A getElement(List<A> list, int pointer) {
A res = null;
if (list.size() > 0) {
res = list.get(pointer);
}
return res;
}
The convention adopted is that the first/last element of an empty list is null...
With Eclipse Collections you can use detectIndex
along with remove(int)
on any java.util.List.
List<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int index = Iterate.detectIndex(integers, i -> i > 2);
if (index > -1) {
integers.remove(index);
}
Assert.assertEquals(Lists.mutable.with(1, 2, 4, 5), integers);
If you use the MutableList
type from Eclipse Collections, you can call the detectIndex
method directly on the list.
MutableList<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int index = integers.detectIndex(i -> i > 2);
if (index > -1) {
integers.remove(index);
}
Assert.assertEquals(Lists.mutable.with(1, 2, 4, 5), integers);
Note: I am a committer for Eclipse Collections
Yeah, eclipse sees the top directory as the working/root directory, for the purposes of paths.
...just thought I'd add some extra info. I'm new here! I'd like to help.
It's a harder problem if you need to use SSH at build time. For example if you're using git clone
, or in my case pip
and npm
to download from a private repository.
The solution I found is to add your keys using the --build-arg
flag. Then you can use the new experimental --squash
command (added 1.13) to merge the layers so that the keys are no longer available after removal. Here's my solution:
Build command
$ docker build -t example --build-arg ssh_prv_key="$(cat ~/.ssh/id_rsa)" --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)" --squash .
Dockerfile
FROM python:3.6-slim
ARG ssh_prv_key
ARG ssh_pub_key
RUN apt-get update && \
apt-get install -y \
git \
openssh-server \
libmysqlclient-dev
# Authorize SSH Host
RUN mkdir -p /root/.ssh && \
chmod 0700 /root/.ssh && \
ssh-keyscan github.com > /root/.ssh/known_hosts
# Add the keys and set permissions
RUN echo "$ssh_prv_key" > /root/.ssh/id_rsa && \
echo "$ssh_pub_key" > /root/.ssh/id_rsa.pub && \
chmod 600 /root/.ssh/id_rsa && \
chmod 600 /root/.ssh/id_rsa.pub
# Avoid cache purge by adding requirements first
ADD ./requirements.txt /app/requirements.txt
WORKDIR /app/
RUN pip install -r requirements.txt
# Remove SSH keys
RUN rm -rf /root/.ssh/
# Add the rest of the files
ADD . .
CMD python manage.py runserver
Update: If you're using Docker 1.13 and have experimental features on you can append --squash
to the build command which will merge the layers, removing the SSH keys and hiding them from docker history
.
Good post, the line
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
is mandatory if the SMTP server uses SSL Authentication, like the GMail SMTP server does. However if the server uses Plaintext Authentication over TLS, it should not be present, because Java Mail will complain about the initial connection being plaintext.
Also make sure you are using the latest version of Java Mail. Recently I used some old Java Mail jars from a previous project and could not make the code work, because the login process was failing. After I have upgraded to the latest version of Java Mail, the reason of the error became clear: it was a javax.net.ssl.SSLHandshakeException, which was not thrown up in the old version of the lib.
If you add a certain value (say, "1") to Anthony Forloney's example, everything would be clear:
function fact(1) {
if (1 === 0) { // our base case
return 1;
}
else {
return 1 * fact(1-1); // <--calling itself.
}
}
original:
function fact($n) {
if ($n === 0) { // our base case
return 1;
}
else {
return $n * fact($n-1); // <--calling itself.
}
}
Yes, it is the right way.
You could use the image in the resource file just using the path:
<Image Source="..\Media\Image.png" />
You must set the build action of the image file to "Resource".
I created a project like you did. The structure looks like this
The Classes are just copy pasted from yours.
I changed the application.properties to this:
spring.datasource.url=jdbc:mysql://localhost/testproject
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
But I think your problem is in your pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<artifactId>spring-boot-sample-jpa</artifactId>
<name>Spring Boot JPA Sample</name>
<description>Spring Boot JPA Sample</description>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Check these files for differences. Hope this helps
Update 1: I changed my username. The link to the example is now https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL
$(".first").addClass("second");
If you'd like to add it on an event, you can do so easily as well. An example with the click event:
$(".first").click(function() {
$(this).addClass("second");
});
To refresh page you don't need react-router, simple js:
window.location.reload();
To re-render view in React component, you can just fire update with props/state.
I came up with what I feel is a much better solution allowing:
no need for 'this._', that/self, weakmaps, symbols etc. Clear and straightforward 'class' code
private variables and methods are really private and have the correct 'this' binding
No use of 'this' at all which means clear code that is much less error prone
public interface is clear and separated from the implementation as a proxy to private methods
allows easy composition
with this you can do:
function Counter() {_x000D_
// public interface_x000D_
const proxy = {_x000D_
advance, // advance counter and get new value_x000D_
reset, // reset value_x000D_
value // get value_x000D_
}_x000D_
_x000D_
// private variables and methods_x000D_
let count=0;_x000D_
_x000D_
function advance() {_x000D_
return ++count;_x000D_
}_x000D_
_x000D_
function reset(newCount) {_x000D_
count=(newCount || 0);_x000D_
}_x000D_
_x000D_
function value() {_x000D_
return count;_x000D_
}_x000D_
_x000D_
return proxy;_x000D_
}_x000D_
_x000D_
let counter=Counter.New();_x000D_
console.log(counter instanceof Counter); // true_x000D_
counter.reset(100);_x000D_
console.log('Counter next = '+counter.advance()); // 101_x000D_
console.log(Object.getOwnPropertyNames(counter)); // ["advance", "reset", "value"]
_x000D_
<script src="https://cdn.rawgit.com/kofifus/New/7987670c/new.js"></script>
_x000D_
see New for the code and more elaborate examples including constructor and composition
Using
calls Dispose()
after the using
-block is left, even if the code throws an exception.
So you usually use using
for classes that require cleaning up after them, like IO.
So, this using block:
using (MyClass mine = new MyClass())
{
mine.Action();
}
would do the same as:
MyClass mine = new MyClass();
try
{
mine.Action();
}
finally
{
if (mine != null)
mine.Dispose();
}
Using using
is way shorter and easier to read.
There is a UDF that will do that described here:
User Defined Function to Strip HTML
CREATE FUNCTION [dbo].[udf_StripHTML] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE @Start INT
DECLARE @End INT
DECLARE @Length INT
SET @Start = CHARINDEX('<',@HTMLText)
SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
SET @Length = (@End - @Start) + 1
WHILE @Start > 0 AND @End > 0 AND @Length > 0
BEGIN
SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')
SET @Start = CHARINDEX('<',@HTMLText)
SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
SET @Length = (@End - @Start) + 1
END
RETURN LTRIM(RTRIM(@HTMLText))
END
GO
Edit: note this is for SQL Server 2005, but if you change the keyword MAX to something like 4000, it will work in SQL Server 2000 as well.
dataframe['column'].squeeze()
should solve this. It basically changes the dataframe column to a list.
Solution:
where some_column NOT LIKE '%[^0-9]%'
Is correct.
Just one important note: Add validation for when the string column = ''
(empty string). This scenario will return that ''
is a valid number as well.
You can use hexdump binary file
sudo apt-get install hexdump
hexdump -C yourfile.bin
There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
//define something for Windows (32-bit and 64-bit, this part is common)
#ifdef _WIN64
//define something for Windows (64-bit only)
#else
//define something for Windows (32-bit only)
#endif
#elif __APPLE__
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR
// iOS Simulator
#elif TARGET_OS_IPHONE
// iOS device
#elif TARGET_OS_MAC
// Other kinds of Mac OS
#else
# error "Unknown Apple platform"
#endif
#elif __linux__
// linux
#elif __unix__ // all unices not caught above
// Unix
#elif defined(_POSIX_VERSION)
// POSIX
#else
# error "Unknown compiler"
#endif
The defined macros depend on the compiler that you are going to use.
The _WIN64
#ifdef
can be nested into the _WIN32
#ifdef
because _WIN32
is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both
(also WIN32
without underscore allows IDE to highlight the right partition of code).
It turns out that lstlisting
is able to format code nicely, but requires a lot of tweaking.
Wikibooks has a good example for the parameters you can tweak.
This is an addition to the answer by Abdull somewhere in this thread:
I had to modify instead of adding a port
semanage port -m -t http_port_t -p tcp 5000
because I get this error on adding the port
ValueError: Port tcp/5000 already defined
Using jQuery the easiest will be:
var text = '<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>';
var output = $("<div />").html(text).text();
console.log(output);
As far as I can see, most of the solutions here count the number of non empty cells, and not the number of rows with non empty cell inside.
One possible solution for the range B3:E29
is for example
=SUM(ArrayFormula(IF(B3:B29&C3:C29&D3:D29&E3:E29="";0;1)))
Here ArrayFormula(IF(B3:B29&C3:C29&D3:D29&E3:E29="";0;1))
returns a column of 0
(if the row is empty) and 1
(else).
Another one is given in consideRatio's answer.
Per the Bloom Filter mentions, Deletable Bloom Filters (DlBF) are in some ways better than basic counting variants. See http://arxiv.org/abs/1005.0352
None of this will work as expected.. The correct way is to change position: fixed to position: absolute for .modal class
You can define a a click function and then set the onclick
attribute for the element.
function imageClick(url) {
window.location = url;
}
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" onclick="imageClick('../images/bottle.html')" />
This approach lets you get rid of the surrounding <a>
element. If you want to keep it, then define the onclick
attribute on <a>
instead of on <img>
.
It's a so-called auto property, and is essentially a shorthand for the following (similar code will be generated by the compiler):
private string name;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
Unsigned int can be converted to signed (or vice-versa) by simple expression as shown below :
unsigned int z;
int y=5;
z= (unsigned int)y;
Though not targeted to the question, you would like to read following links :
In the IFRAME, make your function public to the window object:
window.myFunction = function(args) {
doStuff();
}
For access from the parent page, use this:
var iframe = document.getElementById("iframeId");
iframe.contentWindow.myFunction(args);
I don't recommend encoding binary data in base64 and wrapping it in JSON. It will just needlessly increase the size of the response and slow things down.
Simply serve your file data using GET and application/octect-stream
using one of the factory methods of javax.ws.rs.core.Response
(part of the JAX-RS API, so you're not locked into Jersey):
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() {
File file = ... // Initialize this to the File path you want to serve.
return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) //optional
.build();
}
If you don't have an actual File
object, but an InputStream
, Response.ok(entity, mediaType)
should be able to handle that as well.
If the image is smaller than parent...
.img_100 {
width: 100%;
}
First way is
function function1()
{
var variable1=12;
function2(variable1);
}
function function2(val)
{
var variableOfFunction1 = val;
// Then you will have to use this function for the variable1 so it doesn't really help much unless that's what you want to do. }
Second way is
var globalVariable;
function function1()
{
globalVariable=12;
function2();
}
function function2()
{
var local = globalVariable;
}
Yes, each package must be defined in its own directory.
The source structure is defined in How to Write Go Code.
A package is a component that you can use in more than one program, that you can publish, import, get from an URL, etc. So it makes sense for it to have its own directory as much as a program can have a directory.
First in your ios simulator, if you press [command + D] key then you can see this screen.
Then click Debug JS remotely button.
After you might see React Native Debugger page like this.
And then open your inspector[f12], and go to console tab debug it! :)
<input type= "image" id=" " onclick=" " src=" " />
it works.
Percent encoding. Replace the hash with %23
.
If you need to popback from the fourth fragment in the backstack history to the first, use tags!!!
When you add the first fragment you should use something like this:
getFragmentManager.beginTransaction.addToBackStack("A").add(R.id.container, FragmentA).commit()
or
getFragmentManager.beginTransaction.addToBackStack("A").replace(R.id.container, FragmentA).commit()
And when you want to show Fragments B,C and D you use this:
getFragmentManager.beginTransaction.addToBackStack("B").replace(R.id.container, FragmentB, "B").commit()
and other letters....
To return to Fragment
A, just call popBackStack(0, "A")
, yes, use the flag that you specified when you add it, and note that it must be the same flag in the command addToBackStack()
, not the one used in command replace or add.
You're welcome ;)
The target attribute of a link forces the browser to open the destination page in a new browser window. Using _blank
as a target value will spawn a new window every time while using _new
will only spawn one new window and every link clicked with a target value of _new
will replace the page loaded in the previously spawned window
head or tail can do it as well:
head -c X
Prints the first X bytes (not necessarily characters if it's a UTF-16 file) of the file. tail will do the same, except for the last X bytes.
This (and cut) are portable.
From a Collection
, another way you could do it would be:
$collection->pluck('id')->toArray()
This will return an indexed array, perfectly usable by laravel in a whereIn()
query, for instance.
You should use toString() Method of java script for the convert into string before because replace method is a string function.
The git diffs have an extra path segment prepended to the file paths. You can strip the this entry in the path by specifying -p1 with patch, like so:
patch -p1 < save.patch
../images/logo.png
will move you back one folder.
../../images/logo.png
will move you back two folders.
/images/logo.png
will take you back to the root folder no matter where you are/.
To summarize, this points to current object and the method invocation in java is polymorphic by nature. So, method selection for execution, totally depends upon object pointed by this. Therefore, invoking method method2() from parent class invokes method2() of child class, as the this points to object of child class. The definition of this doesn't changes, irrespective of whichever class it's used.
PS. unlike methods, member variables of class are not polymorphic.
The Css vertical-align property should help you out here:
vertical-align: bottom;
is what you need for your smaller header :)
Short answer: use an unassigned user port
Over achiever's answer - Select and deploy a resource discovery solution. Have the server select a private port dynamically. Have the clients use resource discovery.
The risk that that a server will fail because the port it wants to listen on is not available is real; at least it's happened to me. Another service or a client might get there first.
You can almost totally reduce the risk from a client by avoiding the private ports, which are dynamically handed out to clients.
The risk that from another service is minimal if you use a user port. An unassigned port's risk is only that another service happens to be configured (or dyamically) uses that port. But at least that's probably under your control.
The huge doc with all the port assignments, including User Ports, is here: http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt look for the token Unassigned.
Copied from the formal specification: ECMAScript 5.1 section 11.9.5
11.9.4 The Strict Equals Operator ( === )
The production EqualityExpression : EqualityExpression === RelationalExpression is evaluated as follows:
- Let lref be the result of evaluating EqualityExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating RelationalExpression.
- Let rval be GetValue(rref).
- Return the result of performing the strict equality comparison rval === lval. (See 11.9.6)
11.9.5 The Strict Does-not-equal Operator ( !== )
The production EqualityExpression : EqualityExpression !== RelationalExpression is evaluated as follows:
- Let lref be the result of evaluating EqualityExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating RelationalExpression.
- Let rval be GetValue(rref). Let r be the result of performing strict equality comparison rval === lval. (See 11.9.6)
- If r is true, return false. Otherwise, return true.
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is different from Type(y), return false.
- Type(x) is Undefined, return true.
- Type(x) is Null, return true.
- Type(x) is Number, then
- If x is NaN, return false.
- If y is NaN, return false.
- If x is the same Number value as y, return true.
- If x is +0 and y is -0, return true.
- If x is -0 and y is +0, return true.
- Return false.
- If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
- If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
- Return true if x and y refer to the same object. Otherwise, return false.
As pointed Jeff the tool NDepend can help to find unused methods, fields and types.
To elaborate a bit, NDepend proposes to write Code Rule over LINQ Query (CQLinq). Around 200 default code rules are proposed, 3 of them being dedicated to unused/dead code detection
Basically such a rule to detect unused method for example looks like:
// <Name>Dead Methods</Name>
warnif count > 0
from m in Application.Methods where !m.MethodsCallingMe.Any()
select m
But this rule is naive and will return trivial false positives. There are many situations where a method is never called yet it is not unused (entry point, class constructor, finaliser...) this is why the 3 default rules are more elaborated:
NDepend integrates in Visual Studio 2017,2015, 2013, 2012, 2010, thus these rules can be checked/browsed/edited right inside the IDE. The tool can also be integrated into your CI process and it can build reports that will show rules violated and culprit code elements. NDepend has also a VS Team Services extension.
If you click these 3 links above toward the source code of these rules, you'll see that the ones concerning types and methods are a bit complex. This is because they detect not only unused types and methods, but also types and methods used only by unused dead types and methods (recursive).
This is static analysis, hence the prefix Potentially in the rule names. If a code element is used only through reflection, these rules might consider it as unused which is not the case.
In addition to using these 3 rules, I'd advise measuring code coverage by tests and striving for having full coverage. Often, you'll see that code that cannot be covered by tests, is actually unused/dead code that can be safely discarded. This is especially useful in complex algorithms where it is not clear if a branch of code is reachable or not.
Disclaimer: I work for NDepend.
Use std::printf and c_str() example:
std::printf("Follow this command: %s", myString.c_str());
Just use the length filter on the whole array. It works on more than just strings:
{{ notcount|length }}
When I'm not worried about performance, I'll often use this:
if my_string.to_s == ''
# It's nil or empty
end
There are various variations, of course...
if my_string.to_s.strip.length == 0
# It's nil, empty, or just whitespace
end
To get all of the file system drives, you can use the following command:
gdr -PSProvider 'FileSystem'
gdr
is an alias for Get-PSDrive
, which includes all of the "virtual drives" for the registry, etc.
For multiple headers do as follow:
import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('param1', '212212')
req.add_header('param2', '12345678')
req.add_header('other_param1', 'sample')
req.add_header('other_param2', 'sample1111')
req.add_header('and_any_other_parame', 'testttt')
resp = urllib2.urlopen(req)
content = resp.read()
In your app.js you need add something like this
global.myvar = 100;
Now, in all your files you want use this variable, you can just access it as myvar
public function getSalary()
{
$this->db->select('tbl_salary.*,tbl_employee.empFirstName');
$this->db->from('tbl_salary');
$this->db->join('tbl_employee','tbl_employee.empID = strong texttbl_salary.salEmpID');
$this->db->where('tbl_salary.status',0);
$query = $this->db->get();
return $query->result();
}
Try
echo -en "`date` User `whoami` started the script.\n" >> output.log
Try issuing this multiple times. I hope you are looking for the same output.
There are several sources online that have geojson data for timezones (here's one, here's another)
Use a geometry library to create polygon objects from the geojson coordinates (shapely [python], GEOS [c++], JTS [java], NTS [.net]).
Convert your lat/lng to a point object (however your library represents that) and check if it intersects the timezone polygon.
from shapely.geometry import Polygon, Point
def get_tz_from_lat_lng(lat, lng):
for tz, geojson in timezones.iteritems():
coordinates = geojson['features'][0]['geometry']['coordinates']
polygon = Polygon(coordinates)
point = Point(lng, lat)
if polygon.contains(point):
return tz
You could use Thread.Sleep()
function, e.g.
int milliseconds = 2000;
Thread.Sleep(milliseconds);
that completely stops the execution of the current thread for 2 seconds.
Probably the most appropriate scenario for Thread.Sleep
is when you want to delay the operations in another thread, different from the main e.g. :
MAIN THREAD --------------------------------------------------------->
(UI, CONSOLE ETC.) | |
| |
OTHER THREAD ----- ADD A DELAY (Thread.Sleep) ------>
For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.
I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.
Another cause of this could be if you don't use the default variable name for the "id" which is actually: id.
NOTE: This one is just an alternative for the previous provided .NET framework 3.5 and above
You can send it as raw xml
<test>or like this</test>
If you declare the paramater2 as XElement data type
While this may be an old question, the problem is still occurring these days, and the exact question is still not answered properly.
It is important to note that some projects have multiple classes with a main method.
In my case, I could run the project via the main class, but I could not run a particular other class that had a main method. The only thing that helped me was refactoring the class and renaming it. I've tried:
The only thing that let me run this class is renaming it permanently. I think this must be some kind of a NetBeans bug.
Edit: Another thing that did help was completely uninstall Netbeans, wipe cache and any configuration files. It so happened that a newer Netbeans version was available so I installed it. But the old one would have probably worked too.
Here's the most easy and reliable way I found if you're okay depending on Pandas. However I don't think this is officially part of the Pandas API so it may break with future updates. It works as of 0.25.3
from pandas.io import clipboard
clipboard.copy("test")
Steps to upload project to git:-
step1-open cmd and change current working directory to your project location.
step2-Initialize your project directory as a Git repository.
$ git init
step3-Add files in your local repository.
$ add .
step4-Commit the files that you've staged in your local repository.
$ git commit -m "First commit"
step5-Copy the remote repository url.
step6-add the remote repository url as origin in your local location.
$ git add origin copied_remote_repository_url
step7-confirm your origin is updated ot not.
$ git remote show origin
step8-push the changed to your github repository
$ git push origin master.
What about using mysql -v
to put mysql client in verbose mode ?
Angular 1.1.5 added support for ternary operators:
{{myVar === "two" ? "it's true" : "it's false"}}
Running JMeter in command line mode:
1.Navigate to JMeter’s bin directory
Now enter following command,
jmeter -n –t test.jmx
-n: specifies JMeter is to run in non-gui mode
-t: specifies name of JMX file that contains the Test Plan
Multi-programming :-
More than one task(job) process can reside into main memory at a time. It is basically design to reduce CPU wastage during I/O operation , example : if a job is executing currently and need I/O operation . I/O operation is done using DMA and processor assign to some Other job from the job queue till I/O operation of job1 completed . then job1 continue again . In this way it reduce CPU wastage .
As it solved the problem, I put it as an answer.
Don't use single and double quotes, especially when you define a raw string with r
in front of it.
The correct call is then
path = r"C:\Apps\CorVu\DATA\Reports\AlliD\Monthly Commission Reports\Output\pdcom1"
or
path = r'C:\Apps\CorVu\DATA\Reports\AlliD\Monthly Commission Reports\Output\pdcom1'
Ok for all of you out there that arrived here in desperation searching for the same problem. I hope you will find this quicker then I did ;O.
This is how it is solved. JoostK told me at github that "the first argument to join is the table (or data) you're joining.". And he was right.
Here is the code. Different table and names but you will get the idea right? It t
DB::table('users')
->select('first_name', 'TotalCatches.*')
->join(DB::raw('(SELECT user_id, COUNT(user_id) TotalCatch,
DATEDIFF(NOW(), MIN(created_at)) Days,
COUNT(user_id)/DATEDIFF(NOW(), MIN(created_at))
CatchesPerDay FROM `catch-text` GROUP BY user_id)
TotalCatches'),
function($join)
{
$join->on('users.id', '=', 'TotalCatches.user_id');
})
->orderBy('TotalCatches.CatchesPerDay', 'DESC')
->get();
We can use this. Please change the src location of ur img from git folder and add alternate text if img is not loaded
<p align="center">
<img src="ur img url here" alt="alternate text">
</p>
Use root tag
as shape
instead of selector
in your shape.xml
file, and it will resolve your problem!
I realize that this is a bit late, but I did not notice any of the other answers mentioning indexing into the empty array:
big_array = numpy.empty(10, 4)
for i in range(5):
array_i = numpy.random.random(2, 4)
big_array[2 * i:2 * (i + 1), :] = array_i
This way, you preallocate the entire result array with numpy.empty
and fill in the rows as you go using indexed assignment.
It is perfectly safe to preallocate with empty
instead of zeros
in the example you gave since you are guaranteeing that the entire array will be filled with the chunks you generate.
In JavaScript it has no special significance (no more than a
or Q
anyway). It is just an uninformative variable name.
In jQuery the variable is assigned a copy of the jQuery
function. This function is heavily overloaded and means half a dozen different things depending on what arguments it is passed. In this particular example you are passing it a string that contains a selector, so the function means "Create a jQuery object containing the element with the id Text".
The simplest is to convert to a set then back to a list:
my_list = list(set(my_list))
One disadvantage with this is that it won't preserve the order. You may also want to consider if a set would be a better data structure to use in the first place, instead of a list.
The problem with other answers here is that they use position: absolute;
This makes it difficult to layout the element itself in relation to the ::before
pseudo-element. For example, if you wish to show an image before a link like this:
Here's how I was able to achieve the layout in the picture:
a::before {_x000D_
content: "";_x000D_
float: left;_x000D_
width: 16px;_x000D_
height: 16px;_x000D_
margin-right: 5px;_x000D_
background: url(../../lhsMenu/images/internal_link.png) no-repeat 0 0;_x000D_
background-size: 80%;_x000D_
}
_x000D_
Note that this method allows you to scale the background image, as well as keep the ability to use margins and padding for layout.
I know this is an old question but I came across it while trying to solve this same issue. I thought it'd be worth sharing this solution I hadn't found anywhere else.
Basically the solution is to use CSS to hide the <input>
element and style a <label>
around it to look like a button. Click the 'Run code snippet' button to see the results.
I had used a JavaScript solution before that worked fine too but it is nice to solve a 'presentation' issue with just CSS.
label.cameraButton {_x000D_
display: inline-block;_x000D_
margin: 1em 0;_x000D_
_x000D_
/* Styles to make it look like a button */_x000D_
padding: 0.5em;_x000D_
border: 2px solid #666;_x000D_
border-color: #EEE #CCC #CCC #EEE;_x000D_
background-color: #DDD;_x000D_
}_x000D_
_x000D_
/* Look like a clicked/depressed button */_x000D_
label.cameraButton:active {_x000D_
border-color: #CCC #EEE #EEE #CCC;_x000D_
}_x000D_
_x000D_
/* This is the part that actually hides the 'Choose file' text box for camera inputs */_x000D_
label.cameraButton input[accept*="camera"] {_x000D_
display: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>Nice image capture button</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<label class="cameraButton">Take a picture_x000D_
<input type="file" accept="image/*;capture=camera">_x000D_
</label>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I approached the same problem yesterday and found a module called [natsort][1], which solves your problem. Use:
from natsort import natsorted # pip install natsort
# Example list of strings
a = ['1', '10', '2', '3', '11']
[In] sorted(a)
[Out] ['1', '10', '11', '2', '3']
[In] natsorted(a)
[Out] ['1', '2', '3', '10', '11']
# Your array may contain strings
[In] natsorted(['string11', 'string3', 'string1', 'string10', 'string100'])
[Out] ['string1', 'string3', 'string10', 'string11', 'string100']
It also works for dictionaries as an equivalent of sorted
.
[1]: https://pypi.org/project/natsort/
My Solutions:
$("body").scrollspy({ target: ".target", offset: fix_header_height });
$(".target").click(function() {
$("body").animate(
{
scrollTop: $($(this).attr("href")).offset().top - fix_header_height
},
500
);
return;
});
probably you are not giving the same name as you mentioned in the
upload.single('file')
.
// For Image with parameter /// AFMultipartFormData
NSDictionary *dictParam =@{@"user_id":strGlobalUserId,@"name":[dictParameter objectForKey:@"Name"],@"contact":[dictParameter objectForKey:@"Contact Number"]};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:webServiceUrl]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:@"update_profile" parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
if (Imagedata.length>0) {
[formData appendPartWithFileData:Imagedata name:@"profile_pic" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
}
} progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSLog(@"update_profile %@", responseObject);
if ([[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
{
[self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
[self.navigationController popViewControllerAnimated:YES];
}] animated:YES completion:nil];
}
else
{
[self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
}] animated:YES completion:nil];
}
[SVProgressHUD dismiss];
} failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
{
[SVProgressHUD dismiss];
}];
I like Radar's answer best, so far, I think. I'd tweak a bit like this:
CHARS = ('a'..'z').to_a + ('A'..'Z').to_a
def rand_string(length=8)
s=''
length.times{ s << CHARS[rand(CHARS.length)] }
s
end
You shouldn't use both ngRoute
and UI-router
. Here's a sample code for UI-router:
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
_x000D_
$stateProvider_x000D_
.state('state1', {_x000D_
url: "/state1",_x000D_
templateUrl: "partials/state1.html",_x000D_
controller: 'YourCtrl'_x000D_
})_x000D_
_x000D_
.state('state2', {_x000D_
url: "/state2",_x000D_
templateUrl: "partials/state2.html",_x000D_
controller: 'YourOtherCtrl'_x000D_
});_x000D_
$urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?
You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router
If you declare a DateTime, then the default value is DateTime.MinValue, and hence you have to check it like this:
DateTime dat = new DateTime();
if (dat==DateTime.MinValue)
{
//unassigned
}
If the DateTime is nullable, well that's a different story:
DateTime? dat = null;
if (!dat.HasValue)
{
//unassigned
}
In the above example
int a = 5,i;
i=++a + ++a + a++; //Ans: i = 6 + 7 + 7 = 20 then a = 8
i=a++ + ++a + ++a; //Ans: i = 8 + 10 + 11 = 29 then a = 11
a=++a + ++a + a++; //Ans: a = 12 + 13 + 13 = 38
System.out.println(a); //Ans: a = 38
System.out.println(i); //Ans: i = 29
You can do something like this to read your nodes.
Also you can find some explanation in this page http://www.compoc.com/tuts/
<script type="text/javascript">
var markers = null;
$(document).ready(function () {
$.get("File.xml", {}, function (xml){
$('marker',xml).each(function(i){
markers = $(this);
});
});
});
</script>
This is how I solved this problem
$scope.downloadPDF = function () {
var link = document.createElement("a");
link.setAttribute("href", "path_to_pdf_file/pdf_filename.pdf");
link.setAttribute("download", "download_name.pdf");
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named "download_name.pdf"
}
This is similar to the top answer, but I like it better because it avoids explicit indexing. Assuming your list has the name lst
, you can generate
(item, next_item)
tuples from your list with zip
:
all(x <= y for x,y in zip(lst, lst[1:]))
In Python 3, zip
already returns a generator, in Python 2 you can use itertools.izip
for better memory efficiency.
Small demo:
>>> lst = [1, 2, 3, 4]
>>> zip(lst, lst[1:])
[(1, 2), (2, 3), (3, 4)]
>>> all(x <= y for x,y in zip(lst, lst[1:]))
True
>>>
>>> lst = [1, 2, 3, 2]
>>> zip(lst, lst[1:])
[(1, 2), (2, 3), (3, 2)]
>>> all(x <= y for x,y in zip(lst, lst[1:]))
False
The last one fails when the tuple (3, 2)
is evaluated.
Bonus: checking finite (!) generators which cannot be indexed:
>>> def gen1():
... yield 1
... yield 2
... yield 3
... yield 4
...
>>> def gen2():
... yield 1
... yield 2
... yield 4
... yield 3
...
>>> g1_1 = gen1()
>>> g1_2 = gen1()
>>> next(g1_2)
1
>>> all(x <= y for x,y in zip(g1_1, g1_2))
True
>>>
>>> g2_1 = gen2()
>>> g2_2 = gen2()
>>> next(g2_2)
1
>>> all(x <= y for x,y in zip(g2_1, g2_2))
False
Make sure to use itertools.izip
here if you are using Python 2, otherwise you would defeat the purpose of not having to create lists from the generators.
now featuring all the colors of the dos rainbow
@(IF not "%1" == "max" (start /MAX cmd /Q /C %0 max&X)
ELSE set C=1&set D=A&wmic process where name="cmd.exe" CALL setpriority "REALTIME">NUL)&CLS
:Y
set V=%D%
(IF %V% EQU 10 set V=A)
& (IF %V% EQU 11 set V=B)
& (IF %V% EQU 12 set V=C)
& (IF %V% EQU 13 set V=D)
& (IF %V% EQU 14 set V=E)
& (IF %V% EQU 15 set V=F)
title %random%6%random%%random%%random%%random%9%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%&color %V%&ECHO %random%%C%%random%%random%%random%%random%6%random%9%random%%random%%random%%random%%random%%random%%random%%random%%random%
&(IF %C% EQU 46 (TIMEOUT /T 1 /NOBREAK>nul&set C=1&CLS&IF %D% EQU 15 (set D=1)ELSE set /A D=%D%+1)
ELSE set /A C=%C%+1)&goto Y
those various ways of switch ...
# by index
switch(1, "one", "two")
## [1] "one"
# by index with complex expressions
switch(2, {"one"}, {"two"})
## [1] "two"
# by index with complex named expression
switch(1, foo={"one"}, bar={"two"})
## [1] "one"
# by name with complex named expression
switch("bar", foo={"one"}, bar={"two"})
## [1] "two"
this did it for me. you can vary the options for the output format to Base64.Default whatsoever.
// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);
For those who want to just copy and paste the fastest implementation of shift, there is a benchmark and conclusion(see the end). In addition, I introduce fill_value parameter and fix some bugs.
import numpy as np
import timeit
# enhanced from IronManMark20 version
def shift1(arr, num, fill_value=np.nan):
arr = np.roll(arr,num)
if num < 0:
arr[num:] = fill_value
elif num > 0:
arr[:num] = fill_value
return arr
# use np.roll and np.put by IronManMark20
def shift2(arr,num):
arr=np.roll(arr,num)
if num<0:
np.put(arr,range(len(arr)+num,len(arr)),np.nan)
elif num > 0:
np.put(arr,range(num),np.nan)
return arr
# use np.pad and slice by me.
def shift3(arr, num, fill_value=np.nan):
l = len(arr)
if num < 0:
arr = np.pad(arr, (0, abs(num)), mode='constant', constant_values=(fill_value,))[:-num]
elif num > 0:
arr = np.pad(arr, (num, 0), mode='constant', constant_values=(fill_value,))[:-num]
return arr
# use np.concatenate and np.full by chrisaycock
def shift4(arr, num, fill_value=np.nan):
if num >= 0:
return np.concatenate((np.full(num, fill_value), arr[:-num]))
else:
return np.concatenate((arr[-num:], np.full(-num, fill_value)))
# preallocate empty array and assign slice by chrisaycock
def shift5(arr, num, fill_value=np.nan):
result = np.empty_like(arr)
if num > 0:
result[:num] = fill_value
result[num:] = arr[:-num]
elif num < 0:
result[num:] = fill_value
result[:num] = arr[-num:]
else:
result[:] = arr
return result
arr = np.arange(2000).astype(float)
def benchmark_shift1():
shift1(arr, 3)
def benchmark_shift2():
shift2(arr, 3)
def benchmark_shift3():
shift3(arr, 3)
def benchmark_shift4():
shift4(arr, 3)
def benchmark_shift5():
shift5(arr, 3)
benchmark_set = ['benchmark_shift1', 'benchmark_shift2', 'benchmark_shift3', 'benchmark_shift4', 'benchmark_shift5']
for x in benchmark_set:
number = 10000
t = timeit.timeit('%s()' % x, 'from __main__ import %s' % x, number=number)
print '%s time: %f' % (x, t)
benchmark result:
benchmark_shift1 time: 0.265238
benchmark_shift2 time: 0.285175
benchmark_shift3 time: 0.473890
benchmark_shift4 time: 0.099049
benchmark_shift5 time: 0.052836
shift5 is winner! It's OP's third solution.
var dateTimeToday = new Date();
var dateToday = new Date(
dateTimeToday.getFullYear(),
(dateTimeToday.getMonth() + 1) /*Jan = 0! */,
dateTimeToday.getDate(),
0,
0,
0,
0);
Surprised no one mentioned C# 4.0 optional parameters that work like this:
public void SomeMethod(int a, int b = 0)
{
//some code
}
Edit: I know that at the time the question was asked, C# 4.0 didn't exist. But this question still ranks #1 in Google for "C# optional arguments" so I thought - this answer worth being here. Sorry.
If that kind of thing does not already exist, you can make an NSString category:
@interface NSString (TrucBiduleChoseAdditions)
- (BOOL)isEmpty;
@end
@implementation NSString (TrucBiduleChoseAdditions)
- (BOOL)isEmpty {
return self == nil || [@"" isEqualToString:self];
}
@end
Acording to your first code snipet seems ok, but I've got similar behavior caused by bad programing. Have you checked the "options" variable is not null before the put call?
I'm using Struts2 (2.3.3) webapp and use a HashMap for displaying results. When is executed (in a class initialized by an Action class) :
if(value != null) pdfMap.put("date",value.toString());
else pdfMap.put("date","");
Got this error:
Struts Problem Report
Struts has detected an unhandled exception:
Messages:
File: aoc/psisclient/samples/PDFValidation.java
Line number: 155
Stacktraces
java.lang.NullPointerException
aoc.psisclient.samples.PDFValidation.getRevisionsDetail(PDFValidation.java:155)
aoc.action.signature.PDFUpload.execute(PDFUpload.java:66)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
...
Seems the NullPointerException points to the put method (Line number 155), but the problem was that de Map hasn't been initialized before. It compiled ok since the variable is out of the method that set the value.
Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python
Update - new answer here: https://stackoverflow.com/a/19454282/411229. This answer only applies to those on Spring versions before 3.2.
I've looked for a while for a more definitive solution to this. This blog post seems to cover all my needs and doesn't rely on ordering of bean declarations. All credit to Mattias Severson. http://www.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/
Basically, implement a FactoryBean
package com.jayway.springmock;
import org.mockito.Mockito;
import org.springframework.beans.factory.FactoryBean;
/**
* A {@link FactoryBean} for creating mocked beans based on Mockito so that they
* can be {@link @Autowired} into Spring test configurations.
*
* @author Mattias Severson, Jayway
*
* @see FactoryBean
* @see org.mockito.Mockito
*/
public class MockitoFactoryBean<T> implements FactoryBean<T> {
private Class<T> classToBeMocked;
/**
* Creates a Mockito mock instance of the provided class.
* @param classToBeMocked The class to be mocked.
*/
public MockitoFactoryBean(Class<T> classToBeMocked) {
this.classToBeMocked = classToBeMocked;
}
@Override
public T getObject() throws Exception {
return Mockito.mock(classToBeMocked);
}
@Override
public Class<?> getObjectType() {
return classToBeMocked;
}
@Override
public boolean isSingleton() {
return true;
}
}
Next update your spring config with the following:
<beans...>
<context:component-scan base-package="com.jayway.example"/>
<bean id="someDependencyMock" class="com.jayway.springmock.MockitoFactoryBean">
<constructor-arg name="classToBeMocked" value="com.jayway.example.SomeDependency" />
</bean>
</beans>
The following query will insert the results directly into HDFS:
INSERT OVERWRITE DIRECTORY '/path/to/output/dir' SELECT * FROM table WHERE id > 100;
Below is a suggested approach to Question #1 which I use if I wish to use the ForEach-Object cmdlet. It does not directly answer the question because it does not EXIT the pipeline. However, it may achieve the desired effect in Q#1. The only drawback an amateur like myself can see is when processing large pipeline iterations.
$zStop = $false
(97..122) | Where-Object {$zStop -eq $false} | ForEach-Object {
$zNumeric = $_
$zAlpha = [char]$zNumeric
Write-Host -ForegroundColor Yellow ("{0,4} = {1}" -f ($zNumeric, $zAlpha))
if ($zAlpha -eq "m") {$zStop = $true}
}
Write-Host -ForegroundColor Green "My PSVersion = 5.1.18362.145"
I hope this is of use. Happy New Year to all.
Thread.sleep()
takes in the number of milliseconds to sleep, not seconds.
Sleeping for one millisecond is not noticeable. Try Thread.sleep(1000)
to sleep for one second.
I restarted my computer (Mac Mountain Lion) and the problem fixed itself. Something having to do with the shell thinking it was disconnected from the internet I think.
Restarting your shell in some definite way may solve this problem as well. Simply opening up a new session/window however did not work.
We have document.referrer for this, but it is not on which we can relay. This could be saved, could be not
$(document).ready(function() {
var referrer = document.referrer;
});
The better approach is to add a cookie to store the previous-url in the browser.
Suppose you store float value in "X"
and you are storing integer value in "Y"
.
Var Y = Int(x);
or
var myIntValue = Int(myFloatValue)
You can create a extension method:
public static IEnumerable<T> Do<T>(this IEnumerable<T> self, Action<T> action) {
foreach(var item in self) {
action(item);
yield return item;
}
}
And then use it in code:
listofCompany.Do(d=>d.Id = 1);
listofCompany.Where(d=>d.Name.Contains("Inc")).Do(d=>d.Id = 1);
See this: Demo
$('#cat_icon,.panel_title').click(function () {
$('#categories,#cat_icon').stop().slideToggle('slow');
});
Update : To slide from left to right: Demo2
Note: Second one uses jquery-ui also
For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.
Not always. NaN is a counterexample. But usually, identity (is
) implies equality (==
). The converse is not true: Two distinct objects can have the same value.
Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values?
You use ==
when comparing values and is
when comparing identities.
When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is
, but don't rely on it.
For boolean values, you shouldn't be doing comparisons at all. Instead of:
if x == True:
# do something
write:
if x:
# do something
For comparing against None
, is None
is preferred over == None
.
I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.
Yes, that's exactly what it's for.
For installing Composer below steps worked me:(WAMP version 2.4 x64bit)
edit ->
**C:\wamp\bin\php\php5.4.12\php.ini**
;;uncomment below line or remove the semicolons ';'
extension=php_openssl.dll
**C:\wamp\bin\apache\Apache2.4.4\bin\php.ini**
extension=php_openssl.dll
In Swift:
var uuid: String = NSUUID().UUIDString
println("uuid: \(uuid)")
Maybe you are looking for jar
command to get the list of classes in terminal,
$ jar tf ~/.m2/repository/org/apache/spark/spark-assembly/1.2.0-SNAPSHOT/spark-assembly-1.2.0-SNAPSHOT-hadoop1.0.4.jar
META-INF/
META-INF/MANIFEST.MF
org/
org/apache/
org/apache/spark/
org/apache/spark/unused/
org/apache/spark/unused/UnusedStubClass.class
META-INF/maven/
META-INF/maven/org.spark-project.spark/
META-INF/maven/org.spark-project.spark/unused/
META-INF/maven/org.spark-project.spark/unused/pom.xml
META-INF/maven/org.spark-project.spark/unused/pom.properties
META-INF/NOTICE
where,
-t list table of contents for archive
-f specify archive file name
Or, just grep above result to see .class
es only
$ jar tf ~/.m2/repository/org/apache/spark/spark-assembly/1.2.0-SNAPSHOT/spark-assembly-1.2.0-SNAPSHOT-hadoop1.0.4.jar | grep .class
org/apache/spark/unused/UnusedStubClass.class
To see number of class
es,
jar tvf launcher/target/usergrid-launcher-1.0-SNAPSHOT.jar | grep .class | wc -l
61079
Make use of jquery toggle function which do the task for you
.toggle() - Display or hide the matched elements.
$('#myelement').click(function(){
$('#another-element').toggle('slow');
});
You should be able to do the count on the purch variable:
purch.Count();
e.g.
var purch = from purchase in myBlaContext.purchases
select purchase;
purch.Count();
Just clone one of your existing repos, this will prompt you for new credentials:
e.g.
git clone https://[email protected]/mypath/myrepo.git
// https://[email protected]/mypath/myrepo.git is an address of one of your existing repos.
The big thing to keep in mind is that your headers should not be dependent upon other headers being included first. One way to insure this is to include your headers before any other headers.
"Thinking in C++" in particular mentions this, referencing Lakos' "Large Scale C++ Software Design":
Latent usage errors can be avoided by ensuring that the .h file of a component parses by itself – without externally-provided declarations or definitions... Including the .h file as the very first line of the .c file ensures that no critical piece of information intrinsic to the physical interface of the component is missing from the .h file (or, if there is, that you will find out about it as soon as you try to compile the .c file).
That is to say, include in the following order:
If any of the headers have an issue with being included in this order, either fix them (if yours) or don't use them. Boycott libraries that don't write clean headers.
Google's C++ style guide argues almost the reverse, with really no justification at all; I personally tend to favor the Lakos approach.
$(":button").click(function () {
$("#anchor_google")[0].click();
});
Use JavaScript objects. You can access their properties like keys in a dictionary. This is the foundation of JSON. The syntax is similar to Python dictionaries. See: JSON.org
Here is another way to loop through XML elements using JDOM.
List<Element> nodeNodes = inputNode.getChildren();
if (nodeNodes != null) {
for (Element nodeNode : nodeNodes) {
List<Element> elements = nodeNode.getChildren(elementName);
if (elements != null) {
elements.size();
nodeNodes.removeAll(elements);
}
}
The 'script' command under Unix should do the trick. Just run it at the start of your new console and you should be good.
See this video: http://youtu.be/AjQ5e9TOZVk?t=1m45s
You can do php artisan list
to view all commands,
The command for generating REST-ful controllers is controller:make
You can view the usage with: php artisan help make:controller
This isn't published on Arduino.cc but you can in fact exit from the loop routine with a simple exit(0);
This will compile on pretty much any board you have in your board list. I'm using IDE 1.0.6. I've tested it with Uno, Mega, Micro Pro and even the Adafruit Trinket
void loop() {
// All of your code here
/* Note you should clean up any of your I/O here as on exit,
all 'ON'outputs remain HIGH */
// Exit the loop
exit(0); //The 0 is required to prevent compile error.
}
I use this in projects where I wire in a button to the reset pin. Basically your loop runs until exit(0); and then just persists in the last state. I've made some robots for my kids, and each time the press a button (reset) the code starts from the start of the loop() function.
The problem is that a link to a closed file works with index( but not with index(indirect(
It seems to me that it is a programming issue of the index function. I solved it with a if clause row
C2=sheetname
if(c2=Sheet1,index(sheet1....),if(C2="Sheet2",index(sheet2....
I did it over five sheets, it's a long formula, but does what I need.
To hide the prompt set xls.DisplayAlerts = False
ConflictResolution
is not a true
or false
property, it should be xlLocalSessionChanges
Note that this has nothing to do with displaying the Overwrite prompt though!
Set xls = CreateObject("Excel.Application")
xls.DisplayAlerts = False
Set wb = xls.Workbooks.Add
fullFilePath = importFolderPath & "\" & "A.xlsx"
wb.SaveAs fullFilePath, AccessMode:=xlExclusive,ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
wb.Close (True)
try that :
declare @t nvarchar(max)
set @t='aaaa'
select len(@t)-len(replace(@t,'a',''))
Here is what's worked for me:
Open notepad++ and press F5. You'll get a little popup box:
Type: C:\Python27\python.exe -i "$(FULL_CURRENT_PATH)" for Python 2.7.
and then Save As..., and pick your own key combo to start it each time you want to run something
NOTE: This answer seems to be specific to: No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
, but it was linked here by:
From NDK r19b:
more ~/Android/Sdk/ndk-bundle/CHANGELOG.md
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
,
update your project file to [use plugin version 3.1 or newer]. You will also
need to upgrade to Android Studio 3.1 or newer.This worked for me. Its tedious to set all the colour options for a series, especially if it's dynamic
plotOptions: {
column: {
colorByPoint: true
}
}
Make an effort to configure your build path. Code completion uses a lot of memory if it has to go through your whole project folder.
$rand = substr(md5(microtime()),rand(0,26),5);
Would be my best guess--Unless you're looking for special characters, too:
$seed = str_split('abcdefghijklmnopqrstuvwxyz'
.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.'0123456789!@#$%^&*()'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];
And, for one based on the clock (fewer collisions since it's incremental):
function incrementalHash($len = 5){
$charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$base = strlen($charset);
$result = '';
$now = explode(' ', microtime())[1];
while ($now >= $base){
$i = $now % $base;
$result = $charset[$i] . $result;
$now /= $base;
}
return substr($result, -5);
}
Note: incremental means easier to guess; If you're using this as a salt or a verification token, don't. A salt (now) of "WCWyb" means 5 seconds from now it's "WCWyg")
You can do something like this to read 10 bytes:
char buffer[10];
read(STDIN_FILENO, buffer, 10);
remember read() doesn't add '\0'
to terminate to make it string (just gives raw buffer).
To read 1 byte at a time:
char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
//do stuff
}
and don't forget to #include <unistd.h>
, STDIN_FILENO
defined as macro in this file.
There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:
Integer value Name
0 Standard input (stdin)
1 Standard output (stdout)
2 Standard error (stderr)
So instead STDIN_FILENO
you can use 0.
Edit:
In Linux System you can find this using following command:
$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define STDIN_FILENO 0 /* Standard input. */
Notice the comment /* Standard input. */
(Let's just all agree that TreeView is obviously busted in respect to this problem. Binding to SelectedItem would have been obvious. Sigh)
I needed the solution to interact properly with the IsSelected property of TreeViewItem, so here's how I did it:
// the Type CustomThing needs to implement IsSelected with notification
// for this to work.
public class CustomTreeView : TreeView
{
public CustomThing SelectedCustomThing
{
get
{
return (CustomThing)GetValue(SelectedNode_Property);
}
set
{
SetValue(SelectedNode_Property, value);
if(value != null) value.IsSelected = true;
}
}
public static DependencyProperty SelectedNode_Property =
DependencyProperty.Register(
"SelectedCustomThing",
typeof(CustomThing),
typeof(CustomTreeView),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.None,
SelectedNodeChanged));
public CustomTreeView(): base()
{
this.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(SelectedItemChanged_CustomHandler);
}
void SelectedItemChanged_CustomHandler(object sender, RoutedPropertyChangedEventArgs<object> e)
{
SetValue(SelectedNode_Property, SelectedItem);
}
private static void SelectedNodeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var treeView = d as CustomTreeView;
var newNode = e.NewValue as CustomThing;
treeView.SelectedCustomThing = (CustomThing)e.NewValue;
}
}
With this XAML:
<local:CustonTreeView ItemsSource="{Binding TreeRoot}"
SelectedCustomThing="{Binding SelectedNode,Mode=TwoWay}">
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>
</TreeView.ItemContainerStyle>
</local:CustonTreeView>
To kill from the application, you can do:
android.os.Process.killProcess(android.os.Process.myPid());
For npm: you can run:
npm update -g typescript
By default, it will install latest version.
For yarn, you can run:
yarn upgrade typescript
Or you can remove the orginal version, run yarn global remove typescript
, and then execute yarn global add typescript
, by default it will also install the latest version of typescript.
more details, you can read yarn docs.
If your bound property is DateTime, then all you need is
Binding={Property, StringFormat=d}
Right click on your project -> Android Tool -> Add support library
Type Ctrl+p then Ctrl+q. It will help you to turn interactive mode to daemon mode.
See https://docs.docker.com/v1.7/articles/basics/#running-an-interactive-shell.
# To detach the tty without exiting the shell,
# use the escape sequence Ctrl-p + Ctrl-q
# note: This will continue to exist in a stopped state once exited (see "docker ps -a")
Use window.open()
:
var win = window.open('http://stackoverflow.com/', '_blank');
if (win) {
//Browser has allowed it to be opened
win.focus();
} else {
//Browser has blocked it
alert('Please allow popups for this website');
}
Depending on the browsers implementation this will work
There is nothing you can do to make it open in a window rather than a tab.
If you have no changes, you can always be really thorough and/or lazy and do...
rm -rf *
svn update
But, no really, do not do that unless you are really sure that the nuke-from-space option is what you want!! This has the advantage of also nuking all build cruft, temporary files, and things that SVN ignores.
The more correct solution is to use the revert command:
svn revert -R .
The -R causes subversion to recurse and revert everything in and below the current working directory.
Swift 4.x
extension UIButton {
func centerTextAndImage(spacing: CGFloat) {
let insetAmount = spacing / 2
let writingDirection = UIApplication.shared.userInterfaceLayoutDirection
let factor: CGFloat = writingDirection == .leftToRight ? 1 : -1
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount*factor, bottom: 0, right: insetAmount*factor)
self.titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount*factor, bottom: 0, right: -insetAmount*factor)
self.contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
}
}
Usage:
button.centerTextAndImage(spacing: 10.0)
And another way:
<a href="javascript:history.back()">Go Back</a>
_x000D_
You can't compare a specific point in time (such as "right now") against an unfixed, recurring event (8am happens every day).
You can check if now is before or after today's 8am:
>>> import datetime
>>> now = datetime.datetime.now()
>>> today8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
>>> now < today8am
True
>>> now == today8am
False
>>> now > today8am
False
To answer your additional question how disable views caching:
You can do this by automatically delete the files in the folder for each request with the command php artisan view:clear
mentioned by DilipGurung. Here is an example Middleware class from https://stackoverflow.com/a/38598434/2311074
<?php
namespace App\Http\Middleware;
use Artisan;
use Closure;
class ClearViewCache
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (env('APP_DEBUG') || env('APP_ENV') === 'local')
Artisan::call('view:clear');
return $next($request);
}
}
However you may note that Larevel will recompile the files in the /app/storage/views folder whenever the time on the views files is earlier than the time on the PHP blade files for the layout. THus, I cannot really think of a scenario where this would be necessary to do.
The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.
This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):
See:
If you're looking for a great global .gitignore
file for any Visual Studio ( .NET ) solution - I recommend you to use this one: https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
AFAIK it has the most comprehensive .gitignore
for .NET projects.
From long to DateTime: new DateTime(long ticks)
From DateTime to long: DateTime.Ticks
You can use DataBinding and ViewModel for Switch Checked Change event
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="com.example.ui.ViewModel" />
</data>
<Switch
android:id="@+id/on_off_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onCheckedChanged="@{(button, on) -> viewModel.onCheckedChange(on)}"
/>
dynamic_cast
is known to be inefficient. It traverses up the inheritance hierarchy, and it is the only solution if you have multiple levels of inheritance, and need to check if an object is an instance of any one of the types in its type hierarchy.
But if a more limited form of instanceof
that only checks if an object is exactly the type you specify, suffices for your needs, the function below would be a lot more efficient:
template<typename T, typename K>
inline bool isType(const K &k) {
return typeid(T).hash_code() == typeid(k).hash_code();
}
Here's an example of how you'd invoke the function above:
DerivedA k;
Base *p = &k;
cout << boolalpha << isType<DerivedA>(*p) << endl; // true
cout << boolalpha << isType<DerivedB>(*p) << endl; // false
You'd specify template type A
(as the type you're checking for), and pass in the object you want to test as the argument (from which template type K
would be inferred).
Press CMD + SHIFT + P
(MAC) and search for Toggle Editor Group
First you need to think off when you want to swap. For example you could switch everytime when its a div tag thats loaded. In my example i just used a extra data field "background" and whenever its set the image is applied as a background image.
Then you just have to load the Data with the created image tag. And not overwrite the img tag instead apply a css background image.
Here is a example of the code change:
if (settings.appear) {
var elements_left = elements.length;
settings.appear.call(self, elements_left, settings);
}
var loadImgUri;
if($self.data("background"))
loadImgUri = $self.data("background");
else
loadImgUri = $self.data(settings.data_attribute);
$("<img />")
.bind("load", function() {
$self
.hide();
if($self.data("background")){
$self.css('backgroundImage', 'url('+$self.data("background")+')');
}else
$self.attr("src", $self.data(settings.data_attribute))
$self[settings.effect](settings.effect_speed);
self.loaded = true;
/* Remove image from array so it is not looped next time. */
var temp = $.grep(elements, function(element) {
return !element.loaded;
});
elements = $(temp);
if (settings.load) {
var elements_left = elements.length;
settings.load.call(self, elements_left, settings);
}
})
.attr("src", loadImgUri );
}
the loading stays the same
$("#divToLoad").lazyload();
and in this example you need to modify the html code like this:
<div data-background="http://apod.nasa.gov/apod/image/9712/orionfull_jcc_big.jpg" id="divToLoad" />?
but it would also work if you change the switch to div tags and then you you could work with the "data-original" attribute.
Here's an fiddle example: http://jsfiddle.net/dtm3k/1/
In query, CONCAT_WS()
function.
This function not only add multiple string values and makes them a single string value. It also let you define separator ( ” “, ” , “, ” – “,” _ “, etc.).
Syntax –
CONCAT_WS( SEPERATOR, column1, column2, ... )
Example
SELECT
topic,
CONCAT_WS( " ", subject, year ) AS subject_year
FROM table
you can just split it up and get the last element
var string="xxx_456";
var a=string.split("_");
alert(a[1]); #or a.pop
Statically Typed
The types are checked before run-time so mistakes can be caught earlier.
Examples = c++
Dynamically Typed
The types are checked during execution.
Examples = Python
You can do this with JQuery
Simply:
<form name='add'>
Age: <select id="age" name='age'>
<option value='1' stud_name='sre'>23</option>
<option value='2' stud_name='sam'>24</option>
<option value='5' stud_name='john'>25</option>
</select>
<input type='hidden' id="name" name="name" value=""/>
<input type='submit' name='submit'/>
</form>
Add this code in Header section:
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
Now JQuery function
<script type="text/javascript" language="javascript">
$(function() {
$("#age").change(function(){
var studentNmae= $('option:selected', this).attr('stud_name');
$('#name').val(studentNmae);
});
});
</script>
you can use both values as
$name = $_POST['name'];
$value = $_POST['age'];
@ECHO OFF
:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/
:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"
:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m
:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m
PAUSE
I had this error today and discovered it was an incorrectly-formatted year...
select * from es_timeexpense where parsedate > to_date('12/3/2018', 'MM/dd/yyy')
Notice the year has only three 'y's. It should have 4.
Double-check your format.
let a = {};_x000D_
let b = {};_x000D_
_x000D_
a.prop1 = 2;_x000D_
a.prop2 = { prop3: 2 };_x000D_
_x000D_
b.prop1 = 2;_x000D_
b.prop2 = { prop3: 3 };_x000D_
_x000D_
JSON.stringify(a) === JSON.stringify(b);_x000D_
// false_x000D_
b.prop2 = { prop3: 2};_x000D_
_x000D_
JSON.stringify(a) === JSON.stringify(b);_x000D_
// true
_x000D_
We can combine the DUAL and NOT EXISTS to archive your requirement:
INSERT INTO schema.myFoo (
primary_key, value1, value2
)
SELECT
'bar', 'baz', 'bat'
FROM DUAL
WHERE NOT EXISTS (
SELECT 1
FROM schema.myFoo
WHERE primary_key = 'bar'
);
I have the same problem that you describe although I'm building up my LatLngBounds as proposed by above. The problem is that things are async and calling map.fitBounds()
at the wrong time may leave you with a result like in the Q.
The best way I found is to place the call in an idle handler like this:
google.maps.event.addListenerOnce(map, 'idle', function() {
map.fitBounds(markerBounds);
});
Try this:
[https://lodash.com/docs/4.17.4#clone][1]
var objects = [{ 'a': 1 }, { 'b': 2 }];
var shallow = _.clone(objects);
console.log(shallow[0] === objects[0]);
// => true
Please check if any jar files missing particularly jars are may have been taken as locally, so put into lib folder then create the WAR file
$pos = $name.IndexOf(";")
$leftPart = $name.Substring(0, $pos)
$rightPart = $name.Substring($pos+1)
Internally, PowerShell uses the String class.
In Sybase SQL Anywhere, the columns and table information are stored separately, so you need a join:
select c.column_name from systabcol c
key join systab t on t.table_id=c.table_id
where t.table_name='tablename'
This is the best and simplest way to understand joins:
Credits go to the writer of this article HERE
matches()
will only return true if the full string is matched.
find()
will try to find the next occurrence within the substring that matches the regex. Note the emphasis on "the next". That means, the result of calling find()
multiple times might not be the same. In addition, by using find()
you can call start()
to return the position the substring was matched.
final Matcher subMatcher = Pattern.compile("\\d+").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + subMatcher.matches());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find());
System.out.println("Found: " + subMatcher.find());
System.out.println("Matched: " + subMatcher.matches());
System.out.println("-----------");
final Matcher fullMatcher = Pattern.compile("^\\w+$").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + fullMatcher.find() + " - position " + fullMatcher.start());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
Will output:
Found: false Found: true - position 4 Found: true - position 17 Found: true - position 20 Found: false Found: false Matched: false ----------- Found: true - position 0 Found: false Found: false Matched: true Matched: true Matched: true Matched: true
So, be careful when calling find()
multiple times if the Matcher
object was not reset, even when the regex is surrounded with ^
and $
to match the full string.
Raystorm had a good answer. I'm not a big fan of Rules either. I do something similar, except that I create the following utility class to help readability and usability, which is one of the big plus'es of annotations in the first place.
Add this utility class:
import org.junit.Assert;
public abstract class ExpectedRuntimeExceptionAsserter {
private String expectedExceptionMessage;
public ExpectedRuntimeExceptionAsserter(String expectedExceptionMessage) {
this.expectedExceptionMessage = expectedExceptionMessage;
}
public final void run(){
try{
expectException();
Assert.fail(String.format("Expected a RuntimeException '%s'", expectedExceptionMessage));
} catch (RuntimeException e){
Assert.assertEquals("RuntimeException caught, but unexpected message", expectedExceptionMessage, e.getMessage());
}
}
protected abstract void expectException();
}
Then for my unit test, all I need is this code:
@Test
public void verifyAnonymousUserCantAccessPrivilegedResourceTest(){
new ExpectedRuntimeExceptionAsserter("anonymous user can't access privileged resource"){
@Override
protected void expectException() {
throw new RuntimeException("anonymous user can't access privileged resource");
}
}.run(); //passes test; expected exception is caught, and this @Test returns normally as "Passed"
}
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
For those who have Excel 2016 (and I suppose next versions), there is now directly the CONCAT function, which will replace the CONCATENATE function.
So the correct way to do it in Excel 2016 is :
=CONCAT(A1:A4)
which will produce :
Iamaboy
For users of olders versions of Excel, the other answers are relevant.
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
It's was great if delete return the delete pair of the hash. I'm doing this:
hash = {a: 1, b: 2, c: 3}
{b: hash.delete(:b)} # => {:b=>2}
hash # => {:a=>1, :c=>3}
With Symfony 3.3, I have used this method and working fine.
I have 4 routes like
admin_category_index, admin_category_detail, admin_category_create, admin_category_update
And just one line make an active class for all routes.
<li {% if app.request.get('_route') starts with 'admin_category' %} class="active"{% endif %}>
<a href="{{ path('admin_category_index') }}">Product Categoires</a>
</li>
An example Extension class to simplify this: -
internal static class String
{
public static string TrimEndsCharacter(this string target, char character) => target?.TrimLeadingCharacter(character).TrimTrailingCharacter(character);
public static string TrimLeadingCharacter(this string target, char character) => Match(target?.Substring(0, 1), character) ? target.Remove(0,1) : target;
public static string TrimTrailingCharacter(this string target, char character) => Match(target?.Substring(target.Length - 1, 1), character) ? target.Substring(0, target.Length - 1) : target;
private static bool Match(string value, char character) => !string.IsNullOrEmpty(value) && value[0] == character;
}
Usage
"!Something!".TrimLeadingCharacter('X'); // Result '!Something!' (No Change)
"!Something!".TrimTrailingCharacter('S'); // Result '!Something!' (No Change)
"!Something!".TrimEndsCharacter('g'); // Result '!Something!' (No Change)
"!Something!".TrimLeadingCharacter('!'); // Result 'Something!' (1st Character removed)
"!Something!".TrimTrailingCharacter('!'); // Result '!Something' (Last Character removed)
"!Something!".TrimEndsCharacter('!'); // Result 'Something' (End Characters removed)
"!!Something!!".TrimLeadingCharacter('!'); // Result '!Something!!' (Only 1st instance removed)
"!!Something!!".TrimTrailingCharacter('!'); // Result '!!Something!' (Only Last instance removed)
"!!Something!!".TrimEndsCharacter('!'); // Result '!Something!' (Only End instances removed)
Try setting the style to display=none:
<img src="a.gif" style="display:none">
I ran into a similar situation with code that WAS working , then was not.
Turned while dragging / dropping code within a file, I moved an object into another set of braces. Took longer to figure out than I care to admit.
Bit once I move the code back into its proper place, the error resolved.
I agree with @bortunac's solution. my.conf is mysql specific while netstat will provide you with all the listening ports.
Perhaps use both, one to confirm which is port set for mysql and the other to check that the system is listening through that port.
My client uses CentOS 6.6 and I have found the my.conf file under /etc/, so I used:
grep port /etc/my.conf
(CentOS 6.6)
I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound
This means that nothing is bound to the jndi name greetJndi
, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.
Is there any specific directory structure to deploy in JBoss?
The internal structure of the ejb-jar
is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):
. +-- greetBean.java +-- greetHome.java +-- greetRemote.java +-- META-INF +-- ejb-jar.xml +-- jboss.xml
But as already mentioned, this tutorial is full of mistakes:
<enterprise-beans>]
<-- HERE) in the ejb-jar.xml
(!)PUBLIC
in the ejb-jar.xml
and jboss.xml
(!!)jboss.xml
is incorrect, it should contain a session
element instead of entity
(!!!)Here is a "fixed" version of the ejb-jar.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<home>greetHome</home>
<remote>greetRemote</remote>
<ejb-class>greetBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
And of the jboss.xml
:
<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<jndi-name>greetJndi</jndi-name>
</session>
</enterprise-beans>
</jboss>
After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:
21:48:06,512 INFO [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/} 21:48:06,534 INFO [EjbDeployer] installing bean: ejb/#greetBean,uid19981448 21:48:06,534 INFO [EjbDeployer] with dependencies: 21:48:06,534 INFO [EjbDeployer] and supplies: 21:48:06,534 INFO [EjbDeployer] jndi:greetJndi 21:48:06,624 INFO [EjbModule] Deploying greetBean 21:48:06,661 WARN [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/ 21:48:06,805 INFO [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'
That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.
points
or lines
comes handy if
y2
is generated later, orx
but still should go into the same coordinate system.As your y
s share the same x
, you can also use matplot
:
matplot (x, cbind (y1, y2), pch = 19)
(without the pch
matplopt
will plot the column numbers of the y
matrix instead of dots).
Another Apache ObjectUtils example. Able to sort other types of objects.
@Override
public int compare(Object o1, Object o2) {
String s1 = ObjectUtils.toString(o1);
String s2 = ObjectUtils.toString(o2);
return s1.toLowerCase().compareTo(s2.toLowerCase());
}
Try deleting the virtualenv you created. Then create a new virtualenv with:
virtualenv flask
Then:
cd flask
Now let's activate the virtualenv
source bin/activate
Now you should see (flask)
on the left of the command line.
Edit: In windows there is no "source" that's a linux thing, instead execute the activate.bat file, here I do it using Powershell: PS C:\DEV\aProject> & .\Flask\Scripts\activate
)
Let's install flask:
pip install flask
Then create a file named hello.py
(NOTE: see UPDATE Flask 1.0.2
below):
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
and run it with:
python hello.py
UPDATE Flask 1.0.2
With the new flask release there is no need to run the app from your script. hello.py
should look like this now:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
and run it with:
FLASK_APP=hello.py flask run
Make sure to be inside the folder where hello.py
is when running the latest command.
All the steps before the creation of the hello.py apply for this case as well
I much prefer the array
module to the struct
module for this kind of tasks (ones involving sequences of homogeneous values):
>>> import array
>>> array.array('B', [17, 24, 121, 1, 12, 222, 34, 76]).tostring()
'\x11\x18y\x01\x0c\xde"L'
no len
call, no string manipulation needed, etc -- fast, simple, direct, why prefer any other approach?!
In info.plist
View controller-based status bar appearance NO
Status bar is initially hidden YES
In view controller.m
- (BOOL) prefersStatusBarHidden
{
return YES;
}
#!/bin/bash
function git.branch {
br=`git branch | grep "*"`
echo ${br/* /}
}
git.branch
For me, one neat way to do this is to show a SnackBar
at the bottom while the Signing-In process is taken place, this is a an example of what I mean:
Here is how to setup the SnackBar
.
Define a global key for your Scaffold
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
Add it to your Scaffold
key
attribute
return new Scaffold(
key: _scaffoldKey,
.......
My SignIn button onPressed
callback:
onPressed: () {
_scaffoldKey.currentState.showSnackBar(
new SnackBar(duration: new Duration(seconds: 4), content:
new Row(
children: <Widget>[
new CircularProgressIndicator(),
new Text(" Signing-In...")
],
),
));
_handleSignIn()
.whenComplete(() =>
Navigator.of(context).pushNamed("/Home")
);
}
It really depends on how you want to build your layout, and I am not sure what you have in mind.
Edit
You probably want it this way, I have used a Stack to achieve this result and just show or hide my indicator based on onPressed
class TestSignInView extends StatefulWidget {
@override
_TestSignInViewState createState() => new _TestSignInViewState();
}
class _TestSignInViewState extends State<TestSignInView> {
bool _load = false;
@override
Widget build(BuildContext context) {
Widget loadingIndicator =_load? new Container(
color: Colors.grey[300],
width: 70.0,
height: 70.0,
child: new Padding(padding: const EdgeInsets.all(5.0),child: new Center(child: new CircularProgressIndicator())),
):new Container();
return new Scaffold(
backgroundColor: Colors.white,
body: new Stack(children: <Widget>[new Padding(
padding: const EdgeInsets.symmetric(vertical: 50.0, horizontal: 20.0),
child: new ListView(
children: <Widget>[
new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center
,children: <Widget>[
new TextField(),
new TextField(),
new FlatButton(color:Colors.blue,child: new Text('Sign In'),
onPressed: () {
setState((){
_load=true;
});
//Navigator.of(context).push(new MaterialPageRoute(builder: (_)=>new HomeTest()));
}
),
],),],
),),
new Align(child: loadingIndicator,alignment: FractionalOffset.center,),
],));
}
}
I think you may be looking for Jagged Arrays, which are different from multi-dimensional arrays (as you are using in your example) in C#. Converting the arrays in your declarations to jagged arrays should make it work. However, you'll still need to use two loops to iterate over all the items in the 2D jagged array.
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
Why not using Cakes Response Class? You can set the status code of the response simply by this:
$this->response->statusCode(200);
Then just render a file with the error message, which suits best with JSON.
I am heavily tempted to close this as a duplicate; this question appears to be answered in many different ways all over the site:
I find the easiest way is to double up on the quotes to handle a quote.
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)"
Some people like to use CHR(34)*:
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"
*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.
I tried using:
Range(cells(1, 1), cells(lastRow, lastColumn)).Select
where lastRow
and lastColumn
are integers, but received run-time error 1004. I'm using an older VB (6.5).
What did work was to use the following:
Range(Chr(64 + firstColumn) & firstRow & ":" & Chr(64 + lastColumn) & firstColumn).Select.
Find the process and terminate it. On Windows do a Control+Alt+Delete and then find the "Java(TM) Platform SE Binary" process under the Processes Tab. For example:
On Ubuntu, you can use "ps aux | grep java" to find the process and "kill -9 PID_NUMBER" to kill the process.
OR
If you're using a Spring boot application, go to application.properties and add this:
server.port = 8081
You have to be cautious of double line breaks, which would cause double spaces. Use this really efficient regular expression:
$string = trim(preg_replace('/\s\s+/', ' ', $string));
Multiple spaces and newlines are replaced with a single space.
Edit: As others have pointed out, this solution has issues matching single newlines in between words. This is not present in the example, but one can easily see how that situation could occur. An alternative is to do the following:
$string = trim(preg_replace('/\s+/', ' ', $string));
Look if you have a typo error in your importation or your class generation, it could be simply that.
There are some predefined formats in date_d.php
to use with format
like:
define ('DATE_ATOM', "Y-m-d\TH:i:sP");
define ('DATE_COOKIE', "l, d-M-y H:i:s T");
define ('DATE_ISO8601', "Y-m-d\TH:i:sO");
define ('DATE_RFC822', "D, d M y H:i:s O");
define ('DATE_RFC850', "l, d-M-y H:i:s T");
define ('DATE_RFC1036', "D, d M y H:i:s O");
define ('DATE_RFC1123', "D, d M Y H:i:s O");
define ('DATE_RFC2822', "D, d M Y H:i:s O");
define ('DATE_RFC3339', "Y-m-d\TH:i:sP");
define ('DATE_RSS', "D, d M Y H:i:s O");
define ('DATE_W3C', "Y-m-d\TH:i:sP");
Use like this:
$date = new \DateTime();
$string = $date->format(DATE_RFC2822);
use "-e" to specify the sed-expression
cat input.txt | sed -e 's/foo/bar/g'
I was able to install libc6 2.17
in Debian Wheezy
by editing the recommendations in perror's answer:
IMPORTANT
You need to exit out of your display manager by pressing CTRL-ALT-F1.
Then you can stop x (slim
) with sudo /etc/init.d/slim stop
(replace slim with mdm
or lightdm
or whatever)
Add the following line to the file /etc/apt/sources.list
:
deb http://ftp.debian.org/debian experimental main
Should be changed to:
deb http://ftp.debian.org/debian sid main
Then follow the rest of perror's post:
Update your package database:
apt-get update
Install the eglibc
package:
apt-get -t sid install libc6-amd64 libc6-dev libc6-dbg
IMPORTANT
After done updating libc6
, restart computer, and you should comment out or remove the sid source you just added (deb http://ftp.debian.org/debian sid main
), or else you risk upgrading your whole distro to sid.
Hope this helps. It took me a while to figure out.
You can either make your variable non static
public final String TTT = (String) getText(R.string.TTT);
or make the "getText" method static (if at all possible)
glib has functions for base64 encoding: https://developer.gnome.org/glib/stable/glib-Base64-Encoding.html
Arr1 becomes an array of 'Variant' by the first statement of your code:
Dim arr1() As Variant
Array of size zero is not empty, as like an empty box exists in real world.
If you define a variable of 'Variant', that will be empty when it is created.
Following code will display "Empty".
Dim a as Variant
If IsEmpty(a) then
MsgBox("Empty")
Else
MsgBox("Not Empty")
End If
I could have used RegEx, they can provide elegant solution but they can cause performane issues. Here is one solution
char[] arr = str.ToCharArray();
arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
|| char.IsWhiteSpace(c)
|| c == '-')));
str = new string(arr);
When using the compact framework (which doesn't have FindAll)
Replace FindAll with1
char[] arr = str.Where(c => (char.IsLetterOrDigit(c) ||
char.IsWhiteSpace(c) ||
c == '-')).ToArray();
str = new string(arr);