I like this way and I'm using it
Inside
public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
Put
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_image_and_text, parent, false);
v.setOnClickListener(new MyOnClickListener());
And create this class anywhere you want it
class MyOnClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
int itemPosition = recyclerView.indexOfChild(v);
Log.e("Clicked and Position is ",String.valueOf(itemPosition));
}
}
I've read before that there is a better way but I like this way is easy and not complicated.
This is my working code. Thanks to Paulo for the links. You create a custom error handler and call the trigger_error
function with the correct $errno
exception, even if it's not an error. Make sure you can write to the log file directory without administrator access.
<?php
$logfile_dir = "C:\workspace\logs\\"; // or "/var/log/" for Linux
$logfile = $logfile_dir . "php_" . date("y-m-d") . ".log";
$logfile_delete_days = 30;
function error_handler($errno, $errstr, $errfile, $errline)
{
global $logfile_dir, $logfile, $logfile_delete_days;
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting, so let it fall
// through to the standard PHP error handler
return false;
}
$filename = basename($errfile);
switch ($errno) {
case E_USER_ERROR:
file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "ERROR >> message = [$errno] $errstr\n", FILE_APPEND | LOCK_EX);
exit(1);
break;
case E_USER_WARNING:
file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "WARNING >> message = $errstr\n", FILE_APPEND | LOCK_EX);
break;
case E_USER_NOTICE:
file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "NOTICE >> message = $errstr\n", FILE_APPEND | LOCK_EX);
break;
default:
file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "UNKNOWN >> message = $errstr\n", FILE_APPEND | LOCK_EX);
break;
}
// delete any files older than 30 days
$files = glob($logfile_dir . "*");
$now = time();
foreach ($files as $file)
if (is_file($file))
if ($now - filemtime($file) >= 60 * 60 * 24 * $logfile_delete_days)
unlink($file);
return true; // Don't execute PHP internal error handler
}
set_error_handler("error_handler");
trigger_error("testing 1,2,3", E_USER_NOTICE);
?>
function unzip {
param (
[string]$archiveFilePath,
[string]$destinationPath
)
if ($archiveFilePath -notlike '?:\*') {
$archiveFilePath = [System.IO.Path]::Combine($PWD, $archiveFilePath)
}
if ($destinationPath -notlike '?:\*') {
$destinationPath = [System.IO.Path]::Combine($PWD, $destinationPath)
}
Add-Type -AssemblyName System.IO.Compression
Add-Type -AssemblyName System.IO.Compression.FileSystem
$archiveFile = [System.IO.File]::Open($archiveFilePath, [System.IO.FileMode]::Open)
$archive = [System.IO.Compression.ZipArchive]::new($archiveFile)
if (Test-Path $destinationPath) {
foreach ($item in $archive.Entries) {
$destinationItemPath = [System.IO.Path]::Combine($destinationPath, $item.FullName)
if ($destinationItemPath -like '*/') {
New-Item $destinationItemPath -Force -ItemType Directory > $null
} else {
New-Item $destinationItemPath -Force -ItemType File > $null
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($item, $destinationItemPath, $true)
}
}
} else {
[System.IO.Compression.ZipFileExtensions]::ExtractToDirectory($archive, $destinationPath)
}
}
Using:
unzip 'Applications\Site.zip' 'C:\inetpub\wwwroot\Site'
my config.inc.php file in the phpmyadmin folder. Change username and password to the one you have set for your database.
<?php
/*
* This is needed for cookie based authentication to encrypt password in
* cookie
*/
$cfg['blowfish_secret'] = 'xampp'; /* YOU SHOULD CHANGE THIS FOR A MORE SECURE COOKIE AUTH! */
/*
* Servers configuration
*/
$i = 0;
/*
* First server
*/
$i++;
/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'enter_username_here';
$cfg['Servers'][$i]['password'] = 'enter_password_here';
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;
/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';
/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][$i]['relation'] = 'pma_relation';
$cfg['Servers'][$i]['table_info'] = 'pma_table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma_column_info';
$cfg['Servers'][$i]['history'] = 'pma_history';
$cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
/*
* End of servers configuration
*/
?>
Here's the most basic version:
function collectionHas(a, b) { //helper function (see below)
for(var i = 0, len = a.length; i < len; i ++) {
if(a[i] == b) return true;
}
return false;
}
function findParentBySelector(elm, selector) {
var all = document.querySelectorAll(selector);
var cur = elm.parentNode;
while(cur && !collectionHas(all, cur)) { //keep going up until you find a match
cur = cur.parentNode; //go up
}
return cur; //will return null if not found
}
var yourElm = document.getElementById("yourElm"); //div in your original code
var selector = ".yes";
var parent = findParentBySelector(yourElm, selector);
it's been a long time but another case is when performing requests which takes a long time on the server side (more then 2 minutes which is the default for express) and the timeout parameter was not configured in the server side. In my case I was doing client->server->server request (Node.js express) and I should set the timeout parameter on each request router on the server and on the client. So in both servers I needed to set the request timeout by using
req.setTimeout([your needed timeout])
on the router.
To communicate a child component with another child component I've made a method in parent which calls a method in a child with:
this.$refs.childMethod()
And from the another child I've called the root method:
this.$root.theRootMethod()
It worked for me.
You can reuse the implementation I added to ACRA: http://code.google.com/p/acra/source/browse/tags/REL-3_1_0/CrashReport/src/org/acra/HttpUtils.java?r=236
(See the doPost(Map, Url) method, working over http and https even with self signed certs)
I know is old topic but what about simple solution like while loop?
int function count(array[]) {
int i = 0;
while(array[i] != NULL) {
i++;
}
return i;
}
I know that is slower than sizeof() but this is another example of array count.
Store them as two fields for phone numbers - a "number" and a "mask" as TinyText
types which do not need more than 255 items.
Before we store the files we parse the phone number to get the formatting that has been used and that creates the mask, we then store the number a digits only e.g.
Input: (0123) 456 7890
Number: 01234567890
Mask: (nnnn)_nnn_nnnn
Theoretically this allows us to perform comparison searches on the Number field such as getting all phone numbers that begin with a specific area code, without having to worry how it was input by the users
If your iframe is in the same domain as your parent page you can access the elements using document.frames
collection.
// replace myIFrame with your iFrame id
// replace myIFrameElemId with your iFrame's element id
// you can work on document.frames['myIFrame'].document like you are working on
// normal document object in JS
window.frames['myIFrame'].document.getElementById('myIFrameElemId')
If your iframe is not in the same domain the browser should prevent such access for security reasons.
To recurse on a solved problem: do nothing, you're done.
To recurse on an open problem: do the next step, then recurse on the rest.
Building upon Fabien Kruba's already excellent answer, I thought it would be nice if the **
portion of the URL could be given as a parameter to the controller method via an annotation, in a way which was similar to @RequestParam
and @PathVariable
, rather than always using a utility method which explicitly required the HttpServletRequest
. So here's an example of how that might be implemented. Hopefully someone finds it useful.
Create the annotation, along with the argument resolver:
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface WildcardParam {
class Resolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterAnnotation(WildcardParam.class) != null;
}
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
return request == null ? null : new AntPathMatcher().extractPathWithinPattern(
(String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE),
(String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
}
}
}
Register the method argument resolver:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new WildcardParam.Resolver());
}
}
Use the annotation in your controller handler methods to have easy access to the **
portion of the URL:
@RestController
public class SomeController {
@GetMapping("/**")
public void someHandlerMethod(@WildcardParam String wildcardParam) {
// use wildcardParam here...
}
}
Delete the .metadata
folder in your workspace.
You have to define your TASK_CAT
column first and then set foreign key on it.
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " ("
+ TASK_ID + " integer primary key autoincrement, "
+ TASK_TITLE + " text not null, "
+ TASK_NOTES + " text not null, "
+ TASK_DATE_TIME + " text not null,"
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+"("+CAT_ID+"));";
More information you can find on sqlite foreign keys doc.
Using base-n mini lib, you can do the following:
some_data_t in[] { ... };
constexpr int len = sizeof(in)/sizeof(in[0]);
std::string encoded;
bn::encode_b64(in, in + len, std::back_inserter(encoded));
some_data_t out[len];
bn::decode_b64(encoded.begin(), encoded.end(), out);
The API is generic, iterator-based.
Disclosure: I'm the author.
I used the following on Mac OSX.
currDate=`date +%Y%m%d`
epochDate=$(date -j -f "%Y%m%d" "${currDate}" "+%s")
Create controller go to cmd and the type php artisan make:controller auth\LoginController
You can put an equal formula, then copy it so reference the whole range (one cell goes into one cell)
=Sheet2!A1
If you need to concatenate the results, you'll need a longer formula, or a user-defined function (i.e. macro).
=Sheet2!A1&Sheet2!B1&Sheet2!C1&Sheet2!D1&Sheet2!E1&Sheet2!F1
Performance wise there is no difference. The only purpose of having const_iterator
over iterator
is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:
std::vector<int> integers{ 3, 4, 56, 6, 778 };
If we were to read & write the members of a container we will use iterator:
for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
{*it = 4; std::cout << *it << std::endl; }
If we were to only read the members of the container integers
you might wanna use const_iterator which doesn't allow to write or modify members of container.
for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
{ cout << *it << endl; }
NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.
If you have a handleChange
function that looks like this:
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
}
You can create a custom onChange
function so that it acts like an text input would:
<input
type="checkbox"
name="check"
checked={this.state.check}
onChange={(e) => {
this.handleChange({
target: {
name: e.target.name,
value: e.target.checked,
},
});
}}
/>
Ruby has no pre/post increment/decrement operator. For instance,
x++
orx--
will fail to parse. More importantly,++x
or--x
will do nothing! In fact, they behave as multiple unary prefix operators:-x == ---x == -----x == ......
To increment a number, simply writex += 1
.
Taken from "Things That Newcomers to Ruby Should Know " (archive, mirror)
That explains it better than I ever could.
EDIT: and the reason from the language author himself (source):
- ++ and -- are NOT reserved operator in Ruby.
- C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
- self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.
No. You can't send headers after they were sent. Try to use hooks in wordpress
I think it suffices to hand the data over directly:
$("#inputhidden").select2("data", data, true);
Note that the second parameter seems to indicate that a refresh is desired.
Thanks to @Bergi for help with this.
If that doesn't automatically update you could either try calling it's updateResults method directly.
$("#inputhidden").select2("updateResults");
Or trigger it indirectly by sending a trigger to the "input.select2-input" like so:
var search = $("#inputhidden input.select2-input");
search.trigger("input");
The reject
actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject()
the exception value is undefined
, hence the "undefined" part in the error that you get.
You do not show the code that uses the promise, but I reckon it is something like this:
var promise = doSth();
promise.then(function() { doSthHere(); });
Try adding an empty failure call, like this:
promise.then(function() { doSthHere(); }, function() {});
This will prevent the error to appear.
However, I would consider calling reject
only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.
install sqlescapy package:
pip install sqlescapy
then you can escape variables in you raw query
from sqlescapy import sqlescape
query = """
SELECT * FROM "bar_table" WHERE id='%s'
""" % sqlescape(user_input)
Do git help gitignore
You will get the help page with following line:
A line starting with # serves as a comment.
The following code:
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
interface Function<T> {
long perform(T parameter, long x);
}
class MyArray<T> {
T[] array;
long x;
public MyArray(int size, Class<T> type, long x) {
array = (T[]) Array.newInstance(type, size);
this.x = x;
}
public void forEach(Function<T> function) {
for (T element : array) {
x = function.perform(element, x);
}
}
}
class Compute {
int factor;
final long constant;
public Compute(int factor, long constant) {
this.factor = factor;
this.constant = constant;
}
public long compute(long parameter, long x) {
return x * factor + parameter + constant;
}
}
public class Main {
public static void main(String[] args) {
List<Long> numbers = new ArrayList<Long>(50000000);
for (int i = 0; i < 50000000; i++) {
numbers.add(i * i + 5L);
}
long x = 234553523525L;
long time = System.currentTimeMillis();
for (int i = 0; i < numbers.size(); i++) {
x += x * 7 + numbers.get(i) + 3;
}
System.out.println(System.currentTimeMillis() - time);
System.out.println(x);
x = 0;
time = System.currentTimeMillis();
for (long i : numbers) {
x += x * 7 + i + 3;
}
System.out.println(System.currentTimeMillis() - time);
System.out.println(x);
x = 0;
numbers = null;
MyArray<Long> myArray = new MyArray<Long>(50000000, Long.class, 234553523525L);
for (int i = 0; i < 50000000; i++) {
myArray.array[i] = i * i + 3L;
}
time = System.currentTimeMillis();
myArray.forEach(new Function<Long>() {
public long perform(Long parameter, long x) {
return x * 8 + parameter + 5L;
}
});
System.out.println(System.currentTimeMillis() - time);
System.out.println(myArray.x);
myArray = null;
myArray = new MyArray<Long>(50000000, Long.class, 234553523525L);
for (int i = 0; i < 50000000; i++) {
myArray.array[i] = i * i + 3L;
}
time = System.currentTimeMillis();
myArray.forEach(new Function<Long>() {
public long perform(Long parameter, long x) {
return new Compute(8, 5).compute(parameter, x);
}
});
System.out.println(System.currentTimeMillis() - time);
System.out.println(myArray.x);
}
}
Gives following output on my system:
224
-699150247503735895
221
-699150247503735895
220
-699150247503735895
219
-699150247503735895
I'm running Ubuntu 12.10 alpha with OracleJDK 1.7 update 6.
In general HotSpot optimizes a lot of indirections and simple reduntant operations, so in general you shouldn't worry about them unless there are a lot of them in seqence or they are heavily nested.
On the other hand, indexed get on LinkedList is much slower than calling next on iterator for LinkedList so you can avoid that performance hit while retaining readability when you use iterators (explicitly or implicitly in for-each loop).
Visual Studio Express for Windows needs Windows 8.1. Having a look at the requirements page you might want to try the Web or Windows Desktop version which are able to run under Windows 7.
mylist[c(5,7,9)]
should do it.
You want the sublists returned as sublists of the result list; you don't use [[]]
(or rather, the function is [[
) for that -- as Dason mentions in comments, [[
grabs the element.
Another way of doing it. This approach can be useful for changing the text to 2 different colors, just by adding 2 spans.
Label1.Text = "String with original color" + "<b><span style=""color:red;"">" + "Your String Here" + "</span></b>";
You need to use:
await client.PostAsync(uri, content);
Something like that:
var comment = "hello world";
var questionId = 1;
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("comment", comment),
new KeyValuePair<string, string>("questionId", questionId)
});
var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);
And if you need to get the response after post, you should use:
var stringContent = await response.Content.ReadAsStringAsync();
Hope it helps ;)
I solved a similar problem by passing the value of the available parameter in the URL instead of the label of the parameter.
For instance, I have a report with a parameter named viewName and the predefined Available Values for the parameter are: (labels/values) orders/sub_orders, orderDetail/sub_orderDetail, product/sub_product.
To call this report with a URL to render automatically for parameter=product, you must specify the value not the label.
This would be wrong:
http://server/reportserver?/Data+Dictionary/DetailedInfo&viewName=product&rs:Command=Render
This is correct: http://server/reportserver?/Data+Dictionary/DetailedInfo&viewName=sub_product&rs:Command=Render
In my case, this was happening because the android/gradlew file did not have execute permission. Once granted, this worked fine
Also if you want to make something similar to
You need
1.Set horizontal and vertical alignment for button to
Find all required values and set UIImageEdgeInsets
CGSize buttonSize = button.frame.size;
NSString *buttonTitle = button.titleLabel.text;
CGSize titleSize = [buttonTitle sizeWithAttributes:@{ NSFontAttributeName : [UIFont camFontZonaProBoldWithSize:12.f] }];
UIImage *buttonImage = button.imageView.image;
CGSize buttonImageSize = buttonImage.size;
CGFloat offsetBetweenImageAndText = 10; //vertical space between image and text
[button setImageEdgeInsets:UIEdgeInsetsMake((buttonSize.height - (titleSize.height + buttonImageSize.height)) / 2 - offsetBetweenImageAndText,
(buttonSize.width - buttonImageSize.width) / 2,
0,0)];
[button setTitleEdgeInsets:UIEdgeInsetsMake((buttonSize.height - (titleSize.height + buttonImageSize.height)) / 2 + buttonImageSize.height + offsetBetweenImageAndText,
titleSize.width + [button imageEdgeInsets].left > buttonSize.width ? -buttonImage.size.width + (buttonSize.width - titleSize.width) / 2 : (buttonSize.width - titleSize.width) / 2 - buttonImage.size.width,
0,0)];
This will arrange your title and image on button.
Also please note update this on each relayout
Swift
import UIKit
extension UIButton {
// MARK: - UIButton+Aligment
func alignContentVerticallyByCenter(offset:CGFloat = 10) {
let buttonSize = frame.size
if let titleLabel = titleLabel,
let imageView = imageView {
if let buttonTitle = titleLabel.text,
let image = imageView.image {
let titleString:NSString = NSString(string: buttonTitle)
let titleSize = titleString.sizeWithAttributes([
NSFontAttributeName : titleLabel.font
])
let buttonImageSize = image.size
let topImageOffset = (buttonSize.height - (titleSize.height + buttonImageSize.height + offset)) / 2
let leftImageOffset = (buttonSize.width - buttonImageSize.width) / 2
imageEdgeInsets = UIEdgeInsetsMake(topImageOffset,
leftImageOffset,
0,0)
let titleTopOffset = topImageOffset + offset + buttonImageSize.height
let leftTitleOffset = (buttonSize.width - titleSize.width) / 2 - image.size.width
titleEdgeInsets = UIEdgeInsetsMake(titleTopOffset,
leftTitleOffset,
0,0)
}
}
}
}
tabindex
is a global attribute responsible for two things:
In my mind the second thing is even more important than the first one. There are very few elements that are focusable by default (e.g. <a> and form controls). Developers very often add some JavaScript event handlers (like 'onclick') on not focusable elements (<div>, <span> and so on), and the way to make your interface be responsive not only to mouse events but also to keyboard events (e.g. 'onkeypress') is to make such elements focusable. Lastly, if you don't want to set the order but just make your element focusable use tabindex="0"
on all such elements:
<div tabindex="0"></div>
Also, if you don't want it to be focusable via the tab key then use tabindex="-1"
. For example, the below link will not be focused while using tab keys to traverse.
<a href="#" tabindex="-1">Tab key cannot reach here!</a>
If you commit one file and push your revision, it will not transfer the whole repository, it will push changes.
Post.getInitialProps = async function(context) {_x000D_
_x000D_
const data = {}_x000D_
try{_x000D_
data.queryParam = queryString.parse(context.req.url.split('?')[1]);_x000D_
}catch(err){_x000D_
data.queryParam = queryString.parse(window.location.search);_x000D_
}_x000D_
return { data };_x000D_
};
_x000D_
Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.
So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.
Solution:
By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution
The answers above will definitely solve your problem, but here's what's actually going on:
The default location for storing the rdb.dump
file is ./
(denoting current directory). You can verify this in your redis.conf
file. Therefore, the directory from where you start the redis server is where a dump.rdb
file will be created and updated.
It seems you have started running the redis server in a directory where redis does not have the correct permissions to create the dump.rdb
file.
To make matters worse, redis will also probably not allow you to shut down the server either until it is able to create the rdb file to ensure the proper saving of data.
To solve this problem, you must go into the active redis client environment using redis-cli
and update the dir
key and set its value to your project folder or any folder where non-root has permissions to save. Then run BGSAVE
to invoke the creation of the dump.rdb
file.
CONFIG SET dir "/hardcoded/path/to/your/project/folder"
BGSAVE
(Now, if you need to save the dump.rdb file in the directory that you started the server in, then you will need to change permissions for the directory so that redis can write to it. You can search stackoverflow for how to do that).
You should now be able to shut down the redis server. Note that we hardcoded the path. Hardcoding is rarely a good practice and I highly recommend starting the redis server from your project directory and changing the dir key back to
./`.
CONFIG SET dir "./"
BGSAVE
That way when you need redis for another project, the dump file will be created in your current project's directory and not in the hardcoded path's project directory.
My Personal View of Gist and GitHub:
Gist: Gist is a simple way to share code snippets and pastes with others. It is used when you need to share a sample piece of code or technique with your co-workers or friends.
And
GitHub GitHub, on the other hand, provides a platform to share an entire project as a repo among a team(private repo) or to the whole world(public repo).
Both Will log version details.
You have to convert the response to JSON using Gson.toJson(object)
.
For example:
return Response.status(Status.OK).entity(new Gson().toJson(Student)).build();
Go to data directory and try this:
mv database1 database2
It works for me on a 900 MB database size.
Try disabling iptables: service iptables stop
If this works, enable TCP port 80 to your firewall rules: run system-config-selinux from root, and enable TCP port 80 (HTTP) on your firewall.
Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).
Either way works, I like to put that logic in the query so the report has to do less.
Apply does the job well, but is quite slow. Using sapply and vapply could be useful. dplyr's rowwise could also be useful Let's see an example of how to do row wise product of any data frame.
a = data.frame(t(iris[1:10,1:3]))
vapply(a, prod, 0)
sapply(a, prod)
Note that assigning to variable before using vapply/sapply/ apply is good practice as it reduces time a lot. Let's see microbenchmark results
a = data.frame(t(iris[1:10,1:3]))
b = iris[1:10,1:3]
microbenchmark::microbenchmark(
apply(b, 1 , prod),
vapply(a, prod, 0),
sapply(a, prod) ,
apply(iris[1:10,1:3], 1 , prod),
vapply(data.frame(t(iris[1:10,1:3])), prod, 0),
sapply(data.frame(t(iris[1:10,1:3])), prod) ,
b %>% rowwise() %>%
summarise(p = prod(Sepal.Length,Sepal.Width,Petal.Length))
)
Have a careful look at how t() is being used
Fast, simple, but maybe not always right:
>>> [x for x in mylist if x.isdigit()]
['1', '2', '3', '4']
More traditional if you need to get numbers:
new_list = []
for value in mylist:
try:
new_list.append(int(value))
except ValueError:
continue
Note: The result has integers. Convert them back to strings if needed, replacing the lines above with:
try:
new_list.append(str(int(value)))
Please Try this code margin-left:60px
instead of left:60px
please take a look: http://jsfiddle.net/hbirjand/2LtBh/2/
as @Shomz said,transition must be changed to transition:margin 1s linear;
instead of transition:all 1s linear;
This was a problem with the user having deny privileges as well; in my haste to grant permissions I basically gave the user everything. And deny was killing it. So as soon as I removed those permissions it worked.
AFAIR, MySQL implements INTERSECT through INNER JOIN.
\d will not match the decimal point. Use the following for the decimal.
const re = /^\d*(\.\d+)?$/
'123'.match(re) // true
'123.3'.match(re) // true
'123!3'.match(re) // false
You can use TypeScript's native string interpolation in case if your only goal to eliminate ugly string concatenations and boring string conversions:
var yourMessage = `Your text ${yourVariable} your text continued ${yourExpression} and so on.`
NOTE:
At the right side of the assignment statement the delimiters are neither single or double quotes, instead a special char called backtick or grave accent.
The TypeScript compiler will translate your right side special literal to a string concatenation expression. With other words this syntax is not relies the ECMAScript 6 feature instead a native TypeScript feature. Your generated javascript code remains compatible.
If a value in YAML begins with a curly brace ({
), the YAML parser assumes that it is a dictionary. So, for cases like this where there is a (Jinja2) variable in the value, one of the following two strategies needs to be adopted to avoiding confusing the YAML parser:
Quote the whole command:
- command: "{{ item }} chdir=/src/package/"
with_items:
- ./configure
- /usr/bin/make
- /usr/bin/make install
or change the order of the arguments:
- command: chdir=/src/package/ {{ item }}
with_items:
- ./configure
- /usr/bin/make
- /usr/bin/make install
Thanks for @RamondelaFuente alternative suggestion.
Alphanumeric characters and all of
~
-
_
.
!
*
'
(
)
,
are valid within an URL.
All other characters must be encoded.
<span>You have {{products|length}} products</span>
You can also use this syntax in expressions like
{% if products|length > 1 %}
jinja2's builtin filters are documented here; and specifically, as you've already found, length
(and its synonym count
) is documented to:
Return the number of items of a sequence or mapping.
So, again as you've found, {{products|count}}
(or equivalently {{products|length}}
) in your template will give the "number of products" ("length of list")
Following STEPS worked for me with hadoop 2.2.0,
STEP 1 stop hadoop
hduser@prayagupd$ /usr/local/hadoop-2.2.0/sbin/stop-dfs.sh
STEP 2 remove tmp folder
hduser@prayagupd$ sudo rm -rf /app/hadoop/tmp/
STEP 3 create /app/hadoop/tmp/
hduser@prayagupd$ sudo mkdir -p /app/hadoop/tmp
hduser@prayagupd$ sudo chown hduser:hadoop /app/hadoop/tmp
hduser@prayagupd$ sudo chmod 750 /app/hadoop/tmp
STEP 4 format namenode
hduser@prayagupd$ hdfs namenode -format
STEP 5 start dfs
hduser@prayagupd$ /usr/local/hadoop-2.2.0/sbin/start-dfs.sh
STEP 6 check jps
hduser@prayagupd$ $ jps
11342 Jps
10804 DataNode
11110 SecondaryNameNode
10558 NameNode
From: jQuery text truncation (read more style)
Try this:
var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
.split(" ").slice(0, -1).join(" ") + "...";
And you can also use a plugin:
As a extension of String
String.prototype.trimToLength = function(m) {
return (this.length > m)
? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
: this;
};
Use as
"This is your title".trimToLength(10);
Express version:
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
}
Optional parameter are very much handy, you can declare and use them easily using express:
app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
console.log("category Id: "+req.params.cId);
console.log("product ID: "+req.params.pId);
if (req.params.batchNo){
console.log("Batch No: "+req.params.batchNo);
}
});
In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'
Now I can call with only categoryId and productId or with all three-parameter.
http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987
This works in Mac as well you can use
df= pd.read_csv('Region_count.csv', encoding ='latin1')
Lists are mutable. whereas tuples are immutable. Accessing an offset element with index makes more sense in tuples than lists, Because the elements and their index cannot be changed.
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind
functions to each result callback; the order of parameters is: (success, failure)
. So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: @get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401
You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().
however, Integer objects are immutable; my strategy would be to iterate through the set and for each Integer i, add i+1 to some new temporary set. When you are finished iterating, remove all the elements from the original set and add all the elements of the new temporary set.
Set<Integer> s; //contains your Integers
...
Set<Integer> temp = new Set<Integer>();
for(Integer i : s)
temp.add(i+1);
s.clear();
s.addAll(temp);
You should use doGet()
when you want to intercept on HTTP GET requests. You should use doPost()
when you want to intercept on HTTP POST requests. That's all. Do not port the one to the other or vice versa (such as in Netbeans' unfortunate auto-generated processRequest()
method). This makes no utter sense.
Usually, HTTP GET requests are idempotent. I.e. you get exactly the same result everytime you execute the request (leaving authorization/authentication and the time-sensitive nature of the page —search results, last news, etc— outside consideration). We can talk about a bookmarkable request. Clicking a link, clicking a bookmark, entering raw URL in browser address bar, etcetera will all fire a HTTP GET request. If a Servlet is listening on the URL in question, then its doGet()
method will be called. It's usually used to preprocess a request. I.e. doing some business stuff before presenting the HTML output from a JSP, such as gathering data for display in a table.
@WebServlet("/products")
public class ProductsServlet extends HttpServlet {
@EJB
private ProductService productService;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = productService.list();
request.setAttribute("products", products); // Will be available as ${products} in JSP
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
}
}
Note that the JSP file is explicitly placed in /WEB-INF
folder in order to prevent endusers being able to access it directly without invoking the preprocessing servlet (and thus end up getting confused by seeing an empty table).
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.name}</td>
<td><a href="product?id=${product.id}">detail</a></td>
</tr>
</c:forEach>
</table>
Also view/edit detail links as shown in last column above are usually idempotent.
@WebServlet("/product")
public class ProductServlet extends HttpServlet {
@EJB
private ProductService productService;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Product product = productService.find(request.getParameter("id"));
request.setAttribute("product", product); // Will be available as ${product} in JSP
request.getRequestDispatcher("/WEB-INF/product.jsp").forward(request, response);
}
}
<dl>
<dt>ID</dt>
<dd>${product.id}</dd>
<dt>Name</dt>
<dd>${product.name}</dd>
<dt>Description</dt>
<dd>${product.description}</dd>
<dt>Price</dt>
<dd>${product.price}</dd>
<dt>Image</dt>
<dd><img src="productImage?id=${product.id}" /></dd>
</dl>
HTTP POST requests are not idempotent. If the enduser has submitted a POST form on an URL beforehand, which hasn't performed a redirect, then the URL is not necessarily bookmarkable. The submitted form data is not reflected in the URL. Copypasting the URL into a new browser window/tab may not necessarily yield exactly the same result as after the form submit. Such an URL is then not bookmarkable. If a Servlet is listening on the URL in question, then its doPost()
will be called. It's usually used to postprocess a request. I.e. gathering data from a submitted HTML form and doing some business stuff with it (conversion, validation, saving in DB, etcetera). Finally usually the result is presented as HTML from the forwarded JSP page.
<form action="login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="login">
<span class="error">${error}</span>
</form>
...which can be used in combination with this piece of Servlet:
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@EJB
private UserService userService;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userService.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
response.sendRedirect("home");
}
else {
request.setAttribute("error", "Unknown user, please try again");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
}
You see, if the User
is found in DB (i.e. username and password are valid), then the User
will be put in session scope (i.e. "logged in") and the servlet will redirect to some main page (this example goes to http://example.com/contextname/home
), else it will set an error message and forward the request back to the same JSP page so that the message get displayed by ${error}
.
You can if necessary also "hide" the login.jsp
in /WEB-INF/login.jsp
so that the users can only access it by the servlet. This keeps the URL clean http://example.com/contextname/login
. All you need to do is to add a doGet()
to the servlet like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
(and update the same line in doPost()
accordingly)
That said, I am not sure if it is just playing around and shooting in the dark, but the code which you posted doesn't look good (such as using compareTo()
instead of equals()
and digging in the parameternames instead of just using getParameter()
and the id
and password
seems to be declared as servlet instance variables — which is NOT threadsafe). So I would strongly recommend to learn a bit more about basic Java SE API using the Oracle tutorials (check the chapter "Trails Covering the Basics") and how to use JSP/Servlets the right way using those tutorials.
Update: as per the update of your question (which is pretty major, you should not remove parts of your original question, this would make the answers worthless .. rather add the information in a new block) , it turns out that you're unnecessarily setting form's encoding type to multipart/form-data
. This will send the request parameters in a different composition than the (default) application/x-www-form-urlencoded
which sends the request parameters as a query string (e.g. name1=value1&name2=value2&name3=value3
). You only need multipart/form-data
whenever you have a <input type="file">
element in the form to upload files which may be non-character data (binary data). This is not the case in your case, so just remove it and it will work as expected. If you ever need to upload files, then you'll have to set the encoding type so and parse the request body yourself. Usually you use the Apache Commons FileUpload there for, but if you're already on fresh new Servlet 3.0 API, then you can just use builtin facilities starting with HttpServletRequest#getPart()
. See also this answer for a concrete example: How to upload files to server using JSP/Servlet?
You can't do something like that: (int(sumall[0])+int(sumall[1]))
That's because sumall
is an int
and not a list or dict.
So, summ + sumd
will be you're lucky number
I had the same problem but we can use the time zone we want
we use .toLocaleDateString()
eg:
var day=new Date();
const options= {day:'numeric', month:'long', year:"numeric", timeZone:"Asia/Kolkata"};
const today=day.toLocaleDateString("en-IN", options);
console.log(today);
_x000D_
Today I faced with this problem. I used Android Studio 2.1.3, windows 10. While debugging it works fine, but if I update to release mode it does not work. I cleared all proguard conditions, updated, but this was not solution.
The solution is related with project structure. The google_maps_api.xml file was different between app\src\debug\res and app\src\release\res. I did manual copy paste from debug to release folder.
Now it works.
Just use this code:
SwingUtilities.getRootPane(myButton).setDefaultButton(myButton);
Check out Effective Java, 2nd edition page 27. Item 7: Avoid finalizers
Finalizers are unpredictable, often dangerous, and generally unnecessary. never do anything time-critical in a finalizer. never depend on a finalizer to update critical persistent state.
To terminate a resource, use try-finally instead:
// try-finally block guarantees execution of termination method Foo foo = new Foo(...); try { // Do what must be done with foo ... } finally { foo.terminate(); // Explicit termination method }
I would recommend checking out Otto, an EventBus tailored specifically to Android. Your Activity/UI can listen to events posted on the Bus from the Service, and decouple itself from the backend.
In this case I think you need transform the date to UNIX timestamp
timestamp = testDate.getTime();
strJson = JSON.stringify(timestamp);
After that you can re use it to create a date object and format it. Example with javascript and toLocaleDateString
( https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/toLocaleDateString )
newDateObject = new Date(JSON.parse(strJson));
newDateObject = newDateObject.toLocalDateStrin([
"fr-FR",
]);
If you use stringify to use AJAX, now it's not useful. You just need to send timestamp and get it in your script:
$newDateObject = new \DateTime();
$newDateObject->setTimestamp(round($timestamp/1000));
Be aware that getTime()
will return a time in milliseconds and the PHP function setTimestamp
take time in seconds. It's why you need to divide by 1000 and round
.
This error is common when the source table contains a TEXT column and the target is anything other than a TEXT column. It can be a real time-eater if you have not encountered (or forgot!) this before.
Convert the text column to string and set the error condition on truncation to ignore. this will usually serve as a solution for this error.
If you don't want to use a global object like window or global (node), you can try something like this:
var obj = {};
obj['whatever'] = 'There\'s no need to store even more stuff in a global object.';
console.log(obj['whatever']);
For windows :
Package.json
"scripts": {
"start": "nodemon app.js",
"test": "mocha"
},
then run the command
npm run test
The another way to do it, is using the INHERITS
component. For example:
CREATE TABLE person (
id int ,
name varchar(20),
CONSTRAINT pessoa_pkey PRIMARY KEY (id)
);
CREATE TABLE natural_person (
social_security_number varchar(11),
CONSTRAINT pessoaf_pkey PRIMARY KEY (id)
) INHERITS (person);
CREATE TABLE juridical_person (
tin_number varchar(14),
CONSTRAINT pessoaj_pkey PRIMARY KEY (id)
) INHERITS (person);
Thus it's possible to define a inheritance between tables.
I believe .clone()
is what you're looking for, so long as the class supports it.
Here is simple way using HTML5 and jQuery:
1) include two JS file
<script src="jslibs/jquery.js" type="text/javascript"></script>
<script src="jslibs/ajaxupload-min.js" type="text/javascript"></script>
2) include CSS to have cool buttons
<link rel="stylesheet" href="css/baseTheme/style.css" type="text/css" media="all" />
3) create DIV or SPAN
<div class="demo" > </div>
4) write this code in your HTML page
$('.demo').ajaxupload({
url:'upload.php'
});
5) create you upload.php file to have PHP code to upload data.
You can download required JS file from here Here is Example
Its too cool and too fast And easy too! :)
if (!String.prototype.hasOwnProperty('addSlashes')) {
String.prototype.addSlashes = function() {
return this.replace(/&/g, '&') /* This MUST be the 1st replacement. */
.replace(/'/g, ''') /* The 4 other predefined entities, required. */
.replace(/"/g, '"')
.replace(/\\/g, '\\\\')
.replace(/</g, '<')
.replace(/>/g, '>').replace(/\u0000/g, '\\0');
}
}
Usage: alert(str.addSlashes());
You can check with this command systemctl status docker
it will show the status of the docker. If you want to start you can use systemctl start docker
instead of systemctl
you can try also with service
, service docker status
and service docker start
respectively.
If you include the input tag in the label tag, you don't need to use the 'for' attribute.
That said, I don't like to include the input tag in my labels because I think they're separate, not containing, entities.
I guess you're wondering why C or C++ lets you manipulate an object pointer like a number, but you can't manipulate an object reference in Java the same way.
Object references in Java aren't like pointers in C or C++... Pointers basically are integers and you can manipulate them like any other int. References are intentionally a more concrete abstraction and cannot be manipulated the way pointers can.
$("#list li").click(function() {
var selected = $(this).html();
alert(selected);
});
Didn't see this here
System.Web.HttpUtility.JavaScriptStringEncode("Hello, this is Satan's Site")
it was the only thing that worked (asp 4.0+) when dealing with html like this. The'
gets rendered as '
(using htmldecode) in the html, causing it to fail:
<a href="article.aspx?id=268" onclick="tabs.open('modules/xxx/id/268', 'It's Allstars'); return false;">It's Allstars</a>
There is nothing particularly tricky about the example you posted.
In a ternary operator, the first argument (the conditional) is evaluated and if the result is true
, the second argument is evaluated and returned, otherwise, the third is evaluated and returned. Each of those arguments can be any valid code block, including function calls.
Think of it this way:
var x = (1 < 2) ? true : false;
Could also be written as:
var x = (1 < 2) ? getTrueValue() : getFalseValue();
This is perfectly valid, and those functions can contain any arbitrary code, whether it is related to returning a value or not. Additionally, the results of the ternary operation don't have to be assigned to anything, just as function results do not have to be assigned to anything:
(1 < 2) ? getTrueValue() : getFalseValue();
Now simply replace those with any arbitrary functions, and you are left with something like your example:
(1 < 2) ? removeItem($this) : addItem($this);
Now your last example really doesn't need a ternary at all, as it can be written like this:
x = (1 < 2); // x will be set to "true"
By default the rotation point is the Canvas's (0,0) point, and my guess is that you may want to rotate it around the center. I did that:
protected void renderImage(Canvas canvas)
{
Rect dest,drawRect ;
drawRect = new Rect(0,0, mImage.getWidth(), mImage.getHeight());
dest = new Rect((int) (canvas.getWidth() / 2 - mImage.getWidth() * mImageResize / 2), // left
(int) (canvas.getHeight()/ 2 - mImage.getHeight()* mImageResize / 2), // top
(int) (canvas.getWidth() / 2 + mImage.getWidth() * mImageResize / 2), //right
(int) (canvas.getWidth() / 2 + mImage.getHeight()* mImageResize / 2));// bottom
if(!mRotate) {
canvas.drawBitmap(mImage, drawRect, dest, null);
} else {
canvas.save(Canvas.MATRIX_SAVE_FLAG); //Saving the canvas and later restoring it so only this image will be rotated.
canvas.rotate(90,canvas.getWidth() / 2, canvas.getHeight()/ 2);
canvas.drawBitmap(mImage, drawRect, dest, null);
canvas.restore();
}
}
This is what I put as a menu option where I made a button on a JFrame
to display another JFrame
. I wanted only the new frame to be visible, and not to destroy the one behind it. I initially hid the first JFrame
, while the new one became visible. Upon closing of the new JFrame
, I disposed of it followed by an action of making the old one visible again.
Note: The following code expands off of Ravinda's answer and ng
is a JButton
:
ng.addActionListener((ActionEvent e) -> {
setVisible(false);
JFrame j = new JFrame("NAME");
j.setVisible(true);
j.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
setVisible(true);
}
});
});
Write yourself a Helper function:
public static bool IsBewteenTwoDates(this DateTime dt, DateTime start, DateTime end)
{
return dt >= start && dt <= end;
}
Then call: .IsBewteenTwoDates(DateTime.Today ,new DateTime(,,));
You can use the UUID class with its getLeastSignificantBits() message to get 64 bit of random data, and then convert it to a radix 36 number (i.e. a string consisting of 0-9,A-Z):
Long.toString(Math.abs( UUID.randomUUID().getLeastSignificantBits(), 36));
This yields a string up to 13 characters long. We use Math.abs() to make sure there isn't a minus sign sneaking in.
jspdf does not work with css but it can work along with html2canvas. You can use jspdf along with html2canvas.
include these two files in script on your page :
<script type="text/javascript" src="html2canvas.js"></script>
<script type="text/javascript" src="jspdf.min.js"></script>
<script type="text/javascript">
function genPDF()
{
html2canvas(document.body,{
onrendered:function(canvas){
var img=canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img,'JPEG',20,20);
doc.save('test.pdf');
}
});
}
</script>
You need to download script files such as https://github.com/niklasvh/html2canvas/releases https://cdnjs.com/libraries/jspdf
make clickable button on page so that it will generate pdf and it will be seen same as that of original html page.
<a href="javascript:genPDF()">Download PDF</a>
It will work perfectly.
You can write your own function that returns an array of bits. Example how to convert number to bits
example of above line: 2 * 4 = 8 and remainder is 1 so 9 = 1 0 0 1
function numToBit(num){
var number = num
var result = []
while(number >= 1 ){
result.unshift(Math.floor(number%2))
number = number/2
}
return result
}
Read remainders from bottom to top. Digit 1 in the middle to top.
You can use \centering
with your parbox to do this.
(Sorry for the Google cached link; the original one I had doesn't work anymore.)
I want to mention some other scenario when the real-time is much much bigger than user + sys. I've created a simple server which respondes after a long time
real 4.784
user 0.01s
sys 0.01s
the issue is that in this scenario the process waits for the response which is not on the user site nor in the system.
Something similar happens when you run the find
command. In that case, the time is spent mostly on requesting and getting a response from SSD.
Any subobjects will not be reloaded by this, I believe you have to use IPython's deepreload for that.
Some of the other answers are great for removing zeros from existing data, but if you have a working sheet that is constantly changed and want to prevent zeros from ever appearing, I find it's easiest to use conditional formatting to make them invisible. Just select the range of cells you want to apply it to > conditional formatting > new rule.
Change the rule type to "format only cells that contain" Cell value > equal to > 0.
Under "Format" change the text colour to white or whatever your background happens to be, and all cells which contain exactly zero will disappear.
Obviously this also works with any other value you want to make disappear.
Keith's answer is great - I just want to point out that because Cocoapods 0.36 is starting to support Dynamic Frameworks, if you are using 'use_frameworks!' in your 'Podfile' and you wish to remove the Cocoapods, you must do this:
Build Phases
delete Embed Pods Frameworks
phase.I have solved the issue by using UINavigationController when presenting. In MainVC, when presenting VC1
let vc1 = VC1()
let navigationVC = UINavigationController(rootViewController: vc1)
self.present(navigationVC, animated: true, completion: nil)
In VC1, when I would like to show VC2 and dismiss VC1 in same time (just one animation), I can have a push animation by
let vc2 = VC2()
self.navigationController?.setViewControllers([vc2], animated: true)
And in VC2, when close the view controller, as usual we can use:
self.dismiss(animated: true, completion: nil)
Below the more general templated solution to which Ian referred...
#include <map>
template<typename Key, typename Value>
using Map = std::map<Key, Value>;
template<typename Key, typename Value>
using MapIterator = typename Map<Key, Value>::iterator;
template<typename Key, typename Value>
class MapKeyIterator : public MapIterator<Key, Value> {
public:
MapKeyIterator ( ) : MapIterator<Key, Value> ( ) { };
MapKeyIterator ( MapIterator<Key, Value> it_ ) : MapIterator<Key, Value> ( it_ ) { };
Key *operator -> ( ) { return ( Key * const ) &( MapIterator<Key, Value>::operator -> ( )->first ); }
Key operator * ( ) { return MapIterator<Key, Value>::operator * ( ).first; }
};
template<typename Key, typename Value>
class MapValueIterator : public MapIterator<Key, Value> {
public:
MapValueIterator ( ) : MapIterator<Key, Value> ( ) { };
MapValueIterator ( MapIterator<Key, Value> it_ ) : MapIterator<Key, Value> ( it_ ) { };
Value *operator -> ( ) { return ( Value * const ) &( MapIterator<Key, Value>::operator -> ( )->second ); }
Value operator * ( ) { return MapIterator<Key, Value>::operator * ( ).second; }
};
All credits go to Ian... Thanks Ian.
For SublimeText 3 on Mac:
# .jshintrc
{
"esversion": 6
}
// SublimeLinter Settings - User
{
"linters": {
"jshint": {
"args": ["--config", "/Users/[your_username]/.jshintrc"]
}
}
}
Seems like at least 10 questions rolled into one here, a couple points.
Response.Clear - it really depends on what else is going on in the app - if you have httpmodules early in the pipeline that might be writing stuff you don't want - then clear it. Test it and find out. Fiddler or Wireshark useful for this.
Content Type to text/xml - yup - good idea - read up on HTTP spec as to why this is important. IMO anyone doing web work should have read the 1.0 and 1.1 spec at least once.
Encoding - how is your xml encoded - if it is utf-8, then say so, if not, say something else appropriate, just make sure they all match.
Page - personally, would use ashx or httpmodule, if you are using page, and want it a bit faster, get rid of autoeventwireup and bind the event handlers manually.
Would probably be a bit of a waste of memory to dump the xml into a string first, but it depends a lot on the size of the xml as to whether you would ever notice.
As others have suggested, saving the xml to the output stream probably the fastest, I would normally do that, but if you aren't sure, test it, don't rely on what you read on the interweb. Don't just believe anything I say.
For another approach, if the xml doesn't change that much, you could just write it to the disk and serve the file directly, which would likely be quite performant, but like everything in programming, it depends...
There are three methods of passing an object to a function as a parameter:
Go through the following example:
class Sample
{
public:
int *ptr;
int mVar;
Sample(int i)
{
mVar = 4;
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value of the pointer is " << *ptr << endl
<< "The value of the variable is " << mVar;
}
};
void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}
int main()
{
Sample s1= 10;
SomeFunc(s1);
s1.PrintVal();
char ch;
cin >> ch;
}
Output:
Say i am in someFunc
The value of the pointer is -17891602
The value of the variable is 4
I would do this
var a = someCondition ? { b: 5 } : {};
Edited with one line code version
Two options here:
Replace ifPresent
with map
and use Function
instead of Consumer
private String getStringIfObjectIsPresent(Optional<Object> object) {
return object
.map(obj -> {
String result = "result";
//some logic with result and return it
return result;
})
.orElseThrow(MyCustomException::new);
}
Use isPresent
:
private String getStringIfObjectIsPresent(Optional<Object> object) {
if (object.isPresent()) {
String result = "result";
//some logic with result and return it
return result;
} else {
throw new MyCustomException();
}
}
A lot of the answers on this page only apply to a single cell, and OP asked for all the selected cells.
If all you want is the cell contents, and you don't care about references to the actual cells that are selected, you can just do this:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SelectedThings As String = DataGridView1.GetClipboardContent().GetText().Replace(ChrW(9), ",")
TextBox1.Text = SelectedThings
End Sub
When Button1
is clicked, this will fill TextBox1
with the comma-separated values of the selected cells.
If you want all the configuration files loaded, this is will tell you:
php -i | grep "\.ini"
Some systems load things from more than one ini file. On my ubuntu system, it looks like this:
$ php -i | grep "\.ini"
Configuration File (php.ini) Path => /etc/php5/cli
Loaded Configuration File => /etc/php5/cli/php.ini
Scan this dir for additional .ini files => /etc/php5/cli/conf.d
additional .ini files parsed => /etc/php5/cli/conf.d/apc.ini,
/etc/php5/cli/conf.d/curl.ini,
/etc/php5/cli/conf.d/gd.ini,
/etc/php5/cli/conf.d/mcrypt.ini,
/etc/php5/cli/conf.d/memcache.ini,
/etc/php5/cli/conf.d/mysql.ini,
/etc/php5/cli/conf.d/mysqli.ini,
/etc/php5/cli/conf.d/pdo.ini,
/etc/php5/cli/conf.d/pdo_mysql.ini
I'm agree with Spence (+1), but if you're doing it for learning or testing pourposes, you can use a foreach in the string, appending each char to the securestring using the AppendChar method.
http://en.wikipedia.org/wiki/Database_transaction
http://en.wikipedia.org/wiki/ACID
ACID = Atomicity, Consistency, Isolation, Durability
When you wish for multiple transactional resources to be involved in a single transaction, you will need to use something like a two-phase commit solution. XA is quite widely supported.
In PostgreSQL 9.6, there's a new option idle_in_transaction_session_timeout
which should accomplish what you describe. You can set it using the SET
command, e.g.:
SET SESSION idle_in_transaction_session_timeout = '5min';
You are printing the enum object. Use the .value
attribute if you wanted just to print that:
print(D.x.value)
See the Programmatic access to enumeration members and their attributes section:
If you have an enum member and need its name or value:
>>> >>> member = Color.red >>> member.name 'red' >>> member.value 1
You could add a __str__
method to your enum, if all you wanted was to provide a custom string representation:
class D(Enum):
def __str__(self):
return str(self.value)
x = 1
y = 2
Demo:
>>> from enum import Enum
>>> class D(Enum):
... def __str__(self):
... return str(self.value)
... x = 1
... y = 2
...
>>> D.x
<D.x: 1>
>>> print(D.x)
1
In addition, you can find column name with specified schema also.
SELECT 'DBName' as DBName, COLUMN_NAME, TABLE_NAME, TABLE_SCHEMA
FROM DBName.INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%YourColumnName%' and TABLE_SCHEMA IN ('YourSchemaName')
You can also find same column on multiple database.
SELECT 'DBName1' as DB, COLUMN_NAME, TABLE_NAME, TABLE_SCHEMA
FROM DBName1.INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%YourColumnName%'
UNION
SELECT 'DBName2' as DB, COLUMN_NAME, TABLE_NAME, TABLE_SCHEMA
FROM DBName2.INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%YourColumnName%'
Well, this solution might sound very silly, but can save you in certain conditions.
A friend of mine just ran into accidentally committing very some huge files (four auto-generated files ranging between 3GB to 5GB each) and then made some additional code commits on top of that before realizing the problem that git push
wasn't working any longer!
The files had been listed in .gitignore
but after renaming the container folder, they got exposed and committed! And now there were a few more commits of the code on top of that, but push
was running forever (trying to upload GB of data!) and finally would fail due to Github's file size limits.
The problem with interactive rebase or anything similar was that they would deal with poking around these huge files and would take forever to do anything. Nevertheless, after spending almost an hour in the CLI, we weren't sure if the files (and deltas) are actually removed from the history or simply not included in the current commits. The push wasn't working either and my friend was really stuck.
So, the solution I came up with was:
~/Project-old
.~/Project
). cp -r
the files from ~/Project-old
folder to ~/Project
. mv
ed, and included in .gitignore
properly. .git
folder in the recently-cloned ~/Project
by the old one. That's where the logs of the problematic history lives!push
'ed.The biggest problem with this solution is, it deals with manual copying some files, and also it merges all the recent commits into one (obviously with a new commit-hash.) B
The big benefits are that, it is very clear in every step, it works great for huge files (as well as sensitive ones), and it doesn't leave any trace in history behind!
Upgrade the Microsoft.Net.Compilers Nuget package to the latest version (at least 2.x)
from PIL import Image
image_file = Image.open("convert_image.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('result.png')
yields
You could always check out JMF (Java Media Framework). It is pretty old and abandoned, but it works and I've used it for apps before. Looks like it handles what you're asking for.
I found that using the latest version will fix this problem:
http://code.jquery.com/jquery-git.js
This answer didn't work for me, I needed to run html decode on the string also. See
iconv('UTF-8', 'windows-1252', html_entity_decode($str));
Props go to emfi from html_entity_decode in FPDF(using tFPDF extention)
You've got "Bad Status" its because the target file cannot find or not present, like for example you call README file which is not in the current directory.
an Eclipse Plugin for automatically adding Javadoc and file headers to your source code. It optionally generates initial comments from element name by using Velocity templates for Javadoc and file headers...
Goodrich and Tamassia computed from over 50,000 English words (formed as the union of the word lists provided in two variants of Unix) that using the constants 31, 33, 37, 39, and 41 will produce fewer than 7 collisions in each case. This may be the reason that so many Java implementations choose such constants.
See section 9.2 Hash Tables (page 522) of Data Structures and Algorithms in Java.
Here is a client side "sequential guid" solution.
http://www.pinvoke.net/default.aspx/rpcrt4.uuidcreate
using System;
using System.Runtime.InteropServices;
namespace MyCompany.MyTechnology.Framework.CrossDomain.GuidExtend
{
public static class Guid
{
/*
Original Reference for Code:
http://www.pinvoke.net/default.aspx/rpcrt4/UuidCreateSequential.html
*/
[DllImport("rpcrt4.dll", SetLastError = true)]
static extern int UuidCreateSequential(out System.Guid guid);
public static System.Guid NewGuid()
{
return CreateSequentialUuid();
}
public static System.Guid CreateSequentialUuid()
{
const int RPC_S_OK = 0;
System.Guid g;
int hr = UuidCreateSequential(out g);
if (hr != RPC_S_OK)
throw new ApplicationException("UuidCreateSequential failed: " + hr);
return g;
}
/*
Text From URL above:
UuidCreateSequential (rpcrt4)
Type a page name and press Enter. You'll jump to the page if it exists, or you can create it if it doesn't.
To create a page in a module other than rpcrt4, prefix the name with the module name and a period.
. Summary
Creates a new UUID
C# Signature:
[DllImport("rpcrt4.dll", SetLastError=true)]
static extern int UuidCreateSequential(out Guid guid);
VB Signature:
Declare Function UuidCreateSequential Lib "rpcrt4.dll" (ByRef id As Guid) As Integer
User-Defined Types:
None.
Notes:
Microsoft changed the UuidCreate function so it no longer uses the machine's MAC address as part of the UUID. Since CoCreateGuid calls UuidCreate to get its GUID, its output also changed. If you still like the GUIDs to be generated in sequential order (helpful for keeping a related group of GUIDs together in the system registry), you can use the UuidCreateSequential function.
CoCreateGuid generates random-looking GUIDs like these:
92E60A8A-2A99-4F53-9A71-AC69BD7E4D75
BB88FD63-DAC2-4B15-8ADF-1D502E64B92F
28F8800C-C804-4F0F-B6F1-24BFC4D4EE80
EBD133A6-6CF3-4ADA-B723-A8177B70D268
B10A35C0-F012-4EC1-9D24-3CC91D2B7122
UuidCreateSequential generates sequential GUIDs like these:
19F287B4-8830-11D9-8BFC-000CF1ADC5B7
19F287B5-8830-11D9-8BFC-000CF1ADC5B7
19F287B6-8830-11D9-8BFC-000CF1ADC5B7
19F287B7-8830-11D9-8BFC-000CF1ADC5B7
19F287B8-8830-11D9-8BFC-000CF1ADC5B7
Here is a summary of the differences in the output of UuidCreateSequential:
The last six bytes reveal your MAC address
Several GUIDs generated in a row are sequential
Tips & Tricks:
Please add some!
Sample Code in C#:
static Guid UuidCreateSequential()
{
const int RPC_S_OK = 0;
Guid g;
int hr = UuidCreateSequential(out g);
if (hr != RPC_S_OK)
throw new ApplicationException
("UuidCreateSequential failed: " + hr);
return g;
}
Sample Code in VB:
Sub Main()
Dim myId As Guid
Dim code As Integer
code = UuidCreateSequential(myId)
If code <> 0 Then
Console.WriteLine("UuidCreateSequential failed: {0}", code)
Else
Console.WriteLine(myId)
End If
End Sub
*/
}
}
Keywords: CreateSequentialUUID SequentialUUID
In the latest version of pandas (0.19.2
) you can directly pass the url
import pandas as pd
url="https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"
c=pd.read_csv(url)
If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening. By default, SQL server doesn't enable this after installation.
Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).
Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.
I had an issue with multiple slides. version 1.8.1
if slidesToShow
and slidesToScroll
more than 1
trick is in slick.slickGetOption('slidesToShow');
$(".your-selector").on('init reInit afterChange', function(event, slick, currentSlide, nextSlide){
var i = (currentSlide ? currentSlide : 0) + 1;
var slidesToShow = slick.slickGetOption('slidesToShow');
var curPage = parseInt((i-1)/slidesToShow) + 1;
var lastPage = parseInt((slick.slideCount-1)/slidesToShow) + 1;
$('.your-selector').text(curPage);
$('.your-selector').text(lastPage);
});
Note curPage
and lastPage
is separate. I had to color them differently.
Based on top-voted answer
In python3 the following works:
>>> v=10.4
>>> print('% 6.2f' % v)
10.40
>>> print('% 12.1f' % v)
10.4
>>> print('%012.1f' % v)
0000000010.4
The reason may be that watcher is declared as local variable to a method and it is garbage collected when the method finishes. You should declare it as a class member. Try the following:
FileSystemWatcher watcher;
private void watch()
{
watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
//Copies file to another directory.
}
Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.
It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.
Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart
and touchmove
handlers, which may prevent the scroll entirely by calling preventDefault()
on the event.
Solution: {passive: true}
By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault
to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user
.
document.addEventListener("touchstart", function(e) {
console.log(e.defaultPrevented); // will be false
e.preventDefault(); // does nothing since the listener is passive
console.log(e.defaultPrevented); // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
I know this is an old post but I had the same question but didn't find an answer that set the element fixed relative to a parent div
. The scroll bar on medium.com is a great pure CSS solution for setting something position: fixed;
relative to a parent element instead of the viewport (kinda*). It is achieved by setting the parent div
to position: relative;
and having a button wrapper with position: absolute;
and the button of course is position: fixed;
as follows:
<div class="wrapper">
<div class="content">
Your long content here
</div>
<div class="button-wrapper">
<button class="button">This is your button</button>
</div>
</div>
<style>
.wrapper {
position: relative;
}
.button-wrapper {
position: absolute;
right: 0;
top: 0;
width: 50px;
}
.button {
position: fixed;
top: 0;
width: 50px;
}
</style>
*Since fixed elements don't scroll with the page the vertical position will still be relative to the viewport but the horizontal position is relative to the parent with this solution.
{ "scripts" :
{ "build": "node build.js"}
}
npm run build
ORnpm run-script build
{
"name": "build",
"version": "1.0.0",
"scripts": {
"start": "node build.js"
}
}
npm start
NB: you were missing the
{ brackets }
and the node command
folder structure is fine:
+ build
- package.json
- build.js
This should help:
document.getElementById('FrameID').contentWindow.location.reload(true);
EDIT: Fixed the object name as per @Joro's comment.
How about this :)
.fixed-centered-covers-entire-page{_x000D_
margin:auto;_x000D_
background-image: url('https://i.imgur.com/Ljd0YBi.jpg');_x000D_
background-repeat: no-repeat;background-size:cover;_x000D_
background-position: 50%;_x000D_
background-color: #fff;_x000D_
left:0;_x000D_
right:0;_x000D_
top:0;_x000D_
bottom:0;_x000D_
z-index:-1;_x000D_
position:fixed;_x000D_
}
_x000D_
<div class="fixed-centered-covers-entire-page"></div>
_x000D_
First of all i will say Nice Thaught to develop such app.
Now i am not sure about it, but if you can able to get the face-detection like thing for any object in android camera so with help of that you can achieve that things.
Well i am not sure about it but still have give some view so you can get idea of it.
All the Best. :))
You need to set basicHttpBinding -> MaxReceivedMessageSize in the client configuration.
I really liked @brettdj's code, but then I found that when I added additional code to edit the copy, it overwrote my original sheet instead. I've tweaked his answer so that further code pointed at ws1
will affect the new sheet rather than the original.
Sub Test()
Dim ws1 as Worksheet
ThisWorkbook.Worksheets("Master").Copy
Set ws1 = ThisWorkbook.Worksheets("Master (2)")
End Sub
Here it is:
s = "123"
try:
i = int(s)
except ValueError as verr:
pass # do job to handle: s does not contain anything convertible to int
except Exception as ex:
pass # do job to handle: Exception occurred while converting to int
You can try something like this:
class mylist(list):
def __sub__(self, b):
result = self[:]
b = b[:]
while b:
try:
result.remove(b.pop())
except ValueError:
raise Exception("Not all elements found during subtraction")
return result
a = mylist([0, 1, 2, 1, 0] )
b = mylist([0, 1, 1])
>>> a - b
[2, 0]
You have to define what [1, 2, 3] - [5, 6] should output though, I guess you want [1, 2, 3] thats why I ignore the ValueError.
Edit:
Now I see you wanted an exception if a
does not contain all elements, added it instead of passing the ValueError.
It's somewhat weird to read but yes, the exception will bubble up to the calling code - but only if you await
or Wait()
the call to Foo
.
public async Task Foo()
{
var x = await DoSomethingAsync();
}
public async void DoFoo()
{
try
{
await Foo();
}
catch (ProtocolException ex)
{
// The exception will be caught because you've awaited
// the call in an async method.
}
}
//or//
public void DoFoo()
{
try
{
Foo().Wait();
}
catch (ProtocolException ex)
{
/* The exception will be caught because you've
waited for the completion of the call. */
}
}
Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. - https://msdn.microsoft.com/en-us/magazine/jj991977.aspx
Note that using Wait() may cause your application to block, if .Net decides to execute your method synchronously.
This explanation http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions is pretty good - it discusses the steps the compiler takes to achieve this magic.
Unrelated to the original question, but because this is the first Google result... I hit this on Google AppEngine and had to add:
libraries:
- name: ssl
version: latest
to app.yaml per: https://cloud.google.com/appengine/docs/python/sockets/ssl_support
Please NOTE: This seems to work upto Python version 2.7.9 but not for 2.7.10 or 2.7.11.
if you have a context, i mean inside;
public void onReceive(Context context, Intent intent){
}
you can use this code to get resources:
context.getResources().getString(R.string.app_name);
In WSDL, if you look at the Binding section, you will clearly see that soap binding is explicitly mentioned if the service uses soap 1.2. refer the below sample.
<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="findEmployeeById">
<soap12:operation soapAction=""/>
<input><soap12:body use="literal"/></input>
<output><soap12:body use="literal"/></output>
</operation><operation name="create">
<soap12:operation soapAction=""/>
<input><soap12:body use="literal"/></input>
<output><soap12:body use="literal"/></output>
</operation>
</binding>
if the web service use soap 1.1, it will not explicitly define any soap version in the WSDL file under binding section. refer the below sample.
<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
<operation name="findEmployeeById">
<soap:operation soapAction=""/>
<input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
<output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation><operation name="create">
<soap:operation soapAction=""/>
<input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
<output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation>
</binding>
How to determine the SOAP version of the SOAP message?
but remember that this is not much recommended way to determine the soap version that your web services uses. the version of the soap message can be determined using one of following ways.
1. checking the namespace of the soap message
SOAP 1.1 namespace : http://schemas.xmlsoap.org/soap/envelope
SOAP 1.2 namespace : http://www.w3.org/2003/05/soap-envelope
2. checking the transport binding information (http header information) of the soap message
SOAP 1.1 : user text/xml for the Context-Type
POST /MyService HTTP/1.1
Content-Type: text/xml; charset="utf-8"
Content-Length: xxx
SOAPAction: "urn:uuid:myaction"
SOAP 1.2 : user application/soap+xml for the Context-Type
POST /MyService HTTP/1.1
Content-Type: application/soap+xml; charset="utf-8"
Content-Length: xxx
SOAPAction: "urn:uuid:myaction"
3. using SOAP fault information
The structure of a SOAP fault message between the two versions are different.
Python3:
import importlib.machinery
loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py')
handle = loader.load_module('report')
handle.mainFunction(parameter)
This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).
There's also the more normal way of importing a python module in Python3,
import importlib
module = importlib.load_module('folder.filename')
module.function()
Kudos to Sebastian for spplying a similar answer for Python2:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
Sadly, this is just another annoying quirk of using Internet Explorer.
The simple solution is to run a small .reg file on your PC, to tell IE to automatically open .json files, rather than nag about whether to open/save it.
I've put a copy of the file you'll need here:
You'll need to have Admin rights to run this.
There's another method called dump()
which can also be used for logging:
func dump<T>(T, name: String?, indent: Int, maxDepth: Int, maxItems: Int)
Dumps an object’s contents using its mirror to standard output.
For MS SQL you can do this.
select CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+
CAST(DATEPART(YEAR, DateTyme) as VARCHAR) as 'Date' from #temp
group by Name, CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+
CAST(DATEPART(YEAR, DateTyme) as VARCHAR)
Vintana,
Od course there's something ready now. http://www.devart.com/products.html - it's commercial although (you have a 30days trial IIRC). They make a living writing providers, so I guess it should be fast and stable. I know really big companies using their Oracle provider instead of Orace and MS ones.
Taking the value from Command line and showing THE INPUT IS DECIMAL/NON-DECIMAL and NUMBER or not:
NUMBER=$1
IsDecimal=`echo "$NUMBER" | grep "\."`
if [ -n "$IsDecimal" ]
then
echo "$NUMBER is Decimal"
var1=`echo "$NUMBER" | cut -d"." -f1`
var2=`echo "$NUMBER" | cut -d"." -f2`
Digit1=`echo "$var1" | egrep '^-[0-9]+$'`
Digit2=`echo "$var1" | egrep '^[0-9]+$'`
Digit3=`echo "$var2" | egrep '^[0-9]+$'`
if [ -n "$Digit1" ] && [ -n "$Digit3" ]
then
echo "$NUMBER is a number"
elif [ -n "$Digit2" ] && [ -n "$Digit3" ]
then
echo "$NUMBER is a number"
else
echo "$NUMBER is not a number"
fi
else
echo "$NUMBER is not Decimal"
Digit1=`echo "$NUMBER" | egrep '^-[0-9]+$'`
Digit2=`echo "$NUMBER" | egrep '^[0-9]+$'`
if [ -n "$Digit1" ] || [ -n "$Digit2" ]; then
echo "$NUMBER is a number"
else
echo "$NUMBER is not a number"
fi
fi
You can get the position of the last -
with str.LastIndexOf('-')
. So the next step is obvious:
var result = str.Substring(str.LastIndexOf('-') + 1);
Correction:
As Brian states below, using this on a string with no dashes will result in the same string being returned.
Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.
Having added a new view controller scene to your storyboard, you then have to:
Create a UIViewController
subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":
And then select a unique name for the new view controller subclass:
Specify this new subclass as the base class for the scene you just added to the storyboard.
Now hook up any IBOutlet
and IBAction
references for this new scene with the new view controller subclass.
your fadeIn()
function calls the fadeOut()
function, which calls the fadeIn()
function again. the recursion is in the JS.
You can generate a stack trace and use the informations in the StackTraceElements.
For example an utility class can return you the calling class name :
public class KDebug {
public static String getCallerClassName() {
StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
for (int i=1; i<stElements.length; i++) {
StackTraceElement ste = stElements[i];
if (!ste.getClassName().equals(KDebug.class.getName()) && ste.getClassName().indexOf("java.lang.Thread")!=0) {
return ste.getClassName();
}
}
return null;
}
}
If you call KDebug.getCallerClassName()
from bar()
, you'll get "foo"
.
Now supposing you want to know the class of the method calling bar
(which is more interesting and maybe what you really wanted). You could use this method :
public static String getCallerCallerClassName() {
StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
String callerClassName = null;
for (int i=1; i<stElements.length; i++) {
StackTraceElement ste = stElements[i];
if (!ste.getClassName().equals(KDebug.class.getName())&& ste.getClassName().indexOf("java.lang.Thread")!=0) {
if (callerClassName==null) {
callerClassName = ste.getClassName();
} else if (!callerClassName.equals(ste.getClassName())) {
return ste.getClassName();
}
}
}
return null;
}
Is that for debugging ? If not, there may be a better solution to your problem.
Try this, with strings:
set "var=string1string2string3"
and with string variables:
set "var=%string1%%string2%%string3%"
The whole code if somebody need it.
void alarm(Context context, Calendar calendar) {
AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
final String SOME_ACTION = "com.android.mytabs.MytabsActivity.AlarmReceiver";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
AlarmReceiver mReceiver = new AlarmReceiver();
context.registerReceiver(mReceiver, intentFilter);
Intent anotherIntent = new Intent(SOME_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, anotherIntent, 0);
alramManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(context, "Added", Toast.LENGTH_LONG).show();
}
class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
}
}
This should work for you. Infact the one which you are thinking will also work:-
.......
DECLARE @returnvalue INT
EXEC @returnvalue = SP_One
.....
You need to apply the logo
class to the image...then float the ul
HTML
<img class="logo" src="http://i.imgur.com/hCrQkJi.png">
CSS
.navigation-bar ul {
padding: 0px;
margin: 0px;
text-align: center;
float: left;
background: white;
}
The related name parameter is actually an option. If we do not set it, Django
automatically creates the other side of the relation for us. In the case of the Map model,
Django would have created a map_set
attribute, allowing access via m.map_set
in your
example(m being your class instance). The formula Django uses is the name of the model followed by the
string _set
. The related name parameter thus simply overrides Django’s default rather
than providing new behavior.
This works perfectly for me. Just put the button first since you're starting on the right. If FlowDirection becomes a problem just add a StackPanel around it and specify FlowDirection="LeftToRight" for that portion. Or simply specify FlowDirection="LeftToRight" for the relevant control.
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" FlowDirection="RightToLeft">
<Button Width="40" HorizontalAlignment="Right" Margin="3">Right</Button>
<TextBlock Margin="5">Left</TextBlock>
<StackPanel FlowDirection="LeftToRight">
<my:DatePicker Height="24" Name="DatePicker1" Width="113" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" />
</StackPanel>
<my:DatePicker FlowDirection="LeftToRight" Height="24" Name="DatePicker1" Width="113" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" />
</StackPanel>
A potentially simpler solution:
get-service "servicename*" | Where {$_.Status -eq 'Stopped'} | start-service
im building and Angular App with electron, my solution was the following:
index.html
<script>
if ( typeof module === "object" && typeof module.exports === "object" ) {
window.$ = window.jQuery = require('jquery');
}
</script>
angular.json
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
]
So Jquery gets loaded from angular.json if on browser, else if it is an electron builded app it will require module instead.
If you want to import jquery in index.html instead of importing from angular.json use the following solution:
<script src="path/to/jquery"></script>
<script>
if ( typeof module === "object" && typeof module.exports === "object" ) {
window.$ = window.jQuery = require('jquery');
}
</script>
If you want to list the indexes of all the tables in your schema(s) from your program, all the information is on hand in the catalog:
select
n.nspname as "Schema"
,t.relname as "Table"
,c.relname as "Index"
from
pg_catalog.pg_class c
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
join pg_catalog.pg_index i on i.indexrelid = c.oid
join pg_catalog.pg_class t on i.indrelid = t.oid
where
c.relkind = 'i'
and n.nspname not in ('pg_catalog', 'pg_toast')
and pg_catalog.pg_table_is_visible(c.oid)
order by
n.nspname
,t.relname
,c.relname
If you want to delve further (such as columns and ordering), you need to look at pg_catalog.pg_index. Using psql -E [dbname]
comes in handy for figuring out how to query the catalog.
The additional include directories are relative to the project dir. This is normally the dir where your project file, *.vcproj, is located. I guess that in your case you have to add just "include" to your include and library directories.
If you want to be sure what your project dir is, you can check the value of the $(ProjectDir) macro. To do that go to "C/C++ -> Additional Include Directories", press the "..." button and in the pop-up dialog press "Macros>>".
Also you can try zenity !
user=$(zenity --entry --text 'Please enter the username:') || exit 1
tonumber
takes two arguments, first is string which is converted to number and second is base of e
.
Return value tonumber
is in base 10.
If no base
is provided it converts number to base 10.
> a = '101'
> tonumber(a)
101
If base is provided, it converts it to the given base.
> a = '101'
>
> tonumber(a, 2)
5
> tonumber(a, 8)
65
> tonumber(a, 10)
101
> tonumber(a, 16)
257
>
If e
contains invalid character then it returns nil
.
> --[[ Failed because base 2 numbers consist (0 and 1) --]]
> a = '112'
> tonumber(a, 2)
nil
>
> --[[ similar to above one, this failed because --]]
> --[[ base 8 consist (0 - 7) --]]
> --[[ base 10 consist (0 - 9) --]]
> a = 'AB'
> tonumber(a, 8)
nil
> tonumber(a, 10)
nil
> tonumber(a, 16)
171
I answered considering Lua5.3
preferred way, using MySQLi extension:
$mysqli = new mysqli(SERVER, DBUSER, DBPASS, DATABASE);
$result = $mysqli->query("SELECT id FROM mytable WHERE city = 'c7'");
if($result->num_rows == 0) {
// row not found, do stuff...
} else {
// do other stuff...
}
$mysqli->close();
deprecated:
$result = mysql_query("SELECT id FROM mytable WHERE city = 'c7'");
if(mysql_num_rows($result) == 0) {
// row not found, do stuff...
} else {
// do other stuff...
}
The accepted answer is the correct command, I just want to add one additional thing, when extracting the key if you leave the PEM password("Enter PEM pass phrase:"
) blank then the complete key will not be extracted but only the localKeyID
will be extracted. To get the complete key you must specify a PEM password whem running the following command.
Please note that when it comes to Import password, you can specify the actual password for "Enter Import Password:"
or can leave this password blank:
openssl pkcs12 -in yourP12File.pfx -nocerts -out privateKey.pem
Yes, thanks to C# 7 that can be achieved. Here's how it's done (using expression pattern):
switch (o)
{
case A a:
a.Hop();
break;
case B b:
b.Skip();
break;
case C _:
return new ArgumentException("Type C will be supported in the next version");
default:
return new ArgumentException("Unexpected type: " + o.GetType());
}
You need to use \n
for linebreaks
inside textarea
Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling sys.stdout.flush()
forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.
Here's some good information about (un)buffered I/O and why it's useful:
http://en.wikipedia.org/wiki/Data_buffer
Buffered vs unbuffered IO
Yes, if you are using bootstrap, this would work.
.form-control input {
border: none;
padding-left: 4px;
}
and
<span class="form-control">$ <input type="text"/></span>
http://www.mrexcel.com/td0097.html
Dim WS as Worksheet
Set WS = Sheets.Add
You don't have to know where it's located, or what it's name is, you just refer to it as WS.
If you still want to do this the "old fashioned" way, try this:
Sheets.Add.Name = "Test"
When I had this error, it went away after I my computer crashed and restarted. Try closing and reopening your IDE, if that doesn't work, try restarting your computer. I had just installed the libraries at that point without restarting pycharm when I got this error.
Never closed PyCharm first to test because my blasted computer keeps crashing randomly... working on that one, but it at least solved this problem.. little victories.. :).
The following very efficient algorithm uses Heap's method to generate all permutations of N elements with runtime complexity in O(N!):
function permute(permutation) {_x000D_
var length = permutation.length,_x000D_
result = [permutation.slice()],_x000D_
c = new Array(length).fill(0),_x000D_
i = 1, k, p;_x000D_
_x000D_
while (i < length) {_x000D_
if (c[i] < i) {_x000D_
k = i % 2 && c[i];_x000D_
p = permutation[i];_x000D_
permutation[i] = permutation[k];_x000D_
permutation[k] = p;_x000D_
++c[i];_x000D_
i = 1;_x000D_
result.push(permutation.slice());_x000D_
} else {_x000D_
c[i] = 0;_x000D_
++i;_x000D_
}_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
console.log(permute([1, 2, 3]));
_x000D_
The same algorithm implemented as a generator with space complexity in O(N):
function* permute(permutation) {_x000D_
var length = permutation.length,_x000D_
c = Array(length).fill(0),_x000D_
i = 1, k, p;_x000D_
_x000D_
yield permutation.slice();_x000D_
while (i < length) {_x000D_
if (c[i] < i) {_x000D_
k = i % 2 && c[i];_x000D_
p = permutation[i];_x000D_
permutation[i] = permutation[k];_x000D_
permutation[k] = p;_x000D_
++c[i];_x000D_
i = 1;_x000D_
yield permutation.slice();_x000D_
} else {_x000D_
c[i] = 0;_x000D_
++i;_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
// Memory efficient iteration through permutations:_x000D_
for (var permutation of permute([1, 2, 3])) console.log(permutation);_x000D_
_x000D_
// Simple array conversion:_x000D_
var permutations = [...permute([1, 2, 3])];
_x000D_
Feel free to add your implementation to the following benchmark.js test suite:
function permute_SiGanteng(input) {_x000D_
var permArr = [],_x000D_
usedChars = [];_x000D_
_x000D_
function permute(input) {_x000D_
var i, ch;_x000D_
for (i = 0; i < input.length; i++) {_x000D_
ch = input.splice(i, 1)[0];_x000D_
usedChars.push(ch);_x000D_
if (input.length == 0) {_x000D_
permArr.push(usedChars.slice());_x000D_
}_x000D_
permute(input);_x000D_
input.splice(i, 0, ch);_x000D_
usedChars.pop();_x000D_
}_x000D_
return permArr_x000D_
}_x000D_
return permute(input);_x000D_
}_x000D_
_x000D_
function permute_delimited(inputArr) {_x000D_
var results = [];_x000D_
_x000D_
function permute(arr, memo) {_x000D_
var cur, memo = memo || [];_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
cur = arr.splice(i, 1);_x000D_
if (arr.length === 0) {_x000D_
results.push(memo.concat(cur));_x000D_
}_x000D_
permute(arr.slice(), memo.concat(cur));_x000D_
arr.splice(i, 0, cur[0]);_x000D_
}_x000D_
return results;_x000D_
}_x000D_
return permute(inputArr);_x000D_
}_x000D_
_x000D_
function permute_monkey(inputArray) {_x000D_
return inputArray.reduce(function permute(res, item, key, arr) {_x000D_
return res.concat(arr.length > 1 && arr.slice(0, key).concat(arr.slice(key + 1)).reduce(permute, []).map(function(perm) {_x000D_
return [item].concat(perm);_x000D_
}) || item);_x000D_
}, []);_x000D_
}_x000D_
_x000D_
function permute_Oriol(input) {_x000D_
var permArr = [],_x000D_
usedChars = [];_x000D_
return (function main() {_x000D_
for (var i = 0; i < input.length; i++) {_x000D_
var ch = input.splice(i, 1)[0];_x000D_
usedChars.push(ch);_x000D_
if (input.length == 0) {_x000D_
permArr.push(usedChars.slice());_x000D_
}_x000D_
main();_x000D_
input.splice(i, 0, ch);_x000D_
usedChars.pop();_x000D_
}_x000D_
return permArr;_x000D_
})();_x000D_
}_x000D_
_x000D_
function permute_MarkusT(input) {_x000D_
function permutate(array, callback) {_x000D_
function p(array, index, callback) {_x000D_
function swap(a, i1, i2) {_x000D_
var t = a[i1];_x000D_
a[i1] = a[i2];_x000D_
a[i2] = t;_x000D_
}_x000D_
if (index == array.length - 1) {_x000D_
callback(array);_x000D_
return 1;_x000D_
} else {_x000D_
var count = p(array, index + 1, callback);_x000D_
for (var i = index + 1; i < array.length; i++) {_x000D_
swap(array, i, index);_x000D_
count += p(array, index + 1, callback);_x000D_
swap(array, i, index);_x000D_
}_x000D_
return count;_x000D_
}_x000D_
}_x000D_
if (!array || array.length == 0) {_x000D_
return 0;_x000D_
}_x000D_
return p(array, 0, callback);_x000D_
}_x000D_
var result = [];_x000D_
permutate(input, function(a) {_x000D_
result.push(a.slice(0));_x000D_
});_x000D_
return result;_x000D_
}_x000D_
_x000D_
function permute_le_m(permutation) {_x000D_
var length = permutation.length,_x000D_
result = [permutation.slice()],_x000D_
c = new Array(length).fill(0),_x000D_
i = 1, k, p;_x000D_
_x000D_
while (i < length) {_x000D_
if (c[i] < i) {_x000D_
k = i % 2 && c[i],_x000D_
p = permutation[i];_x000D_
permutation[i] = permutation[k];_x000D_
permutation[k] = p;_x000D_
++c[i];_x000D_
i = 1;_x000D_
result.push(permutation.slice());_x000D_
} else {_x000D_
c[i] = 0;_x000D_
++i;_x000D_
}_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
function permute_Urielzen(arr) {_x000D_
var finalArr = [];_x000D_
var iterator = function (arrayTaken, tree) {_x000D_
for (var i = 0; i < tree; i++) {_x000D_
var temp = arrayTaken.slice();_x000D_
temp.splice(tree - 1 - i, 0, temp.splice(tree - 1, 1)[0]);_x000D_
if (tree >= arr.length) {_x000D_
finalArr.push(temp);_x000D_
} else { iterator(temp, tree + 1); }_x000D_
}_x000D_
}_x000D_
iterator(arr, 1); return finalArr;_x000D_
}_x000D_
_x000D_
function permute_Taylor_Hakes(arr) {_x000D_
var permutations = [];_x000D_
if (arr.length === 1) {_x000D_
return [ arr ];_x000D_
}_x000D_
_x000D_
for (var i = 0; i < arr.length; i++) { _x000D_
var subPerms = permute_Taylor_Hakes(arr.slice(0, i).concat(arr.slice(i + 1)));_x000D_
for (var j = 0; j < subPerms.length; j++) {_x000D_
subPerms[j].unshift(arr[i]);_x000D_
permutations.push(subPerms[j]);_x000D_
}_x000D_
}_x000D_
return permutations;_x000D_
}_x000D_
_x000D_
var Combinatorics = (function () {_x000D_
'use strict';_x000D_
var version = "0.5.2";_x000D_
/* combinatory arithmetics */_x000D_
var P = function(m, n) {_x000D_
var p = 1;_x000D_
while (n--) p *= m--;_x000D_
return p;_x000D_
};_x000D_
var C = function(m, n) {_x000D_
if (n > m) {_x000D_
return 0;_x000D_
}_x000D_
return P(m, n) / P(n, n);_x000D_
};_x000D_
var factorial = function(n) {_x000D_
return P(n, n);_x000D_
};_x000D_
var factoradic = function(n, d) {_x000D_
var f = 1;_x000D_
if (!d) {_x000D_
for (d = 1; f < n; f *= ++d);_x000D_
if (f > n) f /= d--;_x000D_
} else {_x000D_
f = factorial(d);_x000D_
}_x000D_
var result = [0];_x000D_
for (; d; f /= d--) {_x000D_
result[d] = Math.floor(n / f);_x000D_
n %= f;_x000D_
}_x000D_
return result;_x000D_
};_x000D_
/* common methods */_x000D_
var addProperties = function(dst, src) {_x000D_
Object.keys(src).forEach(function(p) {_x000D_
Object.defineProperty(dst, p, {_x000D_
value: src[p],_x000D_
configurable: p == 'next'_x000D_
});_x000D_
});_x000D_
};_x000D_
var hideProperty = function(o, p) {_x000D_
Object.defineProperty(o, p, {_x000D_
writable: true_x000D_
});_x000D_
};_x000D_
var toArray = function(f) {_x000D_
var e, result = [];_x000D_
this.init();_x000D_
while (e = this.next()) result.push(f ? f(e) : e);_x000D_
this.init();_x000D_
return result;_x000D_
};_x000D_
var common = {_x000D_
toArray: toArray,_x000D_
map: toArray,_x000D_
forEach: function(f) {_x000D_
var e;_x000D_
this.init();_x000D_
while (e = this.next()) f(e);_x000D_
this.init();_x000D_
},_x000D_
filter: function(f) {_x000D_
var e, result = [];_x000D_
this.init();_x000D_
while (e = this.next()) if (f(e)) result.push(e);_x000D_
this.init();_x000D_
return result;_x000D_
},_x000D_
lazyMap: function(f) {_x000D_
this._lazyMap = f;_x000D_
return this;_x000D_
},_x000D_
lazyFilter: function(f) {_x000D_
Object.defineProperty(this, 'next', {_x000D_
writable: true_x000D_
});_x000D_
if (typeof f !== 'function') {_x000D_
this.next = this._next;_x000D_
} else {_x000D_
if (typeof (this._next) !== 'function') {_x000D_
this._next = this.next;_x000D_
}_x000D_
var _next = this._next.bind(this);_x000D_
this.next = (function() {_x000D_
var e;_x000D_
while (e = _next()) {_x000D_
if (f(e))_x000D_
return e;_x000D_
}_x000D_
return e;_x000D_
}).bind(this);_x000D_
}_x000D_
Object.defineProperty(this, 'next', {_x000D_
writable: false_x000D_
});_x000D_
return this;_x000D_
}_x000D_
_x000D_
};_x000D_
/* power set */_x000D_
var power = function(ary, fun) {_x000D_
var size = 1 << ary.length,_x000D_
sizeOf = function() {_x000D_
return size;_x000D_
},_x000D_
that = Object.create(ary.slice(), {_x000D_
length: {_x000D_
get: sizeOf_x000D_
}_x000D_
});_x000D_
hideProperty(that, 'index');_x000D_
addProperties(that, {_x000D_
valueOf: sizeOf,_x000D_
init: function() {_x000D_
that.index = 0;_x000D_
},_x000D_
nth: function(n) {_x000D_
if (n >= size) return;_x000D_
var i = 0,_x000D_
result = [];_x000D_
for (; n; n >>>= 1, i++) if (n & 1) result.push(this[i]);_x000D_
return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;_x000D_
},_x000D_
next: function() {_x000D_
return this.nth(this.index++);_x000D_
}_x000D_
});_x000D_
addProperties(that, common);_x000D_
that.init();_x000D_
return (typeof (fun) === 'function') ? that.map(fun) : that;_x000D_
};_x000D_
/* combination */_x000D_
var nextIndex = function(n) {_x000D_
var smallest = n & -n,_x000D_
ripple = n + smallest,_x000D_
new_smallest = ripple & -ripple,_x000D_
ones = ((new_smallest / smallest) >> 1) - 1;_x000D_
return ripple | ones;_x000D_
};_x000D_
var combination = function(ary, nelem, fun) {_x000D_
if (!nelem) nelem = ary.length;_x000D_
if (nelem < 1) throw new RangeError;_x000D_
if (nelem > ary.length) throw new RangeError;_x000D_
var first = (1 << nelem) - 1,_x000D_
size = C(ary.length, nelem),_x000D_
maxIndex = 1 << ary.length,_x000D_
sizeOf = function() {_x000D_
return size;_x000D_
},_x000D_
that = Object.create(ary.slice(), {_x000D_
length: {_x000D_
get: sizeOf_x000D_
}_x000D_
});_x000D_
hideProperty(that, 'index');_x000D_
addProperties(that, {_x000D_
valueOf: sizeOf,_x000D_
init: function() {_x000D_
this.index = first;_x000D_
},_x000D_
next: function() {_x000D_
if (this.index >= maxIndex) return;_x000D_
var i = 0,_x000D_
n = this.index,_x000D_
result = [];_x000D_
for (; n; n >>>= 1, i++) {_x000D_
if (n & 1) result[result.length] = this[i];_x000D_
}_x000D_
_x000D_
this.index = nextIndex(this.index);_x000D_
return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;_x000D_
}_x000D_
});_x000D_
addProperties(that, common);_x000D_
that.init();_x000D_
return (typeof (fun) === 'function') ? that.map(fun) : that;_x000D_
};_x000D_
/* permutation */_x000D_
var _permutation = function(ary) {_x000D_
var that = ary.slice(),_x000D_
size = factorial(that.length);_x000D_
that.index = 0;_x000D_
that.next = function() {_x000D_
if (this.index >= size) return;_x000D_
var copy = this.slice(),_x000D_
digits = factoradic(this.index, this.length),_x000D_
result = [],_x000D_
i = this.length - 1;_x000D_
for (; i >= 0; --i) result.push(copy.splice(digits[i], 1)[0]);_x000D_
this.index++;_x000D_
return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;_x000D_
};_x000D_
return that;_x000D_
};_x000D_
// which is really a permutation of combination_x000D_
var permutation = function(ary, nelem, fun) {_x000D_
if (!nelem) nelem = ary.length;_x000D_
if (nelem < 1) throw new RangeError;_x000D_
if (nelem > ary.length) throw new RangeError;_x000D_
var size = P(ary.length, nelem),_x000D_
sizeOf = function() {_x000D_
return size;_x000D_
},_x000D_
that = Object.create(ary.slice(), {_x000D_
length: {_x000D_
get: sizeOf_x000D_
}_x000D_
});_x000D_
hideProperty(that, 'cmb');_x000D_
hideProperty(that, 'per');_x000D_
addProperties(that, {_x000D_
valueOf: function() {_x000D_
return size;_x000D_
},_x000D_
init: function() {_x000D_
this.cmb = combination(ary, nelem);_x000D_
this.per = _permutation(this.cmb.next());_x000D_
},_x000D_
next: function() {_x000D_
var result = this.per.next();_x000D_
if (!result) {_x000D_
var cmb = this.cmb.next();_x000D_
if (!cmb) return;_x000D_
this.per = _permutation(cmb);_x000D_
return this.next();_x000D_
}_x000D_
return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;_x000D_
}_x000D_
});_x000D_
addProperties(that, common);_x000D_
that.init();_x000D_
return (typeof (fun) === 'function') ? that.map(fun) : that;_x000D_
};_x000D_
_x000D_
/* export */_x000D_
var Combinatorics = Object.create(null);_x000D_
addProperties(Combinatorics, {_x000D_
C: C,_x000D_
P: P,_x000D_
factorial: factorial,_x000D_
factoradic: factoradic,_x000D_
permutation: permutation,_x000D_
});_x000D_
return Combinatorics;_x000D_
})();_x000D_
_x000D_
function permute_Technicalbloke(inputArray) {_x000D_
if (inputArray.length === 1) return inputArray;_x000D_
return inputArray.reduce( function(accumulator,_,index){_x000D_
permute_Technicalbloke([...inputArray.slice(0,index),...inputArray.slice(index+1)])_x000D_
.map(value=>accumulator.push([inputArray[index],value]));_x000D_
return accumulator;_x000D_
},[]);_x000D_
}_x000D_
_x000D_
var suite = new Benchmark.Suite;_x000D_
var input = [0, 1, 2, 3, 4];_x000D_
_x000D_
suite.add('permute_SiGanteng', function() {_x000D_
permute_SiGanteng(input);_x000D_
})_x000D_
.add('permute_delimited', function() {_x000D_
permute_delimited(input);_x000D_
})_x000D_
.add('permute_monkey', function() {_x000D_
permute_monkey(input);_x000D_
})_x000D_
.add('permute_Oriol', function() {_x000D_
permute_Oriol(input);_x000D_
})_x000D_
.add('permute_MarkusT', function() {_x000D_
permute_MarkusT(input);_x000D_
})_x000D_
.add('permute_le_m', function() {_x000D_
permute_le_m(input);_x000D_
})_x000D_
.add('permute_Urielzen', function() {_x000D_
permute_Urielzen(input);_x000D_
})_x000D_
.add('permute_Taylor_Hakes', function() {_x000D_
permute_Taylor_Hakes(input);_x000D_
})_x000D_
.add('permute_Combinatorics', function() {_x000D_
Combinatorics.permutation(input).toArray();_x000D_
})_x000D_
.add('permute_Technicalbloke', function() {_x000D_
permute_Technicalbloke(input);_x000D_
})_x000D_
.on('cycle', function(event) {_x000D_
console.log(String(event.target));_x000D_
})_x000D_
.on('complete', function() {_x000D_
console.log('Fastest is ' + this.filter('fastest').map('name'));_x000D_
})_x000D_
.run({async: true});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.4/platform.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.4/benchmark.min.js"></script>
_x000D_
Run-time results for Chrome 48:
I think you can use keydown
too:
$('#fieldID').on('keydown', function (e) {
//console.log(e.which);
if (e.which === 8) {
//do something when pressing delete
return true;
} else {
//do something else
return false;
}
});
I got the same error using:
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">
But once I added https: in the beginning of the href the error disappeared.
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">
This should do it:
//Returns the index of the first occurence of char c in char* string. If not found -1 is returned.
int get_index(char* string, char c) {
char *e = strchr(string, c);
if (e == NULL) {
return -1;
}
return (int)(e - string);
}
or programatically
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
Sharing my solution here, based on Chris' answer. Hope it can help others.
I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:
export class Settings extends React.PureComponent {
render() {
const loading = (<div>I'm Loading</div>);
let content = [];
let pushMessages = null;
let emailMessages = null;
if (this.props.pushPreferences) {
pushMessages = (<div>Push Content Here</div>);
}
if (this.props.emailPreferences) {
emailMessages = (<div>Email Content Here</div>);
}
// Push the components in the order I want
if (emailMessages) content.push(emailMessages);
if (pushMessages) content.push(pushMessages);
return (
<div>
{content.length ? content : loading}
</div>
)
}
Now, I do realize I could also just put {pushMessages}
and {emailMessages}
directly in my return()
below, but assuming I had even more conditional content, my return()
would just look cluttered.
The answer depends on the presence of other shapes, level of noise if any and invariance you want to provide for (e.g. rotation, scaling, etc). These requirements will define not only the algorithm but also required pre-procesing stages to extract features.
Template matching that was suggested above works well when shapes aren't rotated or scaled and when there are no similar shapes around; in other words, it finds a best translation in the image where template is located:
double minVal, maxVal;
Point minLoc, maxLoc;
Mat image, template, result; // template is your shape
matchTemplate(image, template, result, CV_TM_CCOEFF_NORMED);
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // maxLoc is answer
Geometric hashing is a good method to get invariance in terms of rotation and scaling; this method would require extraction of some contour points.
Generalized Hough transform can take care of invariance, noise and would have minimal pre-processing but it is a bit harder to implement than other methods. OpenCV has such transforms for lines and circles.
In the case when number of shapes is limited calculating moments or counting convex hull vertices may be the easiest solution: openCV structural analysis
LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall
# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)
test: $(SRC)
gcc -o $@ $^ $(CFLAGS) $(LIBS)
Depends on how much space you want. I'm not sure I agree with the logic of adding a "col-XX-1" in between each one, because you are then defining an entire "column" in between each one.
If you just want "a little spacing" in between each button, I like to add padding to the encompassing row. That way, I can still use all 12 columns, while including a "space" in between each button.
Bootply: http://www.bootply.com/ugeXrxpPvD
Hibernate uses a ConnectionProvider internally to obtain connections. From the hibernate javadoc:
The ConnectionProvider interface is not intended to be exposed to the application. Instead it is used internally by Hibernate to obtain connections.
The more elegant way of solving this would be to create a database connection pool yourself and hand connections to hibernate and your legacy tool from there.
The first thing you need to do is to set the level of verification. Such levels is not so much:
Although the method setHostnameVerifier() is obsolete for new library apache, but for version in Android SDK is normal.
And so we take ALLOW_ALL_HOSTNAME_VERIFIER
and set it in the method factory SSLSocketFactory.setHostnameVerifier()
.
Next, You need set our factory for the protocol to https. To do this, simply call the SchemeRegistry.register()
method.
Then you need to create a DefaultHttpClient
with SingleClientConnManager
.
Also in the code below you can see that on default will also use our flag (ALLOW_ALL_HOSTNAME_VERIFIER
) by the method HttpsURLConnection.setDefaultHostnameVerifier()
Below code works for me:
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
// Example send http request
final String url = "https://encrypted.google.com/";
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);
In bootstrap 4 the outline is no longer used, but the box-shadow. If it is your case, just do the following:
.btn:focus {
box-shadow: none;
}
In a case
statement, a ,
is the equivalent of ||
in an if
statement.
case car
when 'toyota', 'lexus'
# code
end
You're looking for the /Y
switch.
You may also get :
Could not load file or assembly 'WebMatrix.Data, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
This has moved to this package
Install-Package Microsoft.AspNet.WebPages.Data
You should probably do a clean build before attempting any of the answers to this question and after updating packages
You can do this by using a content provider. Each data item used in the application remains private to the application. If an application want to share data accross applications, there is only technique to achieve this, using a content provider, which provides interface to access that private data.
Another way to get a subset of columns from your DataFrame, assuming you want all the rows, would be to do:
data[['a','b']]
and data[['c','d','e']]
If you want to use numerical column indexes you can do:
data[data.columns[:2]]
and data[data.columns[2:]]
Although converting the ArrayList
to a HashSet
effectively removes duplicates, if you need to preserve insertion order, I'd rather suggest you to use this variant
// list is some List of Strings
Set<String> s = new LinkedHashSet<>(list);
Then, if you need to get back a List
reference, you can use again the conversion constructor.
//"Comment" Filter datagrid without changing dataset,Perfectly works.
(dg.ItemsSource as ListCollectionView).Filter = (d) =>
{
DataRow myRow = ((System.Data.DataRowView)(d)).Row;
if (myRow["FName"].ToString().ToUpper().Contains(searchText.ToString().ToUpper()) || myRow["LName"].ToString().ToUpper().Contains(searchText.ToString().ToUpper()))
return true; //if want to show in grid
return false; //if don't want to show in grid
};
There are already a lot of answers, but none worked for me... So this is what I'm using now.
readlink_f() {
local target="$1"
[ -f "$target" ] || return 1 #no nofile
while [ -L "$target" ]; do
target="$(readlink "$target")"
done
echo "$(cd "$(dirname "$target")"; pwd -P)/$target"
}
If by Alt-F4 or X you mean "Exit the Application Immediately Without Regard for What Other Windows or Threads are Running", then System.exit(...)
will do exactly what you want in a very abrupt, brute-force, and possibly problematic fashion.
If by Alt-F4 or X you mean hide the window, then frame.setVisible(false)
is how you "close" the window. The window will continue to consume resources/memory but can be made visible again very quickly.
If by Alt-F4 or X you mean hide the window and dispose of any resources it is consuming, then frame.dispose()
is how you "close" the window. If the frame was the last visible window and there are no other non-daemon threads running, the program will exit. If you show the window again, it will have to reinitialize all of the native resources again (graphics buffer, window handles, etc).
dispose()
might be closest to the behavior that you really want. If your app has multiple windows open, do you want Alt-F4 or X to quit the app or just close the active window?
The Java Swing Tutorial on Window Listeners may help clarify things for you.
This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.
Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:
http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/
Update:
Example from Microsoft:
Original
This is how I got client certification working and checking that a specific Root CA had issued it as well as it being a specific certificate.
First I edited <src>\.vs\config\applicationhost.config
and made this change: <section name="access" overrideModeDefault="Allow" />
This allows me to edit <system.webServer>
in web.config
and add the following lines which will require a client certification in IIS Express. Note: I edited this for development purposes, do not allow overrides in production.
For production follow a guide like this to set up the IIS:
https://medium.com/@hafizmohammedg/configuring-client-certificates-on-iis-95aef4174ddb
web.config:
<security>
<access sslFlags="Ssl,SslNegotiateCert,SslRequireCert" />
</security>
API Controller:
[RequireSpecificCert]
public class ValuesController : ApiController
{
// GET api/values
public IHttpActionResult Get()
{
return Ok("It works!");
}
}
Attribute:
public class RequireSpecificCertAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "HTTPS Required"
};
}
else
{
X509Certificate2 cert = actionContext.Request.GetClientCertificate();
if (cert == null)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "Client Certificate Required"
};
}
else
{
X509Chain chain = new X509Chain();
//Needed because the error "The revocation function was unable to check revocation for the certificate" happened to me otherwise
chain.ChainPolicy = new X509ChainPolicy()
{
RevocationMode = X509RevocationMode.NoCheck,
};
try
{
var chainBuilt = chain.Build(cert);
Debug.WriteLine(string.Format("Chain building status: {0}", chainBuilt));
var validCert = CheckCertificate(chain, cert);
if (chainBuilt == false || validCert == false)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "Client Certificate not valid"
};
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
Debug.WriteLine(string.Format("Chain error: {0} {1}", chainStatus.Status, chainStatus.StatusInformation));
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
base.OnAuthorization(actionContext);
}
}
private bool CheckCertificate(X509Chain chain, X509Certificate2 cert)
{
var rootThumbprint = WebConfigurationManager.AppSettings["rootThumbprint"].ToUpper().Replace(" ", string.Empty);
var clientThumbprint = WebConfigurationManager.AppSettings["clientThumbprint"].ToUpper().Replace(" ", string.Empty);
//Check that the certificate have been issued by a specific Root Certificate
var validRoot = chain.ChainElements.Cast<X509ChainElement>().Any(x => x.Certificate.Thumbprint.Equals(rootThumbprint, StringComparison.InvariantCultureIgnoreCase));
//Check that the certificate thumbprint matches our expected thumbprint
var validCert = cert.Thumbprint.Equals(clientThumbprint, StringComparison.InvariantCultureIgnoreCase);
return validRoot && validCert;
}
}
Can then call the API with client certification like this, tested from another web project.
[RoutePrefix("api/certificatetest")]
public class CertificateTestController : ApiController
{
public IHttpActionResult Get()
{
var handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(GetClientCert());
handler.UseProxy = false;
var client = new HttpClient(handler);
var result = client.GetAsync("https://localhost:44331/api/values").GetAwaiter().GetResult();
var resultString = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return Ok(resultString);
}
private static X509Certificate GetClientCert()
{
X509Store store = null;
try
{
store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
var certificateSerialNumber= "?81 c6 62 0a 73 c7 b1 aa 41 06 a3 ce 62 83 ae 25".ToUpper().Replace(" ", string.Empty);
//Does not work for some reason, could be culture related
//var certs = store.Certificates.Find(X509FindType.FindBySerialNumber, certificateSerialNumber, true);
//if (certs.Count == 1)
//{
// var cert = certs[0];
// return cert;
//}
var cert = store.Certificates.Cast<X509Certificate>().FirstOrDefault(x => x.GetSerialNumberString().Equals(certificateSerialNumber, StringComparison.InvariantCultureIgnoreCase));
return cert;
}
finally
{
store?.Close();
}
}
}
Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image. In one of my tries i use
String pathToImageSortBy = "resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
But correct way was use name of my project in path to resource
String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
<h1>My Application</h1>
<select [(ngModel)]="selectedValue">
<option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option>
</select>
NOTE: you can use [ngValue]="c"
instead of [ngValue]="c.id"
where c is the complete country object.
[value]="..."
only supports string values
[ngValue]="..."
supports any type
update
If the value
is an object, the preselected instance needs to be identical with one of the values.
See also the recently added custom comparison https://github.com/angular/angular/issues/13268 available since 4.0.0-beta.7
<select [compareWith]="compareFn" ...
Take care of if you want to access this
within compareFn
.
compareFn = this._compareFn.bind(this);
// or
// compareFn = (a, b) => this._compareFn(a, b);
_compareFn(a, b) {
// Handle compare logic (eg check if unique ids are the same)
return a.id === b.id;
}
function LastRowIndex(byval w as worksheet, byval col as variant) as long
dim r as range
set r = application.intersect(w.usedrange, w.columns(col))
if not r is nothing then
set r = r.cells(r.cells.count)
if isempty(r.value) then
LastRowIndex = r.end(xlup).row
else
LastRowIndex = r.row
end if
end if
end function
Usage:
? LastRowIndex(ActiveSheet, 5)
? LastRowIndex(ActiveSheet, "AI")
Unrelated to the OP's problem, but my issue was that I'm a noob shell scripter. All the other languages I've used require parentheses to invoke methods, whereas shell doesn't seem to like that.
function do_something() {
# do stuff here
}
# bad
do_something()
# works
do_something
As an extension of @Demyn's answer, I created some utility functions which print the current function's name and current function's arguments:
import inspect
import logging
import traceback
def get_function_name():
return traceback.extract_stack(None, 2)[0][2]
def get_function_parameters_and_values():
frame = inspect.currentframe().f_back
args, _, _, values = inspect.getargvalues(frame)
return ([(i, values[i]) for i in args])
def my_func(a, b, c=None):
logging.info('Running ' + get_function_name() + '(' + str(get_function_parameters_and_values()) +')')
pass
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s [%(levelname)s] -> %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
my_func(1, 3) # 2016-03-25 17:16:06,927 [INFO] -> Running my_func([('a', 1), ('b', 3), ('c', None)])
There is no one-to-one correlation. For a really good article please see Efficient String Concatenation in Python:
Building long strings in the Python progamming language can sometimes result in very slow running code. In this article I investigate the computational performance of various string concatenation methods.