Bootstrap 3 Align Text To Bottom of Div
I collected some ideas from other SO question (largely from here and this css page)
Fiddle
The idea is to use relative and absolute positioning to move your line to the bottom:
@media (min-width: 768px ) {
.row {
position: relative;
}
#bottom-align-text {
position: absolute;
bottom: 0;
right: 0;
}}
The display:flex
option is at the moment a solution to make the div get the same size as its parent. This breaks on the other hand the bootstrap possibilities to auto-linebreak on small devices by adding col-sx-12
class. (This is why the media query is needed)
Trim specific character from a string
This one trims all leading and trailing delimeters
const trim = (str, delimiter) => {
const pattern = `[^\\${delimiter}]`;
const start = str.search(pattern);
const stop = str.length - str.split('').reverse().join('').search(pattern);
return str.substring(start, stop);
}
const test = '||2|aaaa12bb3ccc|||||';
console.log(trim(test, '|')); // 2|aaaa12bb3ccc
Serialize form data to JSON
Trying to solve the same problem (validation without getting into complex plugins and libraries), I created jQuery.serializeJSON, that improves serializeArray to support any kind of nested objects.
This plugin got very popular, but in another project I was using Backbone.js, where I would like to write the validation logic in the Backbone.js models. Then I created Backbone.Formwell, which allows you to show the errors returned by the validation method directly in the form.
How do I write stderr to a file while using "tee" with a pipe?
To redirect stderr to a file, display stdout to screen, and also save stdout to a file:
./aaa.sh 2>ccc.out | tee ./bbb.out
EDIT: To display both stderr and stdout to screen and also save both to a file, you can use bash's I/O redirection:
#!/bin/bash
# Create a new file descriptor 4, pointed at the file
# which will receive stderr.
exec 4<>ccc.out
# Also print the contents of this file to screen.
tail -f ccc.out &
# Run the command; tee stdout as normal, and send stderr
# to our file descriptor 4.
./aaa.sh 2>&4 | tee bbb.out
# Clean up: Close file descriptor 4 and kill tail -f.
exec 4>&-
kill %1
Why does Vim save files with a ~ extension?
You're correct that the .swp
file is used by vim for locking and as a recovery file.
Try putting set nobackup
in your vimrc if you don't want these files. See the Vim docs for various backup related options if you want the whole scoop, or want to have .bak files instead...
MySQL high CPU usage
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.
Jackson overcoming underscores in favor of camel-case
Annotating all model classes looks to me as an overkill and Kenny's answer didn't work for me https://stackoverflow.com/a/43271115/4437153. The result of serialization was still camel case.
I realised that there is a problem with my spring configuration, so I had to tackle that problem from another side. Hopefully someone finds it useful, but if I'm doing something against springs' rules then please let me know.
Solution for Spring MVC 5.2.5 and Jackson 2.11.2
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper);
converters.add(converter);
}
}
Spring expected at least 1 bean which qualifies as autowire candidate for this dependency
If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:
public class ThreadProvider implements CustomInterface{
...
}
Then in your controller try this:
@Controller
public class ChiusuraController {
@Autowired
private CustomInterface chiusuraProvider;
}
The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider
extend ThreadProvider
Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).
When you DID extend from ThreadProvider
assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider
type.
If you absolutely need to use ChisuraProvider
you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:
<aop:aspectj-autoproxy proxy-target-class="true"/>
Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb
Retrieve all values from HashMap keys in an ArrayList Java
Suppose I have Hashmap with key datatype as KeyDataType
and value datatype as ValueDataType
HashMap<KeyDataType,ValueDataType> list;
Add all items you needed to it.
Now you can retrive all hashmap keys to a list by.
KeyDataType[] mKeys;
mKeys=list.keySet().toArray(new KeyDataType[list.size()]);
So, now you got your all keys in an array mkeys[]
you can now retrieve any value by calling
list.get(mkeys[position]);
Form submit with AJAX passing form data to PHP without page refresh
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-6 col-xs-12"></div>enter code here
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="msg"></div>
<form method="post" class="frm" id="form1" onsubmit="">
<div class="form-group">
<input type="text" class="form-control" name="fname" id="fname" placeholder="enter your first neme" required>
<!--><span class="sp"><?php// echo $f_err;?></span><!-->
</div>
<div class="form-group">
<input type="text" class="form-control" name="lname" id="lname" placeholder="enter your last neme" required>
<!--><span class="sp"><?php// echo $l_err;?></span><!-->
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" id="email" placeholder="enter your email Address" required>
<!--><span class="sp"><?php// echo $e_err;?></span><!-->
</div>
<div class="form-group">
<input type="number" class="form-control" name="mno" id="mno" placeholder="enter your mobile number" required>
<!--><span class="sp"><?php //echo $m_err;?></span><!-->
</div>
<div class="form-group">
<input type="password" class="form-control" name="pass" id="pass" pattern="(?=.*[a-z])(?=.*[A-Z]).{4,8}" placeholder="enter your Password" required>
<!--><span class="sp"><?php //echo $p_err;?></span><!-->
</div>
<div class="radio">
<input type="radio" value="male" name="gender" id="gender" checked>male<br>
<input type="radio" value="female" name="gender" id="gender">female<br>
<input type="radio" value="other" name="gender" id="gender">other<br>
<!--><span class="sp"> <?php //echo $r_err;?></span><!-->
</div>
<div class="checkbox">
<input type="checkbox" name="check" id="check" checked>I Agree Turms&Condition<br>
<!--><span class="sp"> <?php //echo $c_err;?></span><!-->
</div>
<input type="submit" class="btn btn-warning" name="submit" id="submit">
</form>enter code here
</div>
<div class="col-md-3 col-sm-6 col-xs-12"></div>
</div>
</div>
CMD: Export all the screen content to a text file
If you want to output ALL verbosity, not just stdout. But also any printf statements made by the program, any warnings, infos, etc, you have to add 2>&1
at the end of the command line.
In your case, the command will be
Program.exe > file.txt 2>&1
How to split a list by comma not space
Set IFS to ,:
sorin@sorin:~$ IFS=',' ;for i in `echo "Hello,World,Questions,Answers,bash shell,script"`; do echo $i; done
Hello
World
Questions
Answers
bash shell
script
sorin@sorin:~$
How do I check if an integer is even or odd?
This is a follow up to the discussion with @RocketRoy regarding his answer, but it might be useful to anyone who wants to compare these results.
tl;dr From what I've seen, Roy's approach ((0xFFFFFFFF == (x | 0xFFFFFFFE)
) is not completely optimized to x & 1
as the mod
approach, but in practice running times should turn out equal in all cases.
So, first I compared the compiled output using Compiler Explorer:
Functions tested:
int isOdd_mod(unsigned x) {
return (x % 2);
}
int isOdd_and(unsigned x) {
return (x & 1);
}
int isOdd_or(unsigned x) {
return (0xFFFFFFFF == (x | 0xFFFFFFFE));
}
CLang 3.9.0 with -O3:
isOdd_mod(unsigned int): # @isOdd_mod(unsigned int)
and edi, 1
mov eax, edi
ret
isOdd_and(unsigned int): # @isOdd_and(unsigned int)
and edi, 1
mov eax, edi
ret
isOdd_or(unsigned int): # @isOdd_or(unsigned int)
and edi, 1
mov eax, edi
ret
GCC 6.2 with -O3:
isOdd_mod(unsigned int):
mov eax, edi
and eax, 1
ret
isOdd_and(unsigned int):
mov eax, edi
and eax, 1
ret
isOdd_or(unsigned int):
or edi, -2
xor eax, eax
cmp edi, -1
sete al
ret
Hats down to CLang, it realized that all three cases are functionally equal. However, Roy's approach isn't optimized in GCC, so YMMV.
It's similar with Visual Studio; inspecting the disassembly Release x64 (VS2015) for these three functions, I could see that the comparison part is equal for "mod" and "and" cases, and slightly larger for the Roy's "or" case:
// x % 2
test bl,1
je (some address)
// x & 1
test bl,1
je (some address)
// Roy's bitwise or
mov eax,ebx
or eax,0FFFFFFFEh
cmp eax,0FFFFFFFFh
jne (some address)
However, after running an actual benchmark for comparing these three options (plain mod, bitwise or, bitwise and), results were completely equal (again, Visual Studio 2005 x86/x64, Release build, no debugger attached).
Release assembly uses the test
instruction for and
and mod
cases, while Roy's case uses the cmp eax,0FFFFFFFFh
approach, but it's heavily unrolled and optimized so there is no difference in practice.
My results after 20 runs (i7 3610QM, Windows 10 power plan set to High Performance):
[Test: Plain mod 2 ] AVERAGE TIME: 689.29 ms (Relative diff.: +0.000%)
[Test: Bitwise or ] AVERAGE TIME: 689.63 ms (Relative diff.: +0.048%)
[Test: Bitwise and ] AVERAGE TIME: 687.80 ms (Relative diff.: -0.217%)
The difference between these options is less than 0.3%, so it's rather obvious the assembly is equal in all cases.
Here is the code if anyone wants to try, with a caveat that I only tested it on Windows (check the #if LINUX
conditional for the get_time
definition and implement it if needed, taken from this answer).
#include <stdio.h>
#if LINUX
#include <sys/time.h>
#include <sys/resource.h>
double get_time()
{
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec*1e-6;
}
#else
#include <windows.h>
double get_time()
{
LARGE_INTEGER t, f;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&f);
return (double)t.QuadPart / (double)f.QuadPart * 1000.0;
}
#endif
#define NUM_ITERATIONS (1000 * 1000 * 1000)
// using a macro to avoid function call overhead
#define Benchmark(accumulator, name, operation) { \
double startTime = get_time(); \
double dummySum = 0.0, elapsed; \
int x; \
for (x = 0; x < NUM_ITERATIONS; x++) { \
if (operation) dummySum += x; \
} \
elapsed = get_time() - startTime; \
accumulator += elapsed; \
if (dummySum > 2000) \
printf("[Test: %-12s] %0.2f ms\r\n", name, elapsed); \
}
void DumpAverage(char *test, double totalTime, double reference)
{
printf("[Test: %-12s] AVERAGE TIME: %0.2f ms (Relative diff.: %+6.3f%%)\r\n",
test, totalTime, (totalTime - reference) / reference * 100.0);
}
int main(void)
{
int repeats = 20;
double runningTimes[3] = { 0 };
int k;
for (k = 0; k < repeats; k++) {
printf("Run %d of %d...\r\n", k + 1, repeats);
Benchmark(runningTimes[0], "Plain mod 2", (x % 2));
Benchmark(runningTimes[1], "Bitwise or", (0xFFFFFFFF == (x | 0xFFFFFFFE)));
Benchmark(runningTimes[2], "Bitwise and", (x & 1));
}
{
double reference = runningTimes[0] / repeats;
printf("\r\n");
DumpAverage("Plain mod 2", runningTimes[0] / repeats, reference);
DumpAverage("Bitwise or", runningTimes[1] / repeats, reference);
DumpAverage("Bitwise and", runningTimes[2] / repeats, reference);
}
getchar();
return 0;
}
MATLAB, Filling in the area between two sets of data, lines in one figure
You want to look at the patch() function, and sneak in points for the start and end of the horizontal line:
x = 0:.1:2*pi;
y = sin(x)+rand(size(x))/2;
x2 = [0 x 2*pi];
y2 = [.1 y .1];
patch(x2, y2, [.8 .8 .1]);
If you only want the filled in area for a part of the data, you'll need to truncate the x and y vectors to only include the points you need.
Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit
see NSURLError.h Define
NSURLErrorUnknown = -1,
NSURLErrorCancelled = -999,
NSURLErrorBadURL = -1000,
NSURLErrorTimedOut = -1001,
NSURLErrorUnsupportedURL = -1002,
NSURLErrorCannotFindHost = -1003,
NSURLErrorCannotConnectToHost = -1004,
NSURLErrorNetworkConnectionLost = -1005,
NSURLErrorDNSLookupFailed = -1006,
NSURLErrorHTTPTooManyRedirects = -1007,
NSURLErrorResourceUnavailable = -1008,
NSURLErrorNotConnectedToInternet = -1009,
NSURLErrorRedirectToNonExistentLocation = -1010,
NSURLErrorBadServerResponse = -1011,
NSURLErrorUserCancelledAuthentication = -1012,
NSURLErrorUserAuthenticationRequired = -1013,
NSURLErrorZeroByteResource = -1014,
NSURLErrorCannotDecodeRawData = -1015,
NSURLErrorCannotDecodeContentData = -1016,
NSURLErrorCannotParseResponse = -1017,
NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
NSURLErrorFileDoesNotExist = -1100,
NSURLErrorFileIsDirectory = -1101,
NSURLErrorNoPermissionsToReadFile = -1102,
NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) = -1103,
// SSL errors
NSURLErrorSecureConnectionFailed = -1200,
NSURLErrorServerCertificateHasBadDate = -1201,
NSURLErrorServerCertificateUntrusted = -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid = -1204,
NSURLErrorClientCertificateRejected = -1205,
NSURLErrorClientCertificateRequired = -1206,
NSURLErrorCannotLoadFromNetwork = -2000,
// Download and file I/O errors
NSURLErrorCannotCreateFile = -3000,
NSURLErrorCannotOpenFile = -3001,
NSURLErrorCannotCloseFile = -3002,
NSURLErrorCannotWriteToFile = -3003,
NSURLErrorCannotRemoveFile = -3004,
NSURLErrorCannotMoveFile = -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete =-3007,
NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) = -1018,
NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) = -1019,
NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) = -1020,
NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) = -1021,
NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,
Error in data frame undefined columns selected
Are you meaning?
data2 <- data1[good,]
With
data1[good]
you're selecting columns in a wrong way (using a logical vector of complete rows).
Consider that parameter pollutant
is not used; is it a column name that you want to extract? if so it should be something like
data2 <- data1[good, pollutant]
Furthermore consider that you have to rbind
the data.frame
s inside the for
loop, otherwise you get only the last data.frame (its completed.cases)
And last but not least, i'd prefer generating filenames eg with
id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")
A little modified chunk of ?sprintf
The string fmt
(in our case "%3d"
) contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through ...
. The allowed conversion specifications start with a %
and end with one of the letters in the set aAdifeEgGosxX%
. These letters denote the following types:
Eg a more general example
sprintf("I am %10d years old", 25)
[1] "I am 25 years old"
^^^^^^^^^^
| |
1 10
Waiting until the task finishes
Swift 5 version of the solution
func myCriticalFunction() {
var value1: String?
var value2: String?
let group = DispatchGroup()
group.enter()
//async operation 1
DispatchQueue.global(qos: .default).async {
// Network calls or some other async task
value1 = //out of async task
group.leave()
}
group.enter()
//async operation 2
DispatchQueue.global(qos: .default).async {
// Network calls or some other async task
value2 = //out of async task
group.leave()
}
group.wait()
print("Value1 \(value1) , Value2 \(value2)")
}
CodeIgniter - How to return Json response from controller
For CodeIgniter 4
, you can use the built-in API Response Trait
Here's sample code for reference:
<?php namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
class Home extends BaseController
{
use ResponseTrait;
public function index()
{
$data = [
'data' => 'value1',
'data2' => 'value2',
];
return $this->respond($data);
}
}
Using setDate in PreparedStatement
If you want to add the current date into the database, I would avoid calculating the date in Java to begin with. Determining "now" on the Java (client) side leads to possible inconsistencies in the database if the client side is mis-configured, has the wrong time, wrong timezone, etc. Instead, the date can be set on the server side in a manner such as the following:
requestSQL = "INSERT INTO CREDIT_REQ_TITLE_ORDER (" +
"REQUEST_ID, ORDER_DT, FOLLOWUP_DT) " +
"VALUES(?, SYSDATE, SYSDATE + 30)";
...
prs.setInt(1, new Integer(requestID));
This way, only one bind parameter is required and the dates are calculated on the server side will be consistent. Even better would be to add an insert trigger to CREDIT_REQ_TITLE_ORDER
and have the trigger insert the dates. That can help enforce consistency between different client apps (for example, someone trying to do a fix via sqlplus.
How do I change the number of open files limit in Linux?
1) Add the following line to /etc/security/limits.conf
webuser hard nofile 64000
then login as webuser
su - webuser
2) Edit following two files for webuser
append .bashrc and .bash_profile file by running
echo "ulimit -n 64000" >> .bashrc ; echo "ulimit -n 64000" >> .bash_profile
3) Log out, then log back in and verify that the changes have been made correctly:
$ ulimit -a | grep open
open files (-n) 64000
Thats it and them boom, boom boom.
How to get the anchor from the URL using jQuery?
For current window, you can use this:
var hash = window.location.hash.substr(1);
To get the hash value of the main window, use this:
var hash = window.top.location.hash.substr(1);
If you have a string with an URL/hash, the easiest method is:
var url = 'https://www.stackoverflow.com/questions/123/abc#10076097';
var hash = url.split('#').pop();
If you're using jQuery, use this:
var hash = $(location).attr('hash');
Attributes / member variables in interfaces?
Something important has been said by Tom:
if you use the has-a concept, you avoid the issue.
Indeed, if instead of using extends and implements you define two attributes, one of type rectangle, one of type JLabel
in your Tile
class, then you can define a Rectangle
to be either an interface or a class.
Furthermore, I would normally encourage the use of interfaces in connection with has-a, but I guess it would be an overkill in your situation. However, you are the only one that can decide on this point (tradeoff flexibility/over-engineering).
Force Internet Explorer to use a specific Java Runtime Environment install?
For the server-side solution (which your question was originally ambiguous about), this page at sun lists one way to specify a JRE. Specifically,
<OBJECT
classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
width="200" height="200">
<PARAM name="code" value="Applet1.class">
</OBJECT>
The classid attribute identifies which
version of Java Plug-in to use.
Following is an alternative form of
the classid attribute:
classid="clsid:CAFEEFAC-xxxx-yyyy-zzzz-ABCDEFFEDCBA"
In this form, "xxxx", "yyyy", and
"zzzz" are four-digit numbers that
identify the specific version of Java
Plug-in to be used.
For example, to use Java Plug-in
version 1.5.0, you specify:
classid="clsid:CAFEEFAC-0015-0000-0000-ABCDEFFEDCBA"
How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running
There are two ways to achieve that:
- Use
-rpath
linker option:
gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX -Wl,-rpath=/home/user/.usr/lib
This will work even for a pre-generated binaries, so you can for example download some packages from the debian.org, unpack the binaries and shared libraries into your home directory, and launch them without recompiling.
For a quick test, you can also do (in bash at least):
LD_LIBRARY_PATH=/home/user/.usr/lib ./xxx.out
which has the advantage of not changing your library path for everything else.
c# replace \" characters
Where do these characters occur? Do you see them if you examine the XML data in, say, notepad? Or do you see them when examining the XML data in the debugger. If it is the latter, they are only escape characters for the "
characters, and so part of the actual XML data.
Keep a line of text as a single line - wrap the whole line or none at all
You can use white-space: nowrap;
to define this behaviour:
// HTML:
_x000D_
_x000D_
.nowrap {_x000D_
white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
<span class="nowrap">How do I wrap this line of text</span>_x000D_
<span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
</p>
_x000D_
_x000D_
_x000D_
// CSS:
.nowrap {
white-space: nowrap ;
}
Oracle Add 1 hour in SQL
To add/subtract from a DATE
, you have 2 options :
Method #1 :
The easiest way is to use +
and -
to add/subtract days, hours, minutes, seconds, etc.. from a DATE
, and ADD_MONTHS()
function to add/subtract months and years from a DATE
. Why ? That's because from days, you can get hours and any smaller unit (1 hour = 1/24 days), (1 minute = 1/1440 days), etc... But you cannot get months and years, as that depends on the month and year themselves, hence ADD_MONTHS()
and no add_years(), because from months, you can get years (1 year = 12 months).
Let's try them :
SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints current date: 19-OCT-2019 20:42:02
SELECT TO_CHAR((SYSDATE + 1/24), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 hour: 19-OCT-2019 21:42:02
SELECT TO_CHAR((SYSDATE + 1/1440), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 minute: 19-OCT-2019 20:43:02
SELECT TO_CHAR((SYSDATE + 1/86400), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 second: 19-OCT-2019 20:42:03
-- Same goes for subtraction.
SELECT SYSDATE FROM dual; -- prints current date: 19-OCT-19
SELECT ADD_MONTHS(SYSDATE, 1) FROM dual; -- prints date + 1 month: 19-NOV-19
SELECT ADD_MONTHS(SYSDATE, 12) FROM dual; -- prints date + 1 year: 19-OCT-20
SELECT ADD_MONTHS(SYSDATE, -3) FROM dual; -- prints date - 3 months: 19-JUL-19
Method #2 : Using INTERVAL
s, you can or subtract an interval (duration) from a date easily. More than that, you can combine to add or subtract multiple units at once (e.g 5 hours and 6 minutes, etc..)
Examples :
SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints current date: 19-OCT-2019 21:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' HOUR), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 hour: 19-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' MINUTE), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 minute: 19-OCT-2019 21:35:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' SECOND), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 second: 19-OCT-2019 21:34:16
SELECT TO_CHAR((SYSDATE + INTERVAL '01:05:00' HOUR TO SECOND), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 hour and 5 minutes: 19-OCT-2019 22:39:15
SELECT TO_CHAR((SYSDATE + INTERVAL '3 01' DAY TO HOUR), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 3 days and 1 hour: 22-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE - INTERVAL '10-3' YEAR TO MONTH), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date - 10 years and 3 months: 19-JUL-2009 21:34:15
CSS z-index not working (position absolute)
How about this?
http://jsfiddle.net/P7c9q/4/
<div class="relative">
<div class="yellow-div"></div>
<div class="yellow-div"></div>
<div class="absolute"></div>
</div>
.relative{
position:relative;
}
.absolute {
position:absolute;
width: 40px;
height: 100px;
background: #000;
z-index: 1;
top:30px;
left:0px;
}
.yellow-div {
position:relative;
width: 200px;
height: 50px;
background: yellow;
margin-bottom:4px;
z-index:0;
}
use the relative div as wrapper and let the yellow div's have normal positioning.
Only the black block need to have an absolute position then.
Java 8 Lambda filter by Lists
Look this:
List<Client> result = clients
.stream()
.filter(c ->
(users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
.collect(Collectors.toList());
What is the use of a cursor in SQL Server?
cursor are used because in sub query we can fetch record row by row
so we use cursor to fetch records
Example of cursor:
DECLARE @eName varchar(50), @job varchar(50)
DECLARE MynewCursor CURSOR -- Declare cursor name
FOR
Select eName, job FROM emp where deptno =10
OPEN MynewCursor -- open the cursor
FETCH NEXT FROM MynewCursor
INTO @eName, @job
PRINT @eName + ' ' + @job -- print the name
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM MynewCursor
INTO @ename, @job
PRINT @eName +' ' + @job -- print the name
END
CLOSE MynewCursor
DEALLOCATE MynewCursor
OUTPUT:
ROHIT PRG
jayesh PRG
Rocky prg
Rocky prg
Can't draw Histogram, 'x' must be numeric
Note that you could as well plot directly from ce
(after the comma removing) using the column name :
hist(ce$Weight)
(As opposed to using hist(ce[1])
, which would lead to the same "must be numeric" error.)
This also works for a database query result.
SQL statement to select all rows from previous day
To get the "today" value in SQL:
convert(date, GETDATE())
To get "yesterday":
DATEADD(day, -1, convert(date, GETDATE()))
To get "today minus X days": change the -1 into -X.
So for all yesterday's rows, you get:
select * from tablename
where date >= DATEADD(day, -1, convert(date, GETDATE()))
and date < convert(date, GETDATE())
Working with select using AngularJS's ng-options
One thing to note is that ngModel is required for ngOptions to work... note the ng-model="blah"
which is saying "set $scope.blah to the selected value".
Try this:
<select ng-model="blah" ng-options="item.ID as item.Title for item in items"></select>
Here's more from AngularJS's documentation (if you haven't seen it):
for array data sources:
- label for value in array
- select as label for value in array
- label group by group for value in array
= select as label group by group for value in array
for object data sources:
- label for (key , value) in object
- select as label for (key , value) in object
- label group by group for (key, value) in object
- select as label group by group for (key, value) in object
For some clarification on option tag values in AngularJS:
When you use ng-options
, the values of option tags written out by ng-options will always be the index of the array item the option tag relates to. This is because AngularJS actually allows you to select entire objects with select controls, and not just primitive types. For example:
app.controller('MainCtrl', function($scope) {
$scope.items = [
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' },
{ id: 3, name: 'blah' }
];
});
<div ng-controller="MainCtrl">
<select ng-model="selectedItem" ng-options="item as item.name for item in items"></select>
<pre>{{selectedItem | json}}</pre>
</div>
The above will allow you to select an entire object into $scope.selectedItem
directly. The point is, with AngularJS, you don't need to worry about what's in your option tag. Let AngularJS handle that; you should only care about what's in your model in your scope.
Here is a plunker demonstrating the behavior above, and showing the HTML written out
Dealing with the default option:
There are a few things I've failed to mention above relating to the default option.
Selecting the first option and removing the empty option:
You can do this by adding a simple ng-init
that sets the model (from ng-model
) to the first element in the items your repeating in ng-options
:
<select ng-init="foo = foo || items[0]" ng-model="foo" ng-options="item as item.name for item in items"></select>
Note: This could get a little crazy if foo
happens to be initialized properly to something "falsy". In that case, you'll want to handle the initialization of foo
in your controller, most likely.
Customizing the default option:
This is a little different; here all you need to do is add an option tag as a child of your select, with an empty value attribute, then customize its inner text:
<select ng-model="foo" ng-options="item as item.name for item in items">
<option value="">Nothing selected</option>
</select>
Note: In this case the "empty" option will stay there even after you select a different option. This isn't the case for the default behavior of selects under AngularJS.
A customized default option that hides after a selection is made:
If you wanted your customized default option to go away after you select a value, you can add an ng-hide attribute to your default option:
<select ng-model="foo" ng-options="item as item.name for item in items">
<option value="" ng-if="foo">Select something to remove me.</option>
</select>
J2ME/Android/BlackBerry - driving directions, route between two locations
J2ME Map Route Provider
maps.google.com has a navigation service which can provide you route information in KML format.
To get kml file we need to form url with start and destination locations:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon) {// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
Next you will need to parse xml (implemented with SAXParser) and fill data structures:
public class Point {
String mName;
String mDescription;
String mIconUrl;
double mLatitude;
double mLongitude;
}
public class Road {
public String mName;
public String mDescription;
public int mColor;
public int mWidth;
public double[][] mRoute = new double[][] {};
public Point[] mPoints = new Point[] {};
}
Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon)
then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:
public static Road getRoute(InputStream is)
Full source code RoadProvider.java
BlackBerry
class MapPathScreen extends MainScreen {
MapControl map;
Road mRoad = new Road();
public MapPathScreen() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
map = new MapControl();
add(new LabelField(mRoad.mName));
add(new LabelField(mRoad.mDescription));
add(map);
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
map.drawPath(mRoad);
}
}
private InputStream getConnection(String url) {
HttpConnection urlConnection = null;
InputStream is = null;
try {
urlConnection = (HttpConnection) Connector.open(url);
urlConnection.setRequestMethod("GET");
is = urlConnection.openInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
See full code on J2MEMapRouteBlackBerryEx on Google Code
Android
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
new Thread() {
@Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
See full code on J2MEMapRouteAndroidEx on Google Code
What is the best way to use a HashMap in C++?
Evidence that std::unordered_map
uses a hash map in GCC stdlibc++ 6.4
This was mentioned at: https://stackoverflow.com/a/3578247/895245 but in the following answer: What data structure is inside std::map in C++? I have given further evidence of such for the GCC stdlibc++ 6.4 implementation by:
- GDB step debugging into the class
- performance characteristic analysis
Here is a preview of the performance characteristic graph described in that answer:
How to use a custom class and hash function with unordered_map
This answer nails it: C++ unordered_map using a custom class type as the key
Excerpt: equality:
struct Key
{
std::string first;
std::string second;
int third;
bool operator==(const Key &other) const
{ return (first == other.first
&& second == other.second
&& third == other.third);
}
};
Hash function:
namespace std {
template <>
struct hash<Key>
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
}
Removing the remembered login and password list in SQL Server Management Studio
In my scenario I only wanted to remove a specific username/password from the list which had many other saved connections I didn't want to forget. It turns out the SqlStudio.bin
file others are discussing here is a .NET binary serialization of the Microsoft.SqlServer.Management.UserSettings.SqlStudio
class, which can be deserialized, modified and reserialized to modify specific settings.
To accomplish removal of the specific login, I created a new C# .Net 4.6.1 console application and added a reference to the namespace which is located in the following dll: C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\Microsoft.SqlServer.Management.UserSettings.dll
(your path may differ slightly depending on SSMS version)
From there I could easily create and modify the settings as desired:
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.SqlServer.Management.UserSettings;
class Program
{
static void Main(string[] args)
{
var settingsFile = new FileInfo(@"C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\13.0\SqlStudio.bin");
// Backup our original file just in case...
File.Copy(settingsFile.FullName, settingsFile.FullName + ".backup");
BinaryFormatter fmt = new BinaryFormatter();
SqlStudio settings = null;
using(var fs = settingsFile.Open(FileMode.Open))
{
settings = (SqlStudio)fmt.Deserialize(fs);
}
// The structure of server types / servers / connections requires us to loop
// through multiple nested collections to find the connection to be removed.
// We start here with the server types
var serverTypes = settings.SSMS.ConnectionOptions.ServerTypes;
foreach (var serverType in serverTypes)
{
foreach (var server in serverType.Value.Servers)
{
// Will store the connection for the provided server which should be removed
ServerConnectionSettings removeConn = null;
foreach (var conn in server.Connections)
{
if (conn.UserName == "adminUserThatShouldBeRemoved")
{
removeConn = conn;
break;
}
}
if (removeConn != null)
{
server.Connections.RemoveItem(removeConn);
}
}
}
using (var fs = settingsFile.Open(FileMode.Create))
{
fmt.Serialize(fs, settings);
}
}
}
What is the bit size of long on 64-bit Windows?
The easiest way to get to know it for your compiler/platform:
#include <iostream>
int main() {
std::cout << sizeof(long)*8 << std::endl;
}
Themultiplication by 8 is to get bits from bytes.
When you need a particular size, it is often easiest to use one of the predefined types of a library. If that is undesirable, you can do what often happens with autoconf software and have the configuration system determine the right type for the needed size.
Implement a loading indicator for a jQuery AJAX call
This is how I realised the loading indicator by an Glyphicon:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/bootstrap.min.js"></script>
<style>
.gly-ani {
animation: ani 2s infinite linear;
}
@keyframes ani {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(359deg);
}
}
</style>
</head>
<body>
<div class="container">
<span class="glyphicon glyphicon-refresh gly-ani" style="font-size:40px;"></span>
</div>
</body>
</html>
Escape a string for a sed replace pattern
It's a bit late to respond... but there IS a much simpler way to do this. Just change the delimiter (i.e., the character that separates fields). So, instead of s/foo/bar/
you write s|bar|foo
.
And, here's the easy way to do this:
sed 's|/\*!50017 DEFINER=`snafu`@`localhost`\*/||g'
The resulting output is devoid of that nasty DEFINER clause.
How can I get input radio elements to horizontally align?
This also works like a charm
_x000D_
_x000D_
<form>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio" checked>Option 1_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 2_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 3_x000D_
</label>_x000D_
</form>
_x000D_
_x000D_
_x000D_
How to use PrintWriter and File classes in Java?
You should have a clear idea of exceptions in java.
In java there are checked exceptions and unchecked exceptions.
Checked exceptions are checked (not thrown,just checked) by the compiler at Compile time for the smooth execution of the program at run time.
NOTE: And in our program if their is a chance that a checked exception will rise, then we should handle that checked exception either by try catch or by throws key word.Otherwise we will get a compile time Error:
CE:Unexpected Exception java.io.FileNotFoundException;must be caught or declared to be thrown.
How to resolve:
1.Put your code in try catch block:
2.use throws keyword as shown by other guys above.
Advice:Read more about Exceptions.(I personally love this topic)
How to convert dataframe into time series?
Input. We will start with the text of the input shown in the question since the question did not provide the csv input:
Lines <- "Dates Bajaj_close Hero_close
3/14/2013 1854.8 1669.1
3/15/2013 1850.3 1684.45
3/18/2013 1812.1 1690.5
3/19/2013 1835.9 1645.6
3/20/2013 1840 1651.15
3/21/2013 1755.3 1623.3
3/22/2013 1820.65 1659.6
3/25/2013 1802.5 1617.7
3/26/2013 1801.25 1571.85
3/28/2013 1799.55 1542"
zoo. "ts"
class series normally do not represent date indexes but we can create a zoo series that does (see zoo package):
library(zoo)
z <- read.zoo(text = Lines, header = TRUE, format = "%m/%d/%Y")
Alternately, if you have already read this into a data frame DF
then it could be converted to zoo as shown on the second line below:
DF <- read.table(text = Lines, header = TRUE)
z <- read.zoo(DF, format = "%m/%d/%Y")
In either case above z
ia a zoo series with a "Date"
class time index. One could also create the zoo series, zz
, which uses 1, 2, 3, ... as the time index:
zz <- z
time(zz) <- seq_along(time(zz))
ts. Either of these could be converted to a "ts"
class series:
as.ts(z)
as.ts(zz)
The first has a time index which is the number of days since the Epoch (January 1, 1970) and will have NAs for missing days and the second will have 1, 2, 3, ... as the time index and no NAs.
Monthly series. Typically "ts"
series are used for monthly, quarterly or yearly series. Thus if we were to aggregate the input into months we could reasonably represent it as a "ts"
series:
z.m <- as.zooreg(aggregate(z, as.yearmon, mean), freq = 12)
as.ts(z.m)
CSS media query to target only iOS devices
As mentioned above, the short answer is no. But I'm in need of something similar in the app I'm working on now, yet the areas where the CSS needs to be different are limited to very specific areas of a page.
If you're like me and don't need to serve up an entirely different stylesheet, another option would be to detect a device running iOS in the way described in this question's selected answer: Detect if device is iOS
Once you've detected the iOS device you could add a class to the area you're targeting using Javascript (eg. the document.getElementsByTagName("yourElementHere")[0].setAttribute("class", "iOS-device");
, jQuery, PHP or whatever, and style that class accordingly using the pre-existing stylesheet.
.iOS-device {
style-you-want-to-set: yada;
}
Is multiplication and division using shift operators in C actually faster?
It completely depends on target device, language, purpose, etc.
Pixel crunching in a video card driver? Very likely, yes!
.NET business application for your department? Absolutely no reason to even look into it.
For a high performance game for a mobile device it might be worth looking into, but only after easier optimizations have been performed.
How do I update pip itself from inside my virtual environment?
for windows,
- go to command prompt
- and use this command
python -m pip install –upgrade pip
- Dont forget to restart the editor,to avoid any error
- you can check the version of the
pip
by
pip --version
- if you want to install any particular version of
pip
, for example version 18.1
then use this command,
python -m pip install pip==18.1
How to simulate browsing from various locations?
It depends on wether the locatoin is detected by different DNS resolution from different locations, or by IP address that you are browsing from.
If its by DNS, you could just modify your hosts file to point at the server used in europe. Get your friend to ping the address, to see if its different from the one yours resolves to.
To browse from a different IP address:
You can rent a VPS server. You can use putty / SSH to act as a proxy. I use this from time to time to brows from the US using a VPS server I rent in the US.
Having an account on a remote host may or may not be enough. Sadly, my dreamhost account, even though I have ssh access, does not allow proxying.
Formatting floats in a numpy array
You're confusing actual precision and display precision. Decimal rounding cannot be represented exactly in binary. You should try:
> np.set_printoptions(precision=2)
> np.array([5.333333])
array([ 5.33])
Rename a column in MySQL
In mysql your query should be like
ALTER TABLE table_name change column_1 column_2 Data_Type;
you have written the query in Oracle.
JavaScript: Check if mouse button down?
The following snippet will attempt to execute the "doStuff" function 2 seconds after the mouseDown event occurs in document.body. If the user lifts up the button, the mouseUp event will occur and cancel the delayed execution.
I'd advise using some method for cross-browser event attachment - setting the mousedown and mouseup properties explicitly was done to simplify the example.
function doStuff() {
// does something when mouse is down in body for longer than 2 seconds
}
var mousedownTimeout;
document.body.onmousedown = function() {
mousedownTimeout = window.setTimeout(doStuff, 2000);
}
document.body.onmouseup = function() {
window.clearTimeout(mousedownTimeout);
}
Create a user with all privileges in Oracle
My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this
Error in my case
SQL>create view v1 as select * from books where id=10;
insufficient privileges.
Solution
1)open your cmd and change your directory to where you install your oracle database.
in my case i was downloaded in E drive so my location is
E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>
after reaching in the position you have to type sqlplus sys as sysdba
E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
2) Enter password: here you have to type that password that you give at the time of installation of oracle software.
3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.
for creating new user
SQL> create user abc identified by xyz;
here abc is user and xyz is password.
giving all the privileges to abc user
SQL> grant all privileges to abc;
grant succeeded.
if you are seen this message then all the privileges are giving to the abc user.
4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.
In My case
in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
SQL> grant all privileges to SCOTT;
grant succeeded.
Now I can create views.
How do I import an SQL file using the command line in MySQL?
This line import the dump file in local database, under linux.
mysql -u dbuser -p'password including spaces' dbname < path/to/dump_file.sql
This line import the dump file in remote database, under linux. Note: -P
is for the port, and is required if mysql port is different than default.
mysql -h dbhost -u dbuser -p'password including spaces' -P 3306 dbname < path/to/dump_file.sql
Note: the password include spaces and this is the reason of single quotes. Just change path style for using the command under windows (C:\windows\path\dump_file.sql
)
What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?
VALID padding: this is with zero padding. Hope there is no confusion.
x = tf.constant([[1., 2., 3.], [4., 5., 6.],[ 7., 8., 9.], [ 7., 8., 9.]])
x = tf.reshape(x, [1, 4, 3, 1])
valid_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')
print (valid_pad.get_shape()) # output-->(1, 2, 1, 1)
SAME padding: This is kind of tricky to understand in the first place because we have to consider two conditions separately as mentioned in the official docs.
Let's take input as , output as , padding as , stride as and kernel size as (only a single dimension is considered)
Case 01: :
Case 02: :
is calculated such that the minimum value which can be taken for padding. Since value of is known, value of can be found using this formula .
Let's work out this example:
x = tf.constant([[1., 2., 3.], [4., 5., 6.],[ 7., 8., 9.], [ 7., 8., 9.]])
x = tf.reshape(x, [1, 4, 3, 1])
same_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')
print (same_pad.get_shape()) # --> output (1, 2, 2, 1)
Here the dimension of x is (3,4). Then if the horizontal direction is taken (3):
If the vertial direction is taken (4):
Hope this will help to understand how actually SAME padding works in TF.
How to calculate the bounding box for a given lat/lng location?
I was working on the bounding box problem as a side issue to finding all the points within SrcRad radius of a static LAT, LONG point. There have been quite a few calculations that use
maxLon = $lon + rad2deg($rad/$R/cos(deg2rad($lat)));
minLon = $lon - rad2deg($rad/$R/cos(deg2rad($lat)));
to calculate the longitude bounds, but I found this to not give all the answers that were needed. Because what you really want to do is
(SrcRad/RadEarth)/cos(deg2rad(lat))
I know, I know the answer should be the same, but I found that it wasn't. It appeared that by not making sure I was doing the (SRCrad/RadEarth) First and then dividing by the Cos part I was leaving out some location points.
After you get all your bounding box points, if you have a function that calculates the Point to Point Distance given lat, long it is easy to only get those points that are a certain distance radius from the fixed point. Here is what I did.
I know it took a few extra steps but it helped me
-- GLOBAL Constants
gc_pi CONSTANT REAL := 3.14159265359; -- Pi
-- Conversion Factor Constants
gc_rad_to_degs CONSTANT NUMBER := 180/gc_pi; -- Conversion for Radians to Degrees 180/pi
gc_deg_to_rads CONSTANT NUMBER := gc_pi/180; --Conversion of Degrees to Radians
lv_stat_lat -- The static latitude point that I am searching from
lv_stat_long -- The static longitude point that I am searching from
-- Angular radius ratio in radians
lv_ang_radius := lv_search_radius / lv_earth_radius;
lv_bb_maxlat := lv_stat_lat + (gc_rad_to_deg * lv_ang_radius);
lv_bb_minlat := lv_stat_lat - (gc_rad_to_deg * lv_ang_radius);
--Here's the tricky part, accounting for the Longitude getting smaller as we move up the latitiude scale
-- I seperated the parts of the equation to make it easier to debug and understand
-- I may not be a smart man but I know what the right answer is... :-)
lv_int_calc := gc_deg_to_rads * lv_stat_lat;
lv_int_calc := COS(lv_int_calc);
lv_int_calc := lv_ang_radius/lv_int_calc;
lv_int_calc := gc_rad_to_degs*lv_int_calc;
lv_bb_maxlong := lv_stat_long + lv_int_calc;
lv_bb_minlong := lv_stat_long - lv_int_calc;
-- Now select the values from your location datatable
SELECT * FROM (
SELECT cityaliasname, city, state, zipcode, latitude, longitude,
-- The actual distance in miles
spherecos_pnttopntdist(lv_stat_lat, lv_stat_long, latitude, longitude, 'M') as miles_dist
FROM Location_Table
WHERE latitude between lv_bb_minlat AND lv_bb_maxlat
AND longitude between lv_bb_minlong and lv_bb_maxlong)
WHERE miles_dist <= lv_limit_distance_miles
order by miles_dist
;
Is there a portable way to get the current username in Python?
psutil provides a portable way that doesn't use environment variables like the getpass
solution. It is less prone to security issues, and should probably be the accepted answer as of today.
import psutil
def get_username():
return psutil.Process().username()
Under the hood, this combines the getpwuid
based method for unix and the GetTokenInformation
method for Windows.
checking for typeof error in JS
Or use this for different types of errors
function isError(val) {
return (!!val && typeof val === 'object')
&& ((Object.prototype.toString.call(val) === '[object Error]')
|| (typeof val.message === 'string' && typeof val.name === 'string'))
}
REST API error code 500 handling
It is a server error, not a client error. If server errors weren't to be returned to the client, there wouldn't have been created an entire status code class for them (i.e. 5xx).
You can't hide the fact that you either made a programming error or some service you rely on is unavailable, and that certainly isn't the client's fault. Returning any other range of code in those cases than the 5xx series would make no sense.
RFC 7231 mentions in section 6.6. Server Error 5xx:
The 5xx (Server Error) class of status code indicates that the server
is aware that it has erred or is incapable of performing the
requested method.
This is exactly the case. There's nothing "internal" about the code "500 Internal Server Error" in the sense that it shouldn't be exposed to the client.
How to discard uncommitted changes in SourceTree?
Do as follow,
- Click on
commit
- Select all by pressing
CMD+A
that you want to delete or discard
Right click
on the selected uncommitted files that you want to delete
- Select
Remove
from the drop-down list
Javascript date.getYear() returns 111 in 2011?
From what I've read on Mozilla's JS pages, getYear is deprecated. As pointed out many times, getFullYear()
is the way to go. If you're really wanting to use getYear()
add 1900 to it.
var now = new Date(),
year = now.getYear() + 1900;
Bootstrap $('#myModal').modal('show') is not working
use the object to call...
<a href="#" onclick='$("#myModal").modal("show");'>Try This</a>
or if you using ajax to show that modal after get result, this is work for me...
$.ajax({ url: "YourUrl",
type: "POST", data: "x=1&y=2&z=3",
cache: false, success: function(result){
// Your Function here
$("#myModal").modal("show");
}
});
How to drop a list of rows from Pandas dataframe?
In a comment to @theodros-zelleke's answer, @j-jones asked about what to do if the index is not unique. I had to deal with such a situation. What I did was to rename the duplicates in the index before I called drop()
, a la:
dropped_indexes = <determine-indexes-to-drop>
df.index = rename_duplicates(df.index)
df.drop(df.index[dropped_indexes], inplace=True)
where rename_duplicates()
is a function I defined that went through the elements of index and renamed the duplicates. I used the same renaming pattern as pd.read_csv()
uses on columns, i.e., "%s.%d" % (name, count)
, where name
is the name of the row and count
is how many times it has occurred previously.
Compare 2 arrays which returns difference
/** SUBTRACT ARRAYS **/
function subtractarrays(array1, array2){
var difference = [];
for( var i = 0; i < array1.length; i++ ) {
if( $.inArray( array1[i], array2 ) == -1 ) {
difference.push(array1[i]);
}
}
return difference;
}
You can then call the function anywhere in your code.
var I_like = ["love", "sex", "food"];
var she_likes = ["love", "food"];
alert( "what I like and she does't like is: " + subtractarrays( I_like, she_likes ) ); //returns "Naughty"!
This works in all cases and avoids the problems in the methods above. Hope that helps!
How to pretty print nested dictionaries?
I'm just returning to this question after taking sth's answer and making a small but very useful modification. This function prints all keys in the JSON tree as well as the size of leaf nodes in that tree.
def print_JSON_tree(d, indent=0):
for key, value in d.iteritems():
print ' ' * indent + unicode(key),
if isinstance(value, dict):
print; print_JSON_tree(value, indent+1)
else:
print ":", str(type(d[key])).split("'")[1], "-", str(len(unicode(d[key])))
It's really nice when you have large JSON objects and want to figure out where the meat is. Example:
>>> print_JSON_tree(JSON_object)
key1
value1 : int - 5
value2 : str - 16
key2
value1 : str - 34
value2 : list - 5623456
This would tell you that most of the data you care about is probably inside JSON_object['key1']['key2']['value2']
because the length of that value formatted as a string is very large.
How can I write maven build to add resources to classpath?
By default maven does not include any files from "src/main/java".
You have two possible way to that.
put all your resource files (different than java files) to "src/main/resources" - this is highly recommended
Add to your pom (resource plugin):
?
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
Get first element of Series without knowing the index
Use iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
How to override application.properties during production in Spring-Boot?
I have found the following has worked for me:
java -jar my-awesome-java-prog.jar --spring.config.location=file:/path-to-config-dir/
with file:
added.
LATE EDIT
Of course, this command line is never run as it is in production.
Rather I have
- [possibly several layers of]
shell
scripts in source control with place holders for all parts of the command that could change (name of the jar, path to config...)
ansible
deployment scripts that will deploy the shell
scripts and replace the place holders by the actual value.
Is it possible to pass a flag to Gulp to have it run tasks in different ways?
Edit
gulp-util
is deprecated and should be avoid, so it's recommended to use minimist instead, which gulp-util
already used.
So I've changed some lines in my gulpfile to remove gulp-util
:
var argv = require('minimist')(process.argv.slice(2));
gulp.task('styles', function() {
return gulp.src(['src/styles/' + (argv.theme || 'main') + '.scss'])
…
});
Original
In my project I use the following flag:
gulp styles --theme literature
Gulp offers an object gulp.env
for that. It's deprecated in newer versions, so you must use gulp-util for that. The tasks looks like this:
var util = require('gulp-util');
gulp.task('styles', function() {
return gulp.src(['src/styles/' + (util.env.theme ? util.env.theme : 'main') + '.scss'])
.pipe(compass({
config_file: './config.rb',
sass : 'src/styles',
css : 'dist/styles',
style : 'expanded'
}))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'ff 17', 'opera 12.1', 'ios 6', 'android 4'))
.pipe(livereload(server))
.pipe(gulp.dest('dist/styles'))
.pipe(notify({ message: 'Styles task complete' }));
});
The environment setting is available during all subtasks. So I can use this flag on the watch task too:
gulp watch --theme literature
And my styles task also works.
Ciao
Ralf
How To Define a JPA Repository Query with a Join
You are experiencing this issue for two reasons.
- The JPQL Query is not valid.
- You have not created an association between your entities that the underlying JPQL query can utilize.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="iduser")
private Long idUser;
@Column(name="user_name")
private String userName;
@OneToOne()
@JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
@Entity
@Table(name = "area")
public class Area {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="idarea")
private Long idArea;
@Column(name="area_name")
private String areaName;
@OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Certificate has either expired or has been revoked
1.Change the setting of your Mac Timing to Automatic(Open Date& Time Preferences Check on set the Date and Time Automatically).
2.After that go to your X Code, Clean and Run The Code.
3.If it failed, log out of your Apple Profile and Delete all the Automatically Created Provisioning Profiles in XCode -- Preferences and Move all the Provisioning profiles to trash and download as a new file.Then LogIn again and Run your Code.
Error: getaddrinfo ENOTFOUND in nodejs for get call
var http = require('http');
var options = {
host: 'localhost',
port: 80,
path: '/broadcast'
};
var requestLoop = setInterval(function(){
http.get (options, function (resp) {
resp.on('data', function (d) {
console.log ('data!', d.toString());
});
resp.on('end', function (d) {
console.log ('Finished !');
});
}).on('error', function (e) {
console.log ('error:', e);
});
}, 10000);
var dns = require('dns'), cache = {};
dns._lookup = dns.lookup;
dns.lookup = function(domain, family, done) {
if (!done) {
done = family;
family = null;
}
var key = domain+family;
if (key in cache) {
var ip = cache[key],
ipv = ip.indexOf('.') !== -1 ? 4 : 6;
return process.nextTick(function() {
done(null, ip, ipv);
});
}
dns._lookup(domain, family, function(err, ip, ipv) {
if (err) return done(err);
cache[key] = ip;
done(null, ip, ipv);
});
};
// Works fine (100%)
How to find numbers from a string?
Regular expressions are built to parse. While the syntax can take a while to pick up on this approach is very efficient, and is very flexible for handling more complex string extractions/replacements
Sub Tester()
MsgBox CleanString("3d1fgd4g1dg5d9gdg")
End Sub
Function CleanString(strIn As String) As String
Dim objRegex
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Global = True
.Pattern = "[^\d]+"
CleanString = .Replace(strIn, vbNullString)
End With
End Function
PHP - Fatal error: Unsupported operand types
I had a similar error with the following code:-
foreach($myvar as $key => $value){
$query = "SELECT stuff
FROM table
WHERE col1 = '$criteria1'
AND col2 = '$criteria2'";
$result = mysql_query($query) or die('Could not execute query - '.mysql_error(). __FILE__. __LINE__. $query);
$point_values = mysql_fetch_assoc($result);
$top_five_actions[$key] += $point_values; //<--- Problem Line
}
It turned out that my $point_values variable was occasionally returning false which caused the problem so I fixed it by wrapping it in mysql_num_rows check:-
if(mysql_num_rows($result) > 0) {
$point_values = mysql_fetch_assoc($result);
$top_five_actions[$key] += $point_values;
}
Not sure if this helps though?
Cheers
using extern template (C++11)
You should only use extern template
to force the compiler to not instantiate a template when you know that it will be instantiated somewhere else. It is used to reduce compile time and object file size.
For example:
// header.h
template<typename T>
void ReallyBigFunction()
{
// Body
}
// source1.cpp
#include "header.h"
void something1()
{
ReallyBigFunction<int>();
}
// source2.cpp
#include "header.h"
void something2()
{
ReallyBigFunction<int>();
}
This will result in the following object files:
source1.o
void something1()
void ReallyBigFunction<int>() // Compiled first time
source2.o
void something2()
void ReallyBigFunction<int>() // Compiled second time
If both files are linked together, one void ReallyBigFunction<int>()
will be discarded, resulting in wasted compile time and object file size.
To not waste compile time and object file size, there is an extern
keyword which makes the compiler not compile a template function. You should use this if and only if you know it is used in the same binary somewhere else.
Changing source2.cpp
to:
// source2.cpp
#include "header.h"
extern template void ReallyBigFunction<int>();
void something2()
{
ReallyBigFunction<int>();
}
Will result in the following object files:
source1.o
void something1()
void ReallyBigFunction<int>() // compiled just one time
source2.o
void something2()
// No ReallyBigFunction<int> here because of the extern
When both of these will be linked together, the second object file will just use the symbol from the first object file. No need for discard and no wasted compile time and object file size.
This should only be used within a project, like in times when you use a template like vector<int>
multiple times, you should use extern
in all but one source file.
This also applies to classes and function as one, and even template member functions.
How can I consume a WSDL (SOAP) web service in Python?
Right now (as of 2008), all the SOAP libraries available for Python suck. I recommend avoiding SOAP if possible. The last time we where forced to use a SOAP web service from Python, we wrote a wrapper in C# that handled the SOAP on one side and spoke COM out the other.
Opening port 80 EC2 Amazon web services
For those of you using Centos (and perhaps other linux distibutions), you need to make sure that its FW (iptables) allows for port 80 or any other port you want.
See here on how to completely disable it (for testing purposes only!).
And here for specific rules
Phone Number Validation MVC
Model
[Required(ErrorMessage = "You must provide a phone number")]
[Display(Name = "Home Phone")]
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
public string PhoneNumber { get; set; }
View:
@Html.LabelFor(model => model.PhoneNumber)
@Html.EditorFor(model => model.PhoneNumber)
@Html.ValidationMessageFor(model => model.PhoneNumber)
Using wire or reg with input or output in Verilog
An output reg foo
is just shorthand for output foo_wire; reg foo; assign foo_wire = foo
. It's handy when you plan to register that output anyway. I don't think input reg
is meaningful for module
(perhaps task
). input wire
and output wire
are the same as input
and output
: it's just more explicit.
Get exit code of a background process
This is how I solved it when I had a similar need:
# Some function that takes a long time to process
longprocess() {
# Sleep up to 14 seconds
sleep $((RANDOM % 15))
# Randomly exit with 0 or 1
exit $((RANDOM % 2))
}
pids=""
# Run five concurrent processes
for i in {1..5}; do
( longprocess ) &
# store PID of process
pids+=" $!"
done
# Wait for all processes to finish, will take max 14s
# as it waits in order of launch, not order of finishing
for p in $pids; do
if wait $p; then
echo "Process $p success"
else
echo "Process $p fail"
fi
done
Check if certain value is contained in a dataframe column in pandas
You can simply use this:
'07311954' in df.date.values
which returns True
or False
Here is the further explanation:
In pandas, using in
check directly with DataFrame and Series (e.g. val in df
or val in series
) will check whether the val
is contained in the Index.
BUT you can still use in
check for their values too (instead of Index)! Just using val in df.col_name.values
or val in series.values
. In this way, you are actually checking the val
with a Numpy array.
And .isin(vals)
is the other way around, it checks whether the DataFrame/Series values are in the vals
. Here vals
must be set or list-like. So this is not the natural way to go for the question.
How Do I Take a Screen Shot of a UIView?
I created this extension for save a screen shot from UIView
extension UIView {
func saveImageFromView(path path:String) {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
}}
call:
let pathDocuments = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first!
let pathImage = "\(pathDocuments)/\(user!.usuarioID.integerValue).jpg"
reportView.saveImageFromView(path: pathImage)
If you want to create a png must change:
UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
by
UIImagePNGRepresentation(image)?.writeToFile(path, atomically: true)
How to align entire html body to the center?
If I have one thing that I love to share with respect to CSS, it's MY FAVE WAY OF CENTERING THINGS ALONG BOTH AXES!!!
Advantages of this method:
- Full compatibility with browsers that people actually use
- No tables required
- Highly reusable for centering any other elements inside their parent
- Accomodates parents and children with dynamic (changing) dimensions!
I always do this by using 2 classes: One to specify the parent element, whose content will be centered (.centered-wrapper
), and the 2nd one to specify which child of the parent is centered (.centered-content
). This 2nd class is useful in the case where the parent has multiple children, but only 1 needs to be centered).
In this case, body
will be the .centered-wrapper
, and an inner div
will be .centered-content
.
<html>
<head>...</head>
<body class="centered-wrapper">
<div class="centered-content">...</div>
</body>
</html>
The idea for centering will now be to make .centered-content
an inline-block
. This will easily facilitate horizontal centering, through text-align: center;
, and also allows for vertical centering as you shall see.
.centered-wrapper {
position: relative;
text-align: center;
}
.centered-wrapper:before {
content: "";
position: relative;
display: inline-block;
width: 0; height: 100%;
vertical-align: middle;
}
.centered-content {
display: inline-block;
vertical-align: middle;
}
This gives you 2 really reusable classes for centering any child inside of any parent! Just add the .centered-wrapper
and .centered-content
classes.
So, what's up with that :before
element? It facilitates vertical-align: middle;
and is necessary because vertical alignment isn't relative to the height of the parent - vertical alignment is relative to the height of the tallest sibling!!!. Therefore, by ensuring that there is a sibling whose height is the parent's height (100% height, 0 width to make it invisible), we know that vertical alignment will be with respect to the parent's height.
One last thing: You need to ensure that your html
and body
tags are the size of the window so that centering to them is the same as centering to the browser!
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
Fiddle: https://jsfiddle.net/gershy/g121g72a/
CSS Selector that applies to elements with two classes
Chain both class selectors (without a space in between):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar
in this case) instead, regardless of what other classes you list.
To illustrate how other browsers and IE6 interpret this, consider this CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Output on supported browsers is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Not selected, black text [3] -->
Output on IE6 is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Selected, red text [2] -->
Footnotes:
- Supported browsers:
- Not selected as this element only has class
foo
.
- Selected as this element has both classes
foo
and bar
.
- Not selected as this element only has class
bar
.
- IE6:
- Not selected as this element doesn't have class
bar
.
- Selected as this element has class
bar
, regardless of any other classes listed.
How to re-enable right click so that I can inspect HTML elements in Chrome?
I built upon @Chema solution and added resetting pointer-events
and user-select
. If they are set to none
for an image, right-clicking it does not invoke the context menu for the image with options to view or save it.
javascript:function enableContextMenu(aggressive = true) { void(document.ondragstart=null); void(document.onselectstart=null); void(document.onclick=null); void(document.onmousedown=null); void(document.onmouseup=null); void(document.body.oncontextmenu=null); enableRightClickLight(document); if (aggressive) { enableRightClick(document); removeContextMenuOnAll('body'); removeContextMenuOnAll('img'); removeContextMenuOnAll('td'); } } function removeContextMenuOnAll(tagName) { var elements = document.getElementsByTagName(tagName); for (var i = 0; i < elements.length; i++) { enableRightClick(elements[i]); enablePointerEvents(elements[i]); } } function enableRightClickLight(el) { el || (el = document); el.addEventListener('contextmenu', bringBackDefault, true); } function enableRightClick(el) { el || (el = document); el.addEventListener('contextmenu', bringBackDefault, true); el.addEventListener('dragstart', bringBackDefault, true); el.addEventListener('selectstart', bringBackDefault, true); el.addEventListener('click', bringBackDefault, true); el.addEventListener('mousedown', bringBackDefault, true); el.addEventListener('mouseup', bringBackDefault, true); } function restoreRightClick(el) { el || (el = document); el.removeEventListener('contextmenu', bringBackDefault, true); el.removeEventListener('dragstart', bringBackDefault, true); el.removeEventListener('selectstart', bringBackDefault, true); el.removeEventListener('click', bringBackDefault, true); el.removeEventListener('mousedown', bringBackDefault, true); el.removeEventListener('mouseup', bringBackDefault, true); } function bringBackDefault(event) { event.returnValue = true; (typeof event.stopPropagation === 'function') && event.stopPropagation(); (typeof event.cancelBubble === 'function') && event.cancelBubble(); } function enablePointerEvents(el) { if (!el) return; el.style.pointerEvents='auto'; el.style.webkitTouchCallout='default'; el.style.webkitUserSelect='auto'; el.style.MozUserSelect='auto'; el.style.msUserSelect='auto'; el.style.userSelect='auto'; enablePointerEvents(el.parentElement); } enableContextMenu();
Get index of element as child relative to parent
There's no need to require a big library like jQuery to accomplish this, if you don't want to. To achieve this with built-in DOM manipulation, get a collection of the li
siblings in an array, and on click, check the indexOf
the clicked element in that array.
_x000D_
_x000D_
const lis = [...document.querySelectorAll('#wizard > li')];_x000D_
lis.forEach((li) => {_x000D_
li.addEventListener('click', () => {_x000D_
const index = lis.indexOf(li);_x000D_
console.log(index);_x000D_
});_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_
Or, with event delegation:
_x000D_
_x000D_
const lis = [...document.querySelectorAll('#wizard li')];_x000D_
document.querySelector('#wizard').addEventListener('click', ({ target }) => {_x000D_
// Make sure the clicked element is a <li> which is a child of wizard:_x000D_
if (!target.matches('#wizard > li')) return;_x000D_
_x000D_
const index = lis.indexOf(target);_x000D_
console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_
Or, if the child elements may change dynamically (like with a todo list), then you'll have to construct the array of li
s on every click, rather than beforehand:
_x000D_
_x000D_
const wizard = document.querySelector('#wizard');_x000D_
wizard.addEventListener('click', ({ target }) => {_x000D_
// Make sure the clicked element is a <li>_x000D_
if (!target.matches('li')) return;_x000D_
_x000D_
const lis = [...wizard.children];_x000D_
const index = lis.indexOf(target);_x000D_
console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_
I get Access Forbidden (Error 403) when setting up new alias
If you have installed a module on Xampp (on Linux) via Bitnami and changed chown
settings, make sure that the /opt/lampp/apps/<app>/htdocs
and tmp
usergroup is daemon
with all other sibling files and folders chown
ed to the user you installed as, e.g. cd /opt/lampp/apps/<app>
, sudo chown -R root:root .
, followed by sudo chown -R root:daemon htdocs tmp
.
Closing Twitter Bootstrap Modal From Angular Controller
Here's a reusable Angular directive that will hide and show a Bootstrap modal.
app.directive("modalShow", function () {
return {
restrict: "A",
scope: {
modalVisible: "="
},
link: function (scope, element, attrs) {
//Hide or show the modal
scope.showModal = function (visible) {
if (visible)
{
element.modal("show");
}
else
{
element.modal("hide");
}
}
//Check to see if the modal-visible attribute exists
if (!attrs.modalVisible)
{
//The attribute isn't defined, show the modal by default
scope.showModal(true);
}
else
{
//Watch for changes to the modal-visible attribute
scope.$watch("modalVisible", function (newValue, oldValue) {
scope.showModal(newValue);
});
//Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
element.bind("hide.bs.modal", function () {
scope.modalVisible = false;
if (!scope.$$phase && !scope.$root.$$phase)
scope.$apply();
});
}
}
};
});
Usage Example #1 - this assumes you want to show the modal - you could add ng-if as a condition
<div modal-show class="modal fade"> ...bootstrap modal... </div>
Usage Example #2 - this uses an Angular expression in the modal-visible attribute
<div modal-show modal-visible="showDialog" class="modal fade"> ...bootstrap modal... </div>
Another Example - to demo the controller interaction, you could add something like this to your controller and it will show the modal after 2 seconds and then hide it after 5 seconds.
$scope.showDialog = false;
$timeout(function () { $scope.showDialog = true; }, 2000)
$timeout(function () { $scope.showDialog = false; }, 5000)
I'm late to contribute to this question - created this directive for another question here. Simple Angular Directive for Bootstrap Modal
Hope this helps.
How to create an array containing 1...N
You can use this:
new Array(/*any number which you want*/)
.join().split(',')
.map(function(item, index){ return ++index;})
for example
new Array(10)
.join().split(',')
.map(function(item, index){ return ++index;})
will create following array:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Zero-pad digits in string
First of all, your description is misleading. Double
is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:
$s = sprintf('%02d', $digit);
For more information, refer to the documentation of sprintf
.
jquery - fastest way to remove all rows from a very large table
if you want to remove only fast.. you can do like below..
$( "#tableId tbody tr" ).each( function(){
this.parentNode.removeChild( this );
});
but, there can be some event-binded elements in table,
in that case,
above code is not prevent memory leak in IE... T-T and
not fast in FF...
sorry....
How to find all occurrences of an element in a list
Here is a time performance comparison between using np.where
vs list_comprehension
. Seems like np.where
is faster on average.
# np.where
start_times = []
end_times = []
for i in range(10000):
start = time.time()
start_times.append(start)
temp_list = np.array([1,2,3,3,5])
ixs = np.where(temp_list==3)[0].tolist()
end = time.time()
end_times.append(end)
print("Took on average {} seconds".format(
np.mean(end_times)-np.mean(start_times)))
Took on average 3.81469726562e-06 seconds
# list_comprehension
start_times = []
end_times = []
for i in range(10000):
start = time.time()
start_times.append(start)
temp_list = np.array([1,2,3,3,5])
ixs = [i for i in range(len(temp_list)) if temp_list[i]==3]
end = time.time()
end_times.append(end)
print("Took on average {} seconds".format(
np.mean(end_times)-np.mean(start_times)))
Took on average 4.05311584473e-06 seconds
Fragment onCreateView and onActivityCreated called twice
It looks to me like it's because you are instantiating your TabListener every time... so the system is recreating your fragment from the savedInstanceState and then you are doing it again in your onCreate.
You should wrap that in a if(savedInstanceState == null)
so it only fires if there is no savedInstanceState.
Anaconda site-packages
You could also type 'conda list' in a command line. This will print out the installed modules with the version numbers. The path within your file structure will be printed at the top of this list.
Why does sudo change the PATH?
PATH
is an environment variable, and as such is by default reset by sudo.
You need special permissions to be permitted to do this.
From man sudo
-E The -E (preserve environment) option will override the env_reset
option in sudoers(5)). It is only available when either the match-
ing command has the SETENV tag or the setenv option is set in sudo-
ers(5).
Environment variables to be set for the command may also be passed on
the command line in the form of VAR=value, e.g.
LD_LIBRARY_PATH=/usr/local/pkg/lib. Variables passed on the command
line are subject to the same restrictions as normal environment vari-
ables with one important exception. If the setenv option is set in
sudoers, the command to be run has the SETENV tag set or the command
matched is ALL, the user may set variables that would overwise be for-
bidden. See sudoers(5) for more information.
An Example of usage:
cat >> test.sh
env | grep "MYEXAMPLE" ;
^D
sh test.sh
MYEXAMPLE=1 sh test.sh
# MYEXAMPLE=1
MYEXAMPLE=1 sudo sh test.sh
MYEXAMPLE=1 sudo MYEXAMPLE=2 sh test.sh
# MYEXAMPLE=2
update
man 5 sudoers :
env_reset If set, sudo will reset the environment to only contain
the LOGNAME, SHELL, USER, USERNAME and the SUDO_* vari-
ables. Any variables in the caller's environment that
match the env_keep and env_check lists are then added.
The default contents of the env_keep and env_check
lists are displayed when sudo is run by root with the
-V option. If sudo was compiled with the SECURE_PATH
option, its value will be used for the PATH environment
variable. This flag is on by default.
So may need to check that this is/is not compiled in.
It is by default in Gentoo
# ( From the build Script )
....
ROOTPATH=$(cleanpath /bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/opt/bin${ROOTPATH:+:${ROOTPATH}})
....
econf --with-secure-path="${ROOTPATH}"
warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777
I had the same error here MacOSX 10.11 - it seems ruby checks to see if any directory (including the parents) in the path are world writable. In my case there wasn't a /usr/local/bin present as nothing had created it.
Run this command in your terminal.Try this
sudo chmod 775 /usr/local
After this if you have any password on your mac , then you have to enter the password . Now this issue will be fix.
How can foreign key constraints be temporarily disabled using T-SQL?
Find the constraint
SELECT *
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('TABLE_NAME')
Execute the SQL generated by this SQL
SELECT
'ALTER TABLE ' + OBJECT_SCHEMA_NAME(parent_object_id) +
'.[' + OBJECT_NAME(parent_object_id) +
'] DROP CONSTRAINT ' + name
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('TABLE_NAME')
Safeway.
Note: Added solution for droping the constraint so that table can be dropped or modified without any constraint error.
Executing a command stored in a variable from PowerShell
Try invoking your command with Invoke-Expression
:
Invoke-Expression $cmd1
Here is a working example on my machine:
$cmd = "& 'C:\Program Files\7-zip\7z.exe' a -tzip c:\temp\test.zip c:\temp\test.txt"
Invoke-Expression $cmd
iex
is an alias for Invoke-Expression
so you could do:
iex $cmd1
For a full list :
Visit https://ss64.com/ps/ for more Powershell
stuff.
Good Luck...
How to get the full url in Express?
I use the node package 'url' (npm install url)
What it does is when you call
url.parse(req.url, true, true)
it will give you the possibility to retrieve all or parts of the url. More info here: https://github.com/defunctzombie/node-url
I used it in the following way to get whatever comes after the / in http://www.example.com/ to use as a variable and pull up a particular profile (kind of like facebook: http://www.facebook.com/username)
var url = require('url');
var urlParts = url.parse(req.url, true, true);
var pathname = urlParts.pathname;
var username = pathname.slice(1);
Though for this to work, you have to create your route this way in your server.js file:
self.routes['/:username'] = require('./routes/users');
And set your route file this way:
router.get('/:username', function(req, res) {
//here comes the url parsing code
}
Remove substring from the string
here's what I'd do
2.2.1 :015 > class String; def remove!(start_index, end_index) (end_index - start_index + 1).times{ self.slice! start_index }; self end; end;
2.2.1 :016 > "idliketodeleteHEREallthewaytoHEREplease".remove! 14, 32
=> "idliketodeleteplease"
2.2.1 :017 > ":)".remove! 1,1
=> ":"
2.2.1 :018 > "ohnoe!".remove! 2,4
=> "oh!"
Formatted on multiple lines:
class String
def remove!(start_index, end_index)
(end_index - start_index + 1).times{ self.slice! start_index }
self
end
end
Change the background color in a twitter bootstrap modal?
It gets a little bit more complicated if you want to add the background to a specific modal. One way of solving that is to add and call something like this function instead of showing the modal directly:
function showModal(selector) {
$(selector).modal('show');
$('.modal-backdrop').addClass('background-backdrop');
}
Any css can then be applied to the background-backdrop
class.
$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP
REMOTE_ADDR
can not be trusted.
Anyway, try
$ipAddress = $_SERVER['REMOTE_ADDR'];
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
}
Edit: Also, does your server's router have port forwarding enabled? It may be possible that it's messing with the packets.
Security warning: REMOTE_ADDR can be fully trusted! It comes from your own webserver and contains the IP that was used to access it. You don't even need to quote() it for SQL inserts.
But HTTP_X_FORWARDED_FOR is taken directly from the HTTP headers, it can contain the picture of a cat, malicious code, any content. Treat it like that, never trust it.
How to unmount a busy device
YES!! There is a way to detach a busy device immediately - even if it is busy and cannot be unmounted forcefully. You may cleanup all later:
umount -l /PATH/OF/BUSY-DEVICE
umount -f /PATH/OF/BUSY-NFS (NETWORK-FILE-SYSTEM)
NOTE/CAUTION
- These commands can disrupt a running process, cause data loss OR corrupt open files. Programs accessing target DEVICE/NFS files may throw errors OR could not work properly after force unmount.
- Do not execute above
umount
commands when inside mounted path (Folder/Drive/Device) itself. First, you may use pwd
command to validate your current directory path (which should not be the mounted path), then use cd
command to get out of the mounted path - to unmount it later using above commands.
Jenkins - Configure Jenkins to poll changes in SCM
That's an old question, I know. But, according to me, it is missing proper answer.
The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.
You may find the following links interesting:
In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:
#!/bin/sh
# POST-COMMIT HOOK
REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log
MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
echo post-commit $* >> $LOGFILE 2>&1
# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
echo $(date) - $REPOS - $REV: >> $LOGFILE
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
echo logmsg: $MSG >> $LOGFILE 2>&1
echo curl -qs $JENK >> $LOGFILE 2>&1
curl -qs $JENK >> $LOGFILE 2>&1
echo -------- >> $LOGFILE
fi
# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
echo $(date) - $REPOS - $REV: >> $LOGFILE
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
echo logmsg: $MSG >> $LOGFILE 2>&1
echo curl -qs $JENKtest >> $LOGFILE 2>&1
curl -qs $JENKtest >> $LOGFILE 2>&1
echo -------- >> $LOGFILE
fi
exit 0
Socket.IO - how do I get a list of connected sockets/clients?
I think we can access the socket object from the server, and you can assign the nickname, and point its socket id,
io.sockets.on('connection',function(socket){
io.sockets.sockets['nickname'] = socket.id;
client.on("chat", function(data) {
var sock_id = io.sockets.sockets['nickname']
io.sockets.sockets[sock_id].emit("private", "message");
});
});
On disconnect
please remove the nickname from io.sockets.sockets
.
How to make child divs always fit inside parent div?
There are two techniques commonly used for this:
- Absolute Positioning
- Table Styles
Given the HTML you provided here is the solution using Absolute positioning:
_x000D_
_x000D_
body #one {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
width: auto;_x000D_
height: auto;_x000D_
}_x000D_
body #two {_x000D_
width: auto; _x000D_
}_x000D_
body #three {_x000D_
position: absolute;_x000D_
top: 60px;_x000D_
bottom: 0;_x000D_
height: auto;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
html, body {width:100%;height:100%;margin:0;padding:0;}_x000D_
.border {border:1px solid black;}_x000D_
.margin { margin:5px;}_x000D_
#one {width:100%;height:100%;}_x000D_
#two {width:100%;height:50px;}_x000D_
#three {width:100px;height:100%;}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div id="one" class="border">_x000D_
<div id="two" class="border margin"></div>_x000D_
<div id="three" class="border margin"></div>_x000D_
</div>_x000D_
</body
_x000D_
_x000D_
_x000D_
You can always just use the table, tr, and td elements directly despite common criticisms as it will get the job done. If you prefer to use CSS there is no equivalent for colspan so you will likely end up with nested tables. Here is an example:
_x000D_
_x000D_
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
width: 100%;_x000D_
}_x000D_
#one {_x000D_
box-sizing: border-box;_x000D_
display: table;_x000D_
height: 100%;_x000D_
overflow: hidden;_x000D_
width: 100%;_x000D_
border: 1px solid black;_x000D_
}_x000D_
#two {_x000D_
box-sizing: border-box;_x000D_
display: table;_x000D_
height: 50px;_x000D_
padding: 5px;_x000D_
width: 100%;_x000D_
}_x000D_
#three {_x000D_
box-sizing: border-box;_x000D_
display: table;_x000D_
height: 100%;_x000D_
padding-bottom: 60px;_x000D_
padding-left: 5px;_x000D_
_x000D_
}_x000D_
#four {_x000D_
display: table-cell;_x000D_
border: 1px solid black;_x000D_
}_x000D_
#five {_x000D_
display: table-cell;_x000D_
width: 100px;_x000D_
border: 1px solid black;_x000D_
}_x000D_
#six {_x000D_
display: table-cell; _x000D_
}
_x000D_
<html>_x000D_
<div id="one">_x000D_
<div id="two">_x000D_
<div id="four"></div>_x000D_
</div>_x000D_
<div id="three">_x000D_
<div id="five"></div>_x000D_
<div id="six"></div>_x000D_
</div>_x000D_
</div>_x000D_
</html>
_x000D_
_x000D_
_x000D_
What techniques can be used to speed up C++ compilation times?
Where are you spending your time? Are you CPU bound? Memory bound? Disk bound? Can you use more cores? More RAM? Do you need RAID? Do you simply want to improve the efficiency of your current system?
Under gcc/g++, have you looked at ccache? It can be helpful if you are doing make clean; make
a lot.
How to write inline if statement for print?
hmmm, you can do it with a list comprehension. This would only make sense if you had a real range.. but it does do the job:
print([a for i in range(0,1) if b])
or using just those two variables:
print([a for a in range(a,a+1) if b])
SQL Query to find missing rows between two related tables
SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS
(SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)
or
SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN
(SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)
or
SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B
ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL
Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.
Prevent textbox autofill with previously entered values
This is the answer.
_x000D_
_x000D_
<asp:TextBox id="yourtextBoxname" runat="server" AutoCompleteType="Disabled"></asp:TextBox>
_x000D_
_x000D_
_x000D_
AutoCompleteType="Disabled"
If you still get the pre-filled boxes for example in the Firefox browser then its the browser's fault. You have to go
'Options' --> 'Security'(tab) --> Untick
'Remember password for sites and click on Saved Passwords button to delete any details that the browser has saved.
This should solve the problem
convert string date to java.sql.Date
This works for me without throwing an exception:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date parsed = format.parse("20110210");
java.sql.Date sql = new java.sql.Date(parsed.getTime());
}
}
AngularJS - value attribute for select
If the model specified for the drop down does not exist then angular will generate an empty options element. So you will have to explicitly specify the model on the select like this:
<select ng-model="regions[index]" ng-options="....">
Refer to the following as it has been answered before:
Why does AngularJS include an empty option in select? and this fiddle
Update: Try this instead:
<select ng-model="regions[index].code" ng-options="i.code as i.name for i in regions">
</select>
or
<select ng-model="regions[2]" ng-options="r.name for r in regions">
</select>
Note that there is no empty options element in the select.
How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?
For me, none of the solutions above worked when working with Selenium Web Driver C# + Chrome:
- window.resizeTo(1024, 768); - I want to use the whole screen
--start-maximized
- it is ignored
- driver.manage().window().maximize(); - does not work because it requires some extension and I am not allowed to use Chrome extensions
I managed to get it working using InputSimulator:
var inputSim = new InputSimulator();
// WinKey + UP = Maximize focused window
inputSim.Keyboard.ModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.UP);
How to get parameters from the URL with JSP
www.somesite.com/Transaction_List.jsp?accountID=5
For this URL
there is a method call request.getParameter
in java , if you want a number here cast into int
, similarly for string value cast into string
. so for your requirement , just copy past below line in page,
int accountId =(int)request.getParameter("accountID");
you can now call this value useing accountId
in whole page.
here accountId
is name of parameter you can also get more than one parameters using this, but this not work. It will only work with GET
method if you hit POST
request then their will be an error.
Hope this is helpful.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Is there any advantage of using map over unordered_map in case of trivial keys?
I'd echo roughly the same point GMan made: depending on the type of use, std::map
can be (and often is) faster than std::tr1::unordered_map
(using the implementation included in VS 2008 SP1).
There are a few complicating factors to keep in mind. For example, in std::map
, you're comparing keys, which means you only ever look at enough of the beginning of a key to distinguish between the right and left sub-branches of the tree. In my experience, nearly the only time you look at an entire key is if you're using something like int that you can compare in a single instruction. With a more typical key type like std::string, you often compare only a few characters or so.
A decent hash function, by contrast, always looks at the entire key. IOW, even if the table lookup is constant complexity, the hash itself has roughly linear complexity (though on the length of the key, not the number of items). With long strings as keys, an std::map
might finish a search before an unordered_map
would even start its search.
Second, while there are several methods of resizing hash tables, most of them are pretty slow -- to the point that unless lookups are considerably more frequent than insertions and deletions, std::map will often be faster than std::unordered_map
.
Of course, as I mentioned in the comment on your previous question, you can also use a table of trees. This has both advantages and disadvantages. On one hand, it limits the worst case to that of a tree. It also allows fast insertion and deletion, because (at least when I've done it) I've used a fixed-size of table. Eliminating all table resizing allows you to keep your hash table a lot simpler and typically faster.
One other point: the requirements for hashing and tree-based maps are different. Hashing obviously requires a hash function, and an equality comparison, where ordered maps require a less-than comparison. Of course the hybrid I mentioned requires both. Of course, for the common case of using a string as the key, this isn't really a problem, but some types of keys suit ordering better than hashing (or vice versa).
How can I do string interpolation in JavaScript?
Using template syntax fails in older browsers, important if you are creating HTML for public use. Using concatenation is tedious and hard to read, particularly if you have many or long expressions, or if you must use parentheses to handle mixtures of number and string items (both of which use the + operator).
PHP expands quoted strings containing variables and even some expressions using a very compact notation: $a="the color is $color";
In JavaScript, an efficient function can be written to support this: var a=S('the color is ',color);
, using a variable number of arguments. While there is no advantage over concatenation in this example, when the expressions get longer this syntax may be clearer. Or one can use the dollar sign to signal the start of an expression using a JavaScript function, as in PHP.
On the other hand, writing an efficient workaround function to provide template-like expansion of strings for older browsers wouldn't be hard. Someone has probably done it already.
Finally, I imagine that sprintf (as in C, C++, and PHP) could be written in JavaScript, although it would be a little less efficient than these other solutions.
When should you use constexpr capability in C++11?
Suppose it does something a little more complicated.
constexpr int MeaningOfLife ( int a, int b ) { return a * b; }
const int meaningOfLife = MeaningOfLife( 6, 7 );
Now you have something that can be evaluated down to a constant while maintaining good readability and allowing slightly more complex processing than just setting a constant to a number.
It basically provides a good aid to maintainability as it becomes more obvious what you are doing. Take max( a, b )
for example:
template< typename Type > constexpr Type max( Type a, Type b ) { return a < b ? b : a; }
Its a pretty simple choice there but it does mean that if you call max
with constant values it is explicitly calculated at compile time and not at runtime.
Another good example would be a DegreesToRadians
function. Everyone finds degrees easier to read than radians. While you may know that 180 degrees is 3.14159265 (Pi) in radians it is much clearer written as follows:
const float oneeighty = DegreesToRadians( 180.0f );
Lots of good info here:
http://en.cppreference.com/w/cpp/language/constexpr
Load local images in React.js
In React.js latest version v17.0.1, we can not require the local image we have to import it.
like we use to do before = require('../../src/Assets/images/fruits.png');
Now we have to import it like = import fruits from '../../src/Assets/images/fruits.png';
Before React V17.0.1 we can use require(../) and it is working fine.
How do I convert a PDF document to a preview image in PHP?
I install finished! It's worked!
You may be do base install imagemagick on windows.
In php (local)
use call exec(<command line>)
ex:
<?php
$pdf = "filename.pdf";
$info = pathinfo($pdf);
$file_name = basename($pdf,'.'.$info['extension']);
echo $file_name;
$pdf = "filename.pdf[0]";
exec("convert $pdf convert-img/$file_name.jpg");
?>
Besides, you may be use class imagick
in PHP Imagick class
Thanks all helped me!
curl error 18 - transfer closed with outstanding read data remaining
I got this error when i was accidentally downloading a file onto itself.
(I had created a symlink in an sshfs mount of the remote directory to make it available for download, forgot to switch the working directory, and used -OJ
).
I guess it won’t really »help« you when you read this, since it means your file got trashed.
Accessing Session Using ASP.NET Web API
Mark, if you check the nerddinner MVC example the logic is pretty much the same.
You only need to retrieve the cookie and set it in the current session.
Global.asax.cs
public override void Init()
{
this.AuthenticateRequest += new EventHandler(WebApiApplication_AuthenticateRequest);
base.Init();
}
void WebApiApplication_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
SampleIdentity id = new SampleIdentity(ticket);
GenericPrincipal prin = new GenericPrincipal(id, null);
HttpContext.Current.User = prin;
}
enter code here
You'll have to define your "SampleIdentity" class, which you can borrow from the nerddinner project.
What is the meaning of git reset --hard origin/master?
git reset --hard origin/master
says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master
.
You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".
How to add parameters into a WebRequest?
I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;
string data = "phone_number=19735559042";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
How to use the 'replace' feature for custom AngularJS directives?
replace:true
is Deprecated
From the Docs:
replace
([DEPRECATED!], will be removed in next major release - i.e. v2.0)
specify what the template should replace. Defaults to false
.
true
- the template will replace the directive's element.
false
- the template will replace the contents of the directive's element.
-- AngularJS Comprehensive Directive API
From GitHub:
Caitp-- It's deprecated because there are known, very silly problems with replace: true
, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".
-- AngularJS Issue #7636
Update
Note: replace: true
is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.
Issues with replace: true
For more information, see
How do I reverse an int array in Java?
2 ways to reverse an Array .
Using For loop and swap the elements till the mid point with time complexity of O(n/2).
private static void reverseArray() {
int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
int index = array.length - i - 1;
array[i] = array[index];
array[index] = temp;
}
System.out.println(Arrays.toString(array));
}
Using built in function (Collections.reverse())
private static void reverseArrayUsingBuiltInFun() {
int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
Collections.reverse(Ints.asList(array));
System.out.println(Arrays.toString(array));
}
Output : [6, 5, 4, 3, 2, 1]
byte[] to hex string
You have to know the encoding of the string represented in bytes, but you can say System.Text.UTF8Encoding.GetString(bytes)
or System.Text.ASCIIEncoding.GetString(bytes)
. (I'm doing this from memory, so the API may not be exactly correct, but it's very close.)
For the answer to your second question, see this question.
INNER JOIN in UPDATE sql for DB2
for you ask
update file1 f1
set file1.firstfield=
(
select 'BIT OF TEXT' || f2.something
from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
where exists
(
select * from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
and f1.firstfield like 'BLAH%'
if join give multiple result you can force update like this
update file1 f1
set file1.firstfield=
(
select 'BIT OF TEXT' || f2.something
from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
fetch first rows only
)
where exists
(
select * from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
and f1.firstfield like 'BLAH%'
template methode
update table1 f1
set (f1.field1, f1.field2, f1.field3, f1.field4)=
(
select f2.field1, f2.field2, f2.field3, 'CONSTVALUE'
from table2 f2
where (f1.key1, f1.key2)=(f2.key1, f2.key2)
)
where exists
(
select * from table2 f2
where (f1.key1, f1.key2)=(f2.key1, f2.key2)
)
How to check if a column exists before adding it to an existing table in PL/SQL?
All the metadata about the columns in Oracle Database is accessible using one of the following views.
user_tab_cols; -- For all tables owned by the user
all_tab_cols ; -- For all tables accessible to the user
dba_tab_cols; -- For all tables in the Database.
So, if you are looking for a column like ADD_TMS in SCOTT.EMP Table and add the column only if it does not exist, the PL/SQL Code would be along these lines..
DECLARE
v_column_exists number := 0;
BEGIN
Select count(*) into v_column_exists
from user_tab_cols
where upper(column_name) = 'ADD_TMS'
and upper(table_name) = 'EMP';
--and owner = 'SCOTT --*might be required if you are using all/dba views
if (v_column_exists = 0) then
execute immediate 'alter table emp add (ADD_TMS date)';
end if;
end;
/
If you are planning to run this as a script (not part of a procedure), the easiest way would be to include the alter command in the script and see the errors at the end of the script, assuming you have no Begin-End for the script..
If you have file1.sql
alter table t1 add col1 date;
alter table t1 add col2 date;
alter table t1 add col3 date;
And col2 is present,when the script is run, the other two columns would be added to the table and the log would show the error saying "col2" already exists, so you should be ok.
Razor If/Else conditional operator syntax
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.
Java generics - ArrayList initialization
Think of the ?
as to mean "unknown"
. Thus, "ArrayList<? extends Object>"
is to say "an unknown type that (or as long as it)extends Object". Therefore, needful to say, arrayList.add(3)
would be putting something you know, into an unknown. I.e 'Forgetting'.
Understanding __getitem__ method
__getitem__
can be used to implement "lazy" dict
subclasses. The aim is to avoid instantiating a dictionary at once that either already has an inordinately large number of key-value pairs in existing containers, or has an expensive hashing process between existing containers of key-value pairs, or if the dictionary represents a single group of resources that are distributed over the internet.
As a simple example, suppose you have two lists, keys
and values
, whereby {k:v for k,v in zip(keys, values)}
is the dictionary that you need, which must be made lazy for speed or efficiency purposes:
class LazyDict(dict):
def __init__(self, keys, values):
self.keys = keys
self.values = values
super().__init__()
def __getitem__(self, key):
if key not in self:
try:
i = self.keys.index(key)
self.__setitem__(self.keys.pop(i), self.values.pop(i))
except ValueError, IndexError:
raise KeyError("No such key-value pair!!")
return super().__getitem__(key)
Usage:
>>> a = [1,2,3,4]
>>> b = [1,2,2,3]
>>> c = LazyDict(a,b)
>>> c[1]
1
>>> c[4]
3
>>> c[2]
2
>>> c[3]
2
>>> d = LazyDict(a,b)
>>> d.items()
dict_items([])
"Content is not allowed in prolog" when parsing perfectly valid XML on GAE
Unexpected reason: #
character in file path
Due to some internal bug, the error Content is not allowed in prolog also appears if the file content itself is 100% correct but you are supplying the file name like C:\Data\#22\file.xml
.
This may possibly apply to other special characters, too.
How to check: If you move your file into a path without special characters and the error disappears, then it was this issue.
Forcing a postback
You can try redirecting to same page.
Response.Redirect(Request.RawUrl);
Is it possible to change the package name of an Android app on Google Play?
As far as I can tell what you could do is "retire" your previous app and redirect all users to your new app. This procedure is not supported by Google (tsk... tsk...), but it could be implemented in four steps:
Change the current application to show a message to the users about the upgrade and redirect them to the new app listing.
Probably a full screen message would do with some friendly text. This message could be triggered remotely ideally, but a cut-off date can be used too. (But then that will be a hard deadline for you, so be careful... ;))
Release the modified old app as an upgrade, maybe with some feature upgrades/bug fixes too, to "sweeten the deal" to the users. Still there is no guarantee that all users will upgrade, but probably the majority will do.
Prepare your new app with the updated package name and upload it to the store, then trigger the message in the old app (or just wait until it expires, if that was your choice).
Unpublish the old app in Play Store to avoid any new installs. Unpublishing an app doesn't mean the users who already installed it won't have access to it anymore, but at least the potential new users won't find it on the market.
Not ideal and can be annoying to the users, sometimes even impossible to implement due to the status/possibilities of the app. But since Google left us no choice this is the only way to migrate the users of the old apps to a "new" one (even if it is not really new).
Not to mention that if you don't have access to the sources and code signing details for the old app then all you could do is hoping that he users will notice the new app...
If anybody figured out a better way by all means: please do tell.
How do I POST an array of objects with $.ajax (jQuery or Zepto)
edit: I guess it's now starting to be safe to use the native JSON.stringify() method, supported by most browsers (yes, even IE8+ if you're wondering).
As simple as:
JSON.stringify(yourData)
You should encode you data in JSON before sending it, you can't just send an object like this as POST data.
I recommand using the jQuery json plugin to do so. You can then use something like this in jQuery:
$.post(_saveDeviceUrl, {
data : $.toJSON(postData)
}, function(response){
//Process your response here
}
);
How to resolve a Java Rounding Double issue
To control the precision of floating point arithmetic, you should use java.math.BigDecimal. Read The need for BigDecimal by John Zukowski for more information.
Given your example, the last line would be as following using BigDecimal.
import java.math.BigDecimal;
BigDecimal premium = BigDecimal.valueOf("1586.6");
BigDecimal netToCompany = BigDecimal.valueOf("708.75");
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);
This results in the following output.
877.85 = 1586.6 - 708.75
How to POST the data from a modal form of Bootstrap?
I was facing same issue not able to post form without ajax.
but found solution , hope it can help and someones time.
<form name="paymentitrform" id="paymentitrform" class="payment"
method="post"
action="abc.php">
<input name="email" value="" placeholder="email" />
<input type="hidden" name="planamount" id="planamount" value="0">
<input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
name="planform">
</form>
You can submit post form, from bootstrap modal using below javascript/jquery code :
call the below function onclick of input submit button
function form_submit() {
document.getElementById("paymentitrform").submit();
}
What is the difference between . (dot) and $ (dollar sign)?
The most important part about $ is that it has the lowest operator precedence.
If you type info you'll see this:
?> :info ($)
($) :: (a -> b) -> a -> b
-- Defined in ‘GHC.Base’
infixr 0 $
This tells us it is an infix operator with right-associativity that has the lowest possible precedence. Normal function application is left-associative and has highest precedence (10). So $ is something of the opposite.
So then we use it where normal function application or using () doesn't work.
So, for example, this works:
?> head . sort $ "example"
?> e
but this does not:
?> head . sort "example"
because . has lower precedence than sort and the type of (sort "example") is [Char]
?> :type (sort "example")
(sort "example") :: [Char]
But . expects two functions and there isn't a nice short way to do this because of the order of operations of sort and .
How to implement the Softmax function in Python
Already answered in much detail in above answers. max
is subtracted to avoid overflow. I am adding here one more implementation in python3.
import numpy as np
def softmax(x):
mx = np.amax(x,axis=1,keepdims = True)
x_exp = np.exp(x - mx)
x_sum = np.sum(x_exp, axis = 1, keepdims = True)
res = x_exp / x_sum
return res
x = np.array([[3,2,4],[4,5,6]])
print(softmax(x))
npm ERR! Error: EPERM: operation not permitted, rename
If you want to avoid the --force
option (which is always a better approach), I suggest making sure that you have stopped running the project, as this is usually the main reason for locking the files in almost 90% of the cases I have seen
I suggest the following steps in this order:
1- In Angular stopping ng s
and in React stopping npm start
usually solves this issue because usually this error happens if a development server is running the project as it locks some files & then npm can't update them thus throwing this error
2- If the above doesn't work, then try closing the code editor that has the workspace opened in it (maybe it was locking some files or something)
So try closing the code editor & running:
npm install
3- If still it doesn't work, then maybe you can try the --force
option
npm install --force
react-router go back a page how do you configure history?
Go back to specific page:
import { useHistory } from "react-router-dom";
const history = useHistory();
const routeChange = () => {
let path = '/login';
history.push(path);
};
Go back to previous page:
import { useHistory } from "react-router-dom";
const history = useHistory();
const routeChange = () => {
history.goBack()
};
Convert International String to \u Codes in java
You could probably hack if from this JavaScript code:
/* convert to \uD83D\uDE4C */
function text_to_unicode(string) {
'use strict';
function is_whitespace(c) { return 9 === c || 10 === c || 13 === c || 32 === c; }
function left_pad(string) { return Array(4).concat(string).join('0').slice(-1 * Math.max(4, string.length)); }
string = string.split('').map(function(c){ return "\\u" + left_pad(c.charCodeAt(0).toString(16).toUpperCase()); }).join('');
return string;
}
/* convert \uD83D\uDE4C to */
function unicode_to_text(string) {
var prefix = "\\\\u"
, regex = new RegExp(prefix + "([\da-f]{4})","ig")
;
string = string.replace(regex, function(match, backtrace1){
return String.fromCharCode( parseInt(backtrace1, 16) )
});
return string;
}
source: iCompile - Yet Another JavaScript Unicode Encode/Decode
HTTP POST using JSON in Java
I found this question looking for solution about how to send post request from java client to Google Endpoints. Above answers, very likely correct, but not work in case of Google Endpoints.
Solution for Google Endpoints.
- Request body must contains only JSON string, not name=value pair.
Content type header must be set to "application/json".
post("http://localhost:8888/_ah/api/langapi/v1/createLanguage",
"{\"language\":\"russian\", \"description\":\"dsfsdfsdfsdfsd\"}");
public static void post(String url, String json ) throws Exception{
String charset = "UTF-8";
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(json.getBytes(charset));
}
InputStream response = connection.getInputStream();
}
It sure can be done using HttpClient as well.
How to get milliseconds from LocalDateTime in Java 8
What I do so I don't specify a time zone is,
System.out.println("ldt " + LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
System.out.println("ctm " + System.currentTimeMillis());
gives
ldt 1424812121078
ctm 1424812121281
As you can see the numbers are the same except for a small execution time.
Just in case you don't like System.currentTimeMillis, use Instant.now().toEpochMilli()
How to display both icon and title of action inside ActionBar?
You can create actions with text in 2 ways:
1- From XML:
<item android:id="@id/resource_name"
android:title="text"
android:icon="@drawable/drawable_resource_name"
android:showAsAction="withText" />
When inflating the menu, you should call getSupportMenuInflater()
since you are using ActionBarSherlock
.
2- Programmatically:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, ID, POSITION, TEXT);
item.setIcon(R.drawable.drawable_resource_name);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
Make sure you import com.actionbarsherlock.view.Menu
and com.actionbarsherlock.view.MenuItem
.
Default value of function parameter
In C++ the requirements imposed on default arguments with regard to their location in parameter list are as follows:
Default argument for a given parameter has to be specified no more than once. Specifying it more than once (even with the same default value) is illegal.
Parameters with default arguments have to form a contiguous group at the end of the parameter list.
Now, keeping that in mind, in C++ you are allowed to "grow" the set of parameters that have default arguments from one declaration of the function to the next, as long as the above requirements are continuously satisfied.
For example, you can declare a function with no default arguments
void foo(int a, int b);
In order to call that function after such declaration you'll have to specify both arguments explicitly.
Later (further down) in the same translation unit, you can re-declare it again, but this time with one default argument
void foo(int a, int b = 5);
and from this point on you can call it with just one explicit argument.
Further down you can re-declare it yet again adding one more default argument
void foo(int a = 1, int b);
and from this point on you can call it with no explicit arguments.
The full example might look as follows
void foo(int a, int b);
int main()
{
foo(2, 3);
void foo(int a, int b = 5); // redeclare
foo(8); // OK, calls `foo(8, 5)`
void foo(int a = 1, int b); // redeclare again
foo(); // OK, calls `foo(1, 5)`
}
void foo(int a, int b)
{
// ...
}
As for the code in your question, both variants are perfectly valid, but they mean different things. The first variant declares a default argument for the second parameter right away. The second variant initially declares your function with no default arguments and then adds one for the second parameter.
The net effect of both of your declarations (i.e. the way it is seen by the code that follows the second declaration) is exactly the same: the function has default argument for its second parameter. However, if you manage to squeeze some code between the first and the second declarations, these two variants will behave differently. In the second variant the function has no default arguments between the declarations, so you'll have to specify both arguments explicitly.
How to get the last day of the month?
Here is a solution based python lambdas:
next_month = lambda y, m, d: (y, m + 1, 1) if m + 1 < 13 else ( y+1 , 1, 1)
month_end = lambda dte: date( *next_month( *dte.timetuple()[:3] ) ) - timedelta(days=1)
The next_month
lambda finds the tuple representation of the first day of the next month, and rolls over to the next year. The month_end
lambda transforms a date (dte
) to a tuple, applies next_month
and creates a new date. Then the "month's end" is just the next month's first day minus timedelta(days=1)
.
Can you get a Windows (AD) username in PHP?
If you're using Apache on Windows, you can install the mod_auth_sspi from
https://sourceforge.net/projects/mod-auth-sspi/
Instructions are in the INSTALL file, and there is a whoami.php example. (It's just a case of copying the mod_auth_sspi.so file into a folder and adding a line into httpd.conf.)
Once it's installed and the necessary settings are made in httpd.conf to protect the directories you wish, PHP will populate the $_SERVER['REMOTE_USER']
with the user and domain ('USER\DOMAIN') of the authenticated user in IE -- or prompt and authenticate in Firefox before passing it in.
Info is session-based, so single(ish) signon is possible even in Firefox...
-Craig
How to make inline functions in C#
C# 7 adds support for local functions
Here is the previous example using a local function
void Method()
{
string localFunction(string source)
{
// add your functionality here
return source ;
};
// call the inline function
localFunction("prefix");
}