you can always create new admin template , and do what you need in your admin_view (override the admin add url to your admin_view):
url(r'^admin/mymodel/mymodel/add/$' , 'admin_views.add_my_special_model')
in comments to the answer you took the code from someone says ShellExecuteEx doesn't post its STDOUT back to the originating shell. so you will not see "I am root now", even though the code is probably working fine.
instead of printing something, try writing to a file:
import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'
if sys.argv[-1] != ASADMIN:
script = os.path.abspath(sys.argv[0])
params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
sys.exit(0)
with open("somefilename.txt", "w") as out:
print >> out, "i am root"
and then look in the file.
Literally dozens of answers in this and linked questions and elsewhere at SE, all of which are deficient in this way or another, have clearly shown that Windows doesn't provide a reliable built-in console utility. So, it's time to roll out your own.
The following C code, based on Detect if program is running with full administrator rights, works in Win2k+1, anywhere and in all cases (UAC, domains, transitive groups...) - because it does the same as the system itself when it checks permissions. It signals of the result both with a message (that can be silenced with a switch) and exit code.
It only needs to be compiled once, then you can just copy the .exe
everywhere - it only depends on kernel32.dll
and advapi32.dll
(I've uploaded a copy).
chkadmin.c
:
#include <malloc.h>
#include <stdio.h>
#include <windows.h>
#pragma comment (lib,"Advapi32.lib")
int main(int argc, char** argv) {
BOOL quiet = FALSE;
DWORD cbSid = SECURITY_MAX_SID_SIZE;
PSID pSid = _alloca(cbSid);
BOOL isAdmin;
if (argc > 1) {
if (!strcmp(argv[1],"/q")) quiet=TRUE;
else if (!strcmp(argv[1],"/?")) {fprintf(stderr,"Usage: %s [/q]\n",argv[0]);return 0;}
}
if (!CreateWellKnownSid(WinBuiltinAdministratorsSid,NULL,pSid,&cbSid)) {
fprintf(stderr,"CreateWellKnownSid: error %d\n",GetLastError());exit(-1);}
if (!CheckTokenMembership(NULL,pSid,&isAdmin)) {
fprintf(stderr,"CheckTokenMembership: error %d\n",GetLastError());exit(-1);}
if (!quiet) puts(isAdmin ? "Admin" : "Non-admin");
return !isAdmin;
}
1MSDN claims the APIs are XP+ but this is false. CheckTokenMembership
is 2k+ and the other one is even older. The last link also contains a much more complicated way that would work even in NT.
Update mongod.conf file
vi /etc/mongod.conf
net:
port: 27017
bindIp: 0.0.0.0
security:
authorization: enabled
Start MongoDB service demon
systemctl start mongod
Open MongoDB shell
mongo
Execute this command on the shell
use admin
db.createUser(
{
user: 'admin',
pwd: 'YouPassforUser',
roles: [ { role: 'root', db: 'admin' } ]
}
);
Remote root user has been created. Now you can test this database connection by using any MongoDB GUI tool from your dev machine. Like Robo 3T
res = request.GET['paymentid']
will raise a KeyError
if paymentid
is not in the GET data.
Your sample php code checks to see if paymentid
is in the POST data, and sets $payID
to '' otherwise:
$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''
The equivalent in python is to use the get()
method with a default argument:
payment_id = request.POST.get('payment_id', '')
while debugging, this is what I see in the
response.GET: <QueryDict: {}>
,request.POST: <QueryDict: {}>
It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.
Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.
void main(){
float bug=0.0;
vec3 tile=texture2D(colMap, coords.st).xyz;
vec4 col=vec4(tile, 1.0);
if(something) bug=1.0;
col.x+=bug;
gl_FragColor=col;
}
This isn't a "slice", but it is a general solution that doesn't use explicit indexing, and works for the scenario where the sequence in question is anonymous (so you can create and "slice" on the same line, without creating twice and indexing twice): operator.itemgetter
import operator
# Done once and reused
first_and_last = operator.itemgetter(0, -1)
...
first, last = first_and_last(some_list)
You could just inline it as (after from operator import itemgetter
for brevity at time of use):
first, last = itemgetter(0, -1)(some_list)
but if you'll be reusing the getter a lot, you can save the work of recreating it (and give it a useful, self-documenting name) by creating it once ahead of time.
Thus, for your specific use case, you can replace:
x, y = a.split("-")[0], a.split("-")[-1]
with:
x, y = itemgetter(0, -1)(a.split("-"))
and split
only once without storing the complete list
in a persistent name for len
checking or double-indexing or the like.
Note that itemgetter
for multiple items returns a tuple
, not a list
, so if you're not just unpacking it to specific names, and need a true list
, you'd have to wrap the call in the list
constructor.
I used Task Manager to kill adb.exe to solve this problem. Adb.exe will automatically start after being killed.
Killing adb.exe has solved a lot of problems related to debug and emulators for me so far.
It's working to me.
I use Asp.net core 2.2
(this way supported in asp.net core 2.1
and upper version).
add Kestrel
section in appsettings.json
file.
like this:
{
"Kestrel": {
"EndPoints": {
"Http": {
"Url": "http://localhost:4300"
}
}
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
and in Startup.cs
:
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
You can use this
var fs = require('fs');
var myCss = {
style : fs.readFileSync('./style.css','utf8');
};
app.get('/', function(req, res){
res.render('index.ejs', {
title: 'My Site',
myCss: myCss
});
});
put this on template
<%- myCss.style %>
just build style.css
<style>
body {
background-color: #D8D8D8;
color: #444;
}
</style>
I try this for some custom css. It works for me
you can try to put this in your php.ini:
ini_set("display_errors", "1");
error_reporting(E_ALL);
In php.ini file also you can set error_reporting();
Just a reminder you can't initialise DataTable
on the same <table>
element twice.
If you encounter same issue then you can set searching
and paging
false while initializing DataTable on your HTML <table>
like this
$('#tbl').DataTable({
searching: false,
paging: false,
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
Using moment.js is as easy as:
var years = moment().diff('1981-01-01', 'years');
var days = moment().diff('1981-01-01', 'days');
For additional reference, you can read moment.js official documentation.
Why you just not read the File line by line and add it to a StringBuffer?
After you reach end of File you can get the String from the StringBuffer.
There is a simple way to do it. I tried it on my app and it worked pretty well.
Just type: $text = $row["text"]; echo nl2br($text);
According the the Apple Reference on UIImage the object is immutable and you have no access to the backing bytes. While it is true that you can access the CGImage data if you populated the UIImage
with a CGImage
(explicitly or implicitly), it will return NULL
if the UIImage
is backed by a CIImage
and vice-versa.
Image objects not provide direct access to their underlying image data. However, you can retrieve the image data in other formats for use in your app. Specifically, you can use the cgImage and ciImage properties to retrieve versions of the image that are compatible with Core Graphics and Core Image, respectively. You can also use the UIImagePNGRepresentation(:) and UIImageJPEGRepresentation(:_:) functions to generate an NSData object containing the image data in either the PNG or JPEG format.
As stated your options are
Neither of these are particularly good tricks if you want output that isn't ARGB, PNG, or JPEG data and the data isn't already backed by CIImage.
While developing your project it might make more sense for you to avoid UIImage altogether and pick something else. UIImage, as a Obj-C image wrapper, is often backed by CGImage to the point where we take it for granted. CIImage tends to be a better wrapper format in that you can use a CIContext to get out the format you desire without needing to know how it was created. In your case, getting the bitmap would be a matter of calling
- render:toBitmap:rowBytes:bounds:format:colorSpace:
As an added bonus you can start doing nice manipulations to the image by chaining filters onto the image. This solves a lot of the issues where the image is upside down or needs to be rotated/scaled etc.
Use angular.copy when assigning value of object or array to another variable and that object
value should not be changed.
Without deep copy or using angular.copy, changing value of property or adding any new property update all object referencing that same object.
var app = angular.module('copyExample', []);_x000D_
app.controller('ExampleController', ['$scope',_x000D_
function($scope) {_x000D_
$scope.printToConsole = function() {_x000D_
$scope.main = {_x000D_
first: 'first',_x000D_
second: 'second'_x000D_
};_x000D_
_x000D_
$scope.child = angular.copy($scope.main);_x000D_
console.log('Main object :');_x000D_
console.log($scope.main);_x000D_
console.log('Child object with angular.copy :');_x000D_
console.log($scope.child);_x000D_
_x000D_
$scope.child.first = 'last';_x000D_
console.log('New Child object :')_x000D_
console.log($scope.child);_x000D_
console.log('Main object after child change and using angular.copy :');_x000D_
console.log($scope.main);_x000D_
console.log('Assing main object without copy and updating child');_x000D_
_x000D_
$scope.child = $scope.main;_x000D_
$scope.child.first = 'last';_x000D_
console.log('Main object after update:');_x000D_
console.log($scope.main);_x000D_
console.log('Child object after update:');_x000D_
console.log($scope.child);_x000D_
}_x000D_
}_x000D_
]);_x000D_
_x000D_
// Basic object assigning example_x000D_
_x000D_
var main = {_x000D_
first: 'first',_x000D_
second: 'second'_x000D_
};_x000D_
var one = main; // same as main_x000D_
var two = main; // same as main_x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same_x000D_
_x000D_
two = {_x000D_
three: 'three'_x000D_
}; // two changed but one and main remains same_x000D_
console.log('main :' + JSON.stringify(main)); // one and main are same_x000D_
console.log('one :' + JSON.stringify(one)); // one and main are same_x000D_
console.log('two :' + JSON.stringify(two)); // two is changed_x000D_
_x000D_
two = main; // same as main_x000D_
_x000D_
two.first = 'last'; // change value of object's property so changed value of all object property _x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same with new value_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same with new value_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same with new value
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="copyExample" ng-controller="ExampleController">_x000D_
<button ng-click='printToConsole()'>Explain</button>_x000D_
</div>
_x000D_
Another approach is to use pickle. See this answer to a duplicate of this question.
Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.
<script type="text/javascript">
function handleClick(evt) {
var node = evt.target || evt.srcElement;
if (node.name == 'edit') {
node.value = "Modify";
}
}
</script>
<table id="table1" border="1" onclick="handleClick(event);">
<thead>
<tr>
<th>Select
</thead>
<tbody>
<tr>
<td>
<form name="f1" action="#" >
<input id="edit1" type="submit" name="edit" value="Edit">
</form>
<tr>
<td>
<form name="f2" action="#" >
<input id="edit2" type="submit" name="edit" value="Edit">
</form>
<tr>
<td>
<form name="f3" action="#" >
<input id="edit3" type="submit" name="edit" value="Edit">
</form>
</tbody>
</table>
I use this method to add a border outside the image. You can customise the border width in boderWidth
constant.
func addBorderToImage(image : UIImage) -> UIImage {
let bgImage = image.cgImage
let initialWidth = (bgImage?.width)!
let initialHeight = (bgImage?.height)!
let borderWidth = Int(Double(initialWidth) * 0.10);
let width = initialWidth + borderWidth * 2
let height = initialHeight + borderWidth * 2
let data = malloc(width * height * 4)
let context = CGContext(data: data,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: (bgImage?.colorSpace)!,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue);
context?.draw(bgImage!, in: CGRect(x: CGFloat(borderWidth), y: CGFloat(borderWidth), width: CGFloat(initialWidth), height: CGFloat(initialHeight)))
context?.setStrokeColor(UIColor.white.cgColor)
context?.setLineWidth(CGFloat(borderWidth))
context?.move(to: CGPoint(x: 0, y: 0))
context?.addLine(to: CGPoint(x: 0, y: height))
context?.addLine(to: CGPoint(x: width, y: height))
context?.addLine(to: CGPoint(x: width, y: 0))
context?.addLine(to: CGPoint(x: 0, y: 0))
context?.strokePath()
let cgImage = context?.makeImage()
let uiImage = UIImage(cgImage: cgImage!)
free(data)
return uiImage;
}
By saying "Character array" you mean a string? Like "hello" or "hahaha this is a string of characters"..
Anyway, use strlen(). Read a bit about it, there's plenty of info about it, like here.
Let's Encrypt is a free, automated, and open certificate authority made by the Internet Security Research Group (ISRG). It is sponsored by well-known organisations such as Mozilla, Cisco or Google Chrome. All modern browsers are compatible and trust Let's Encrypt.
All certificates are free (even wildcard certificates)! For security reasons, the certificates expire pretty fast (after 90 days). For this reason, it is recommended to install an ACME client, which will handle automatic certificate renewal.
There are many clients you can use to install a Let's Encrypt certificate:
Let’s Encrypt uses the ACME protocol to verify that you control a given domain name and to issue you a certificate. To get a Let’s Encrypt certificate, you’ll need to choose a piece of ACME client software to use. - https://letsencrypt.org/docs/client-options/
The first (excellent) answer stated -
The method with count() is unsafe. If another session deletes the row that met the condition after the line with the count(*), and before the line with the select ... into, the code will throw an exception that will not get handled.
Not so. Within a given logical Unit of Work Oracle is totally consistent. Even if someone commits the delete of the row between a count and a select Oracle will, for the active session, obtain the data from the logs. If it cannot, you will get a "snapshot too old" error.
You can browse all the jQuery plugins tagged with "cookie" here:
http://plugins.jquery.com/plugin-tags/cookies
Plenty of options there.
Check out the one called jQuery Storage, which takes advantage of HTML5's localStorage. If localStorage isn't available, it defaults to cookies. However, it doesn't allow you to set expiration.
You could also just compile the following program and run it on your machine.
#include <gtk/gtk.h>
#include <glib/gprintf.h>
int main(int argc, char *argv[])
{
/* Initialize GTK */
gtk_init (&argc, &argv);
g_printf("%d.%d.%d\n", gtk_major_version, gtk_minor_version, gtk_micro_version);
return(0);
}
compile with ( assuming above source file is named version.c):
gcc version.c -o version `pkg-config --cflags --libs gtk+-2.0`
When you run this you will get some output. On my old embedded device I get the following:
[root@n00E04B3730DF n2]# ./version
2.10.4
[root@n00E04B3730DF n2]#
The query below will result in dd-mmm-yy format.
select
cast(DAY(getdate()) as varchar)+'-'+left(DATEname(m,getdate()),3)+'-'+
Right(Year(getdate()),2)
This is another solution with lambda:
#include <cmath>
#include <limits>
auto Compare = [](float a, float b, float epsilon = std::numeric_limits<float>::epsilon()){ return (std::fabs(a - b) <= epsilon); };
Per Mozilla's Map documentation, you can initialize as follows:
private _gridOptions:Map<string, Array<string>> =
new Map([
["1", ["test"]],
["2", ["test2"]]
]);
Additionally to
openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes -out domain.key
I also generated Certificate Authority (CA) certificate:
openssl pkcs12 -in domain.pfx -out domain-ca.crt -nodes -nokeys -cacerts
And included it in Apache config file:
<VirtualHost 192.168.0.1:443>
...
SSLEngine on
SSLCertificateFile /path/to/domain.cer
SSLCertificateKeyFile /path/to/domain.key
SSLCACertificateFile /path/to/domain-ca.crt
...
</VirtualHost>
always set folder directory properly for image otherwise image will not be upload check my code for image upload if you issue still there let me know will help you
if (move_uploaded_file($_FILES['profile_picture']['tmp_name'],'../images/manager/'.
$_FILES["profile_picture"]['name'])) {
echo "Uploaded";
} else {
echo "File not uploaded";
}
Spring framework is definitely good for web development and to be more specific for restful api services.
It is good for the above because of its dependency injection and integration with other modules like spring security, spring aop, mvc framework, microservices
With in any application, security is most probably a requirement.
If you aim to build a product that needs long maintenance, then you will need the utilize the Aop concept.
If your application has to much traffic thus increasing the load, you need to use the microservices concept.
Spring is giving all these features in one platform. Support with many modules.
Most importantly, spring is open source and an extensible framework,have a hook everywhere to integrate custom code in life cycle.
Spring Data is one project which provides integration with your project.
So spring can fit into almost every requirement.
The assignment operator has lower precedence than &&
, so your condition is equivalent to:
if ((match == 0 && k) = m)
But the left-hand side of this is an rvalue, namely the boolean resulting from the evaluation of the subexpression match == 0 && k
, so you cannot assign to it.
By contrast, comparison has higher precedence, so match == 0 && k == m
is equivalent to:
if ((match == 0) && (k == m))
To get current skin URL use this Mage::getDesign()->getSkinUrl()
Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.
function removeParam(key, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === key) {
params_arr.splice(i, 1);
}
}
if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
}
return rtn;
}
To use it, simply do something like this:
var originalURL = "http://yourewebsite.com?id=10&color_id=1";
var alteredURL = removeParam("color_id", originalURL);
The var alteredURL
will be the output you desire.
Hope it helps!
$("#personal").click(function() {
if ($(this).is(":checked")) {
alert('Personal');
/* var validator = $("#register_france").validate();
validator.resetForm(); */
}
}
);
You can also try Word Extractor tool. Word Extractor can be used with any file in your computer to separate the strings that contain human text / words from binary code (exe applications, DLLs).
To access the super user or root user, follow:
At user@computer:
$sudo su
After you enter your password, you'll be at root@computer:
$docker run hello-world
In solution explorer, right-click References, then click to expand assemblies, find System.IO.Compression.FileSystem and make sure it's checked. Then you can use it in your class - using System.IO.Compression;
Make a class that will fit table cell width to content
.table td.fit,
.table th.fit {
white-space: nowrap;
width: 1%;
}
use the click event for best compatibility with MSIE
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
alert("state changed");
});
});
You can stay DRY and just use node-ipware that supports both IPv4 and IPv6.
Install:
npm install ipware
In your app.js or middleware:
var getIP = require('ipware')().get_ip;
app.use(function(req, res, next) {
var ipInfo = getIP(req);
console.log(ipInfo);
// { clientIp: '127.0.0.1', clientIpRoutable: false }
next();
});
It will make the best attempt to get the user's IP address or returns 127.0.0.1
to indicate that it could not determine the user's IP address. Take a look at the README file for advanced options.
Try psrinfo to find the processor type and the number of physical processors installed on the system.
+ Copy .htaccess from Application to Root folder
+ edit .htaccess and put
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /ci_test/
#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin
ErrorDocument 404 /index.php
</IfModule>
Note: make sure your web server is enable for "rewrite_module"
+ Remove index.php from $config['index_page'] = 'index.php';
- edit config.php in application/config
- search for index.php
change it from $config['index_page'] = 'index.php'; to $config['index_page'] = '';
Please watch this videos for reference https://www.youtube.com/watch?v=HFG2nMDn35Q
You can check it with irb:
$ irb
>> 2 / 3
=> 0
>> 2.to_f / 3
=> 0.666666666666667
>> 2 / 3.to_f
=> 0.666666666666667
for XML android
android:src="@drawable/foto1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
You could also use a third party api to do device detection via user agent string. One such service is www.useragentinfo.co. Just sign up and get your api token and below is how you get the device info via PHP:
<?php
$useragent = $_SERVER['HTTP_USER_AGENT'];
// get api token at https://www.useragentinfo.co/
$token = "<api-token>";
$url = "https://www.useragentinfo.co/api/v1/device/";
$data = array('useragent' => $useragent);
$headers = array();
$headers[] = "Content-type: application/json";
$headers[] = "Authorization: Token " . $token;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status != 200 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
echo $json_response;
?>
And here is the sample response if the visitor is using an iPhone:
{
"device_type":"SmartPhone",
"browser_version":"5.1",
"os":"iOS",
"os_version":"5.1",
"device_brand":"Apple",
"bot":false,
"browser":"Mobile Safari",
"device_model":"iPhone"
}
You can go for identifying a list of elements with xPath:
//td[text() = ' Color Digest ']/following-sibling::td[1]
This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:
List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))
Now, you can use the 2nd element as your intended element, which is elements.get(1)
You can also check this out. If you are using this method, then use the parse function to get values from Mongo Database:
db.getCollection('user').find({
createdOn: {
$gt: ISODate("2020-01-01T00:00:00.000Z"),
$lt: ISODate("2020-03-01T00:00:00.000Z")
}
})
If array of Books is null, return zero as it looks that method count total price of all Books provided - if no Book is provided, zero is correct value:
public static double calculateInventoryTotal(Book[] books)
{
if(books == null) return 0;
double total = 0;
for (int i = 0; i < books.length; i++)
{
total += books[i].getPrice();
}
return total;
}
It's upon to you to decide if it's correct that you can input null input value (shoul not be correct, but...).
try this:
head -1 /etc/*release | awk '{print $1}'
clear()
didn't work for me. But this did:
input.sendKeys(Keys.CONTROL, Keys.chord("a")); //select all text in textbox
input.sendKeys(Keys.BACK_SPACE); //delete it
input.sendKeys("new text"); //enter new text
I added this helper method to handle my POST requests that return an object I care about.
For REST purists, I know, POSTs should not return anything besides a status. However, I had a large collection of ids that was too big for a query string parameter.
Helper Method:
public TResponse Post<TResponse>(string relativeUri, object postBody) where TResponse : new()
{
//Note: Ideally the RestClient isn't created for each request.
var restClient = new RestClient("http://localhost:999");
var restRequest = new RestRequest(relativeUri, Method.POST)
{
RequestFormat = DataFormat.Json
};
restRequest.AddBody(postBody);
var result = restClient.Post<TResponse>(restRequest);
if (!result.IsSuccessful)
{
throw new HttpException($"Item not found: {result.ErrorMessage}");
}
return result.Data;
}
Usage:
public List<WhateverReturnType> GetFromApi()
{
var idsForLookup = new List<int> {1, 2, 3, 4, 5};
var relativeUri = "/api/idLookup";
var restResponse = Post<List<WhateverReturnType>>(relativeUri, idsForLookup);
return restResponse;
}
I wanted a more exact and useful answer to this question. Here's the real answer (adjust accordingly if you want a byte array specifically; obviously the math will be off by a factor of 8 bits : 1 byte
):
class BitArray {
constructor(bits = 0) {
this.uints = new Uint32Array(~~(bits / 32));
}
getBit(bit) {
return (this.uints[~~(bit / 32)] & (1 << (bit % 32))) != 0 ? 1 : 0;
}
assignBit(bit, value) {
if (value) {
this.uints[~~(bit / 32)] |= (1 << (bit % 32));
} else {
this.uints[~~(bit / 32)] &= ~(1 << (bit % 32));
}
}
get size() {
return this.uints.length * 32;
}
static bitsToUints(bits) {
return ~~(bits / 32);
}
}
Usage:
let bits = new BitArray(500);
for (let uint = 0; uint < bits.uints.length; ++uint) {
bits.uints[uint] = 457345834;
}
for (let bit = 0; bit < 50; ++bit) {
bits.assignBit(bit, 1);
}
str = '';
for (let bit = bits.size - 1; bit >= 0; --bit) {
str += bits.getBit(bit);
}
str;
Output:
"00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000111111111111111111
11111111111111111111111111111111"
Note: This class is really slow to e.g. assign bits (i.e. ~2s per 10 million assignments) if it's created as a global variable, at least in the Firefox 76.0 Console on Linux... If, on the other hand, it's created as a variable (i.e. let bits = new BitArray(1e7);
), then it's blazingly fast (i.e. ~300ms per 10 million assignments)!
For more info, see here:
Note that I used Uint32Array because there's no way to directly have a bit/byte array (that you can interact with directly) and because even though there's a BigUint64Array
, JS only supports 32 bits:
Bitwise operators treat their operands as a sequence of 32 bits
...
The operands of all bitwise operators are converted to...32-bit integers
You could use XMLTABLE
:
SELECT rownum
FROM XMLTABLE('1 to 100');
-- alternatively(useful for generating range i.e. 10-20)
SELECT (COLUMN_VALUE).GETNUMBERVAL() AS NUM
FROM XMLTABLE('1 to 100');
At times you do not want to simply remove the characters, but just remove the accents. I came up with the following utility class which I use in my Java REST web projects whenever I need to include a String in an URL:
import java.text.Normalizer;
import java.text.Normalizer.Form;
import org.apache.commons.lang.StringUtils;
/**
* Utility class for String manipulation.
*
* @author Stefan Haberl
*/
public abstract class TextUtils {
private static String[] searchList = { "Ä", "ä", "Ö", "ö", "Ü", "ü", "ß" };
private static String[] replaceList = { "Ae", "ae", "Oe", "oe", "Ue", "ue",
"sz" };
/**
* Normalizes a String by removing all accents to original 127 US-ASCII
* characters. This method handles German umlauts and "sharp-s" correctly
*
* @param s
* The String to normalize
* @return The normalized String
*/
public static String normalize(String s) {
if (s == null)
return null;
String n = null;
n = StringUtils.replaceEachRepeatedly(s, searchList, replaceList);
n = Normalizer.normalize(n, Form.NFD).replaceAll("[^\\p{ASCII}]", "");
return n;
}
/**
* Returns a clean representation of a String which might be used safely
* within an URL. Slugs are a more human friendly form of URL encoding a
* String.
* <p>
* The method first normalizes a String, then converts it to lowercase and
* removes ASCII characters, which might be problematic in URLs:
* <ul>
* <li>all whitespaces
* <li>dots ('.')
* <li>(semi-)colons (';' and ':')
* <li>equals ('=')
* <li>ampersands ('&')
* <li>slashes ('/')
* <li>angle brackets ('<' and '>')
* </ul>
*
* @param s
* The String to slugify
* @return The slugified String
* @see #normalize(String)
*/
public static String slugify(String s) {
if (s == null)
return null;
String n = normalize(s);
n = StringUtils.lowerCase(n);
n = n.replaceAll("[\\s.:;&=<>/]", "");
return n;
}
}
Being a German speaker I've included proper handling of German umlauts as well - the list should be easy to extend for other languages.
HTH
EDIT: Note that it may be unsafe to include the returned String in an URL. You should at least HTML encode it to prevent XSS attacks.
$('#fileupload').bind('change', function (e) { //dynamic property binding
alert('hello');// message you want to display
});
You can use this one also
The way to do this is to run the following command:
bundle update --source gem-name
If you have a Decimal or similar numeric type, you can use:
Math.Round(myNumber, 2)
EDIT: So, in your case, it would be:
Public Class Form1
Private Sub btncalc_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btncalc.Click
txtA.Text = Math.Round((Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)), 2)
txtB.Text = Math.Round((Val(txtA.Text) * 1000 / Val(txtG.Text)), 2)
End Sub
End Class
Try this. (Here we use text=Lines
to keep the example self contained but in reality we would replace it with the file name.)
Lines <- "2009-01 12
2009-02 310
2009-03 2379
2009-04 234
2009-05 14
2009-08 1
2009-09 34
2009-10 2386"
library(zoo)
z <- read.zoo(text = Lines, FUN = as.yearmon)
plot(z)
The X axis is not so pretty with this data but if you have more data in reality it might be ok or you can use the code for a fancy X axis shown in the examples section of ?plot.zoo
.
The zoo series, z
, that is created above has a "yearmon"
time index and looks like this:
> z
Jan 2009 Feb 2009 Mar 2009 Apr 2009 May 2009 Aug 2009 Sep 2009 Oct 2009
12 310 2379 234 14 1 34 2386
"yearmon"
can be used alone as well:
> as.yearmon("2000-03")
[1] "Mar 2000"
Note:
"yearmon"
class objects sort in calendar order.
This will plot the monthly points at equally spaced intervals which is likely what is wanted; however, if it were desired to plot the points at unequally spaced intervals spaced in proportion to the number of days in each month then convert the index of z
to "Date"
class: time(z) <- as.Date(time(z))
.
I'm exceptionally new to VBScript, so this may not be considered best practice or there may be a reason it shouldn't be done this that way I'm not yet aware of, but this is the solution I came up with to trim down the amount of error logging code in my main code block.
Dim oConn, connStr
Set oConn = Server.CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;Server=XX;UID=XX;PWD=XX;Databse=XX"
ON ERROR RESUME NEXT
oConn.Open connStr
If err.Number <> 0 Then : showError() : End If
Sub ShowError()
'You could write the error details to the console...
errDetail = "<script>" & _
"console.log('Description: " & err.Description & "');" & _
"console.log('Error number: " & err.Number & "');" & _
"console.log('Error source: " & err.Source & "');" & _
"</script>"
Response.Write(errDetail)
'...you could display the error info directly in the page...
Response.Write("Error Description: " & err.Description)
Response.Write("Error Source: " & err.Source)
Response.Write("Error Number: " & err.Number)
'...or you could execute additional code when an error is thrown...
'Insert error handling code here
err.clear
End Sub
HTML + CSS
solution worked for me:form select:invalid {_x000D_
color: gray;_x000D_
}_x000D_
_x000D_
form select option:first-child {_x000D_
color: gray;_x000D_
}_x000D_
_x000D_
form select:invalid option:not(:first-child) {_x000D_
color: black;_x000D_
}
_x000D_
<form>_x000D_
<select required>_x000D_
<option value="">Select Planet...</option>_x000D_
<option value="earth">Earth</option>_x000D_
<option value="pandora">Pandora</option>_x000D_
</select>_x000D_
</form>
_x000D_
Good Luck...
If you start to do something like this, then I would say it starts to get a bit strange and you're better off moving it to a seperate method that returns
a result upon the matchedCondition.
boolean matched = false;
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(matchedCondition) {
matched = true;
break;
}
}
if(matched) {
break;
}
}
To elaborate on how to clean up the above code, you can refactor, moving the code to a function that returns
instead of using breaks
. This is in general, better dealing with complex/messy breaks
.
public boolean matches()
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(matchedCondition) {
return true;
}
}
}
return false;
}
However for something simple like my below example. By all means use break
!
for(int i = 0; i < 10; i++) {
if(wereDoneHere()) { // we're done, break.
break;
}
}
And changing the conditions, in the above case i
, and j
's value, you would just make the code really hard to read. Also there could be a case where the upper limits (10 in the example) are variables so then it would be even harder to guess what value to set it to in order to exit the loop. You could of course just set i
and j
to Integer.MAX_VALUE, but I think you can see this starts to get messy very quickly. :)
Here is the sample on what worked for me. I think that put method is needed in entity class to map sql columns to java class attributes.
//simpleExample
Query query = em.createNativeQuery(
"SELECT u.name,s.something FROM user u, someTable s WHERE s.user_id = u.id",
NameSomething.class);
List list = (List<NameSomething.class>) query.getResultList();
Entity class:
@Entity
public class NameSomething {
@Id
private String name;
private String something;
// getters/setters
/**
* Generic put method to map JPA native Query to this object.
*
* @param column
* @param value
*/
public void put(Object column, Object value) {
if (((String) column).equals("name")) {
setName(String) value);
} else if (((String) column).equals("something")) {
setSomething((String) value);
}
}
}
Assign position:relative
to .outside
, and then position:absolute; bottom:0;
to your .inside
.
Like so:
.outside {
position:relative;
}
.inside {
position: absolute;
bottom: 0;
}
If you want, you can still run your tests within Spring Context and set the required properties inside Spring configuration class. If you use JUnit, use SpringJUnit4ClassRunner and define dedicated configuration class for your tests like that:
The class under test:
@Component
public SomeClass {
@Autowired
private SomeDependency someDependency;
@Value("${someProperty}")
private String someProperty;
}
The test class:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SomeClassTestsConfig.class)
public class SomeClassTests {
@Autowired
private SomeClass someClass;
@Autowired
private SomeDependency someDependency;
@Before
public void setup() {
Mockito.reset(someDependency);
@Test
public void someTest() { ... }
}
And the configuration class for this test:
@Configuration
public class SomeClassTestsConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer properties() throws Exception {
final PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
Properties properties = new Properties();
properties.setProperty("someProperty", "testValue");
pspc.setProperties(properties);
return pspc;
}
@Bean
public SomeClass getSomeClass() {
return new SomeClass();
}
@Bean
public SomeDependency getSomeDependency() {
// Mockito used here for mocking dependency
return Mockito.mock(SomeDependency.class);
}
}
Having that said, I wouldn't recommend this approach, I just added it here for reference. In my opinion much better way is to use Mockito runner. In that case you don't run tests inside Spring at all, which is much more clear and simpler.
Install Asus PC Link on your PC available here: https://www.asus.com/ph/support/FAQ/1007320/
If you don't wont use jquery.ui(that is highly recommended), you can take a look at Block.UI plugin.
Provide a path (myfolder in this case) and just run:
git diff myfolder/
I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:
<select [(ngModel)]="simpleValue"> // value is a string or number
<option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>
If you want to match on the actual object, I'd do it like this:
<select [(ngModel)]="objValue"> // value is an object
<option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>
Well, I am using Express profiler for that purpose at the moment, the drawback is that it only works for MS SQL Server. You can find this tool here: https://expressprofiler.codeplex.com/
If you have Homebrew installed, you can do this.
# check the zsh info
brew info zsh
# install zsh
brew install --without-etcdir zsh
# add shell path
sudo vim /etc/shells
# add the following line into the very end of the file(/etc/shells)
/usr/local/bin/zsh
# change default shell
chsh -s /usr/local/bin/zsh
Hope it helps, thanks.
Assuming your "states" collection is like:
{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }
The query to find states with null cities would be:
db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});
It is a common mistake to query for nulls as:
db.states.find({"cities.name" : null});
because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.
#include <iostream>
using namespace std ;
typedef int (*Type)[3][3] ;
Type Demo_function( Type ); //prototype
int main (){
cout << "\t\t!!!!!Passing and returning 2D array from function!!!!!\n"
int array[3][3] ;
Type recieve , ptr = &array;
recieve = Demo_function( ptr ) ;
for ( int i = 0 ; i < 3 ; i ++ ){
for ( int j = 0 ; j < 3 ; j ++ ){
cout << (*recieve)[i][j] << " " ;
}
cout << endl ;
}
return 0 ;
}
Type Demo_function( Type array ){/*function definition */
cout << "Enter values : \n" ;
for (int i =0 ; i < 3 ; i ++)
for ( int j = 0 ; j < 3 ; j ++ )
cin >> (*array)[i][j] ;
return array ;
}
Session is used for maintaining a dialogue between server and user. It is more secure because it is stored on the server, we cannot easily access it. It embeds cookies on the user computer. It stores unlimited data.
Cookies are stored on the local computer. Basically, it maintains user identification, meaning it tracks visitors record. It is less secure than session. It stores limited amount of data, and is maintained for a limited time.
As it often happens, this question is confusing as hell. People are coming here having two different tasks in mind:
That's two absolutely different tasks that have nothing in common and cannot be solved by the same function. Ironically, for neither of them the actual PDOStatement::rowCount()
function has to be used.
Let's see why
Before using PDO I just simply used
mysql_num_rows()
.
Means you already did it wrong. Using mysql_num_rows()
or rowCount()
to count the number of rows in the table is a real disaster in terms of consuming the server resources. A database has to read all the rows from the disk, consume the memory on the database server, then send all this heap of data to PHP, consuming PHP process' memory as well, burdening your server with absolute no reason.
Besides, selecting rows only to count them simply makes no sense. A count(*)
query has to be run instead. The database will count the records out of the index, without reading the actual rows and then only one row returned.
For this purpose the code suggested in the accepted answer is fair, save for the fact it won't be an "extra" query but the only query to run.
The second use case is not as disastrous as rather pointless: in case you need to know whether your query returned any data, you always have the data itself!
Say, if you are selecting only one row. All right, you can use the fetched row as a flag:
$stmt->execute();
$row = $stmt->fetch();
if (!$row) { // here! as simple as that
echo 'No data found';
}
In case you need to get many rows, then you can use fetchAll()
.
fetchAll()
is something I won't want as I may sometimes be dealing with large datasets
Yes of course, for the first use case it would be twice as bad. But as we learned already, just don't select the rows only to count them, neither with rowCount()
nor fetchAll()
.
But in case you are going to actually use the rows selected, there is nothing wrong in using fetchAll()
. Remember that in a web application you should never select a huge amount of rows. Only rows that will be actually used on a web page should be selected, hence you've got to use LIMIT
, WHERE
or a similar clause in your SQL. And for such a moderate amount of data it's all right to use fetchAll()
. And again, just use this function's result in the condition:
$stmt->execute();
$data = $stmt->fetchAll();
if (!$data) { // again, no rowCount() is needed!
echo 'No data found';
}
And of course it will be absolute madness to run an extra query only to tell whether your other query returned any rows, as it suggested in the two top answers.
In such a rare case when you need to select a real huge amount of rows (in a console application for example), you have to use an unbuffered query, in order to reduce the amount of memory used. But this is the actual case when rowCount()
won't be available, thus there is no use for this function as well.
Hence, that's the only use case when you may possibly need to run an extra query, in case you'd need to know a close estimate for the number of rows selected.
I know this is an old question but the most up to date answer is to use the Android Support Design library that will make your life easy.
If you are getting this from an outside site it might be helpful to use jQuery's getJSON. If it's a list you can iterate through it with $.each
$.getJSON(url, function (json) {
alert(json.result);
$.each(json.list, function (i, fb) {
alert(fb.result);
});
});
In more simple terms:
Technically, the -u
flag adds a tracking reference to the upstream server you are pushing to.
What is important here is that this lets you do a git pull
without supplying any more arguments. For example, once you do a git push -u origin master
, you can later call git pull
and git will know that you actually meant git pull origin master
.
Otherwise, you'd have to type in the whole command.
I would think Eigenface, which you are doing already, is the way to go if you want to calculate the distance between faces. You could try out different approaches like Support Vector Machine or Hidden Markov Model. I found a page that lists major algorithms that could be used for facial recognition: Face Recognition Homepage.
Also, when you say "better performance," do you mean speed or accuracy? What kind of problem are you having? How varying are the data? Are they mostly frontal face or do they include profiles?
You can use a TextView and change its background to the image you want to use
for example ..and please use mysqli() next time because mysql() is deprecated.
<?php
$select="select * from tbl_assign where id='".$_GET['uid']."'";
$q=mysql_query($select) or die($select);
$row=mysql_fetch_array($q);
?>
<select name="sclient" id="sclient" class="reginput"/>
<option value="">Select Client</option>
<?php $s="select * from tbl_new_user where type='client'";
$q=mysql_query($s) or die($s);
while($rw=mysql_fetch_array($q))
{ ?>
<option value="<?php echo $rw['login_name']; ?>"<?php if($row['clientname']==$rw['login_name']) echo 'selected="selected"'; ?>><?php echo $rw['login_name']; ?></option>
<?php } ?>
</select>
You can view which modules (compiled in) are available via terminal through php -m
A cookie is a object with key value pair to store information related to the customer. Main objective is to personalize the customer's experience.
An utility method can be created like
private Cookie createCookie(String cookieName, String cookieValue) {
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setPath("/");
cookie.setMaxAge(MAX_AGE_SECONDS);
cookie.setHttpOnly(true);
cookie.setSecure(true);
return cookie;
}
If storing important information then we should alsways put setHttpOnly so that the cookie cannot be accessed/modified via javascript. setSecure is applicable if you are want cookies to be accessed only over https protocol.
using above utility method you can add cookies to response as
Cookie cookie = createCookie("name","value");
response.addCookie(cookie);
You could make use of Prepared Stements
like this.
set @query = concat( "select name from " );
set @query = concat( "table_name"," [where condition] " );
prepare stmt from @like_q;
execute stmt;
lets assume that your pem file and somefile.txt you want to send is in Downloads folder
scp -i ~/Downloads/mykey.pem ~/Downloads/somefile.txt [email protected]:~/
let me know if it doesn't work
Simply delete your local master branch and recreate it like so:
git branch -D master
git checkout origin/master -b master
I found the solution after a few tries, I hope this can help you. Add the following to your <ReactTable>
component:
getTrProps={(state, rowInfo) => {
if (rowInfo && rowInfo.row) {
return {
onClick: (e) => {
this.setState({
selected: rowInfo.index
})
},
style: {
background: rowInfo.index === this.state.selected ? '#00afec' : 'white',
color: rowInfo.index === this.state.selected ? 'white' : 'black'
}
}
}else{
return {}
}
}
In your state
don't forget to add a null selected
value, like:
state = { selected: null }
The pros and cons are pretty much identical.It depends on whether you want this or not.
Be careful, if MySQL timezone differs from your system time (for instance PHP), comparing the time or printing to the user will involve some tinkering.
You need to define border-width:1px
Your code should read:
$(this).css({"border-color": "#C1E0FF",
"border-width":"1px",
"border-style":"solid"});
You should ideally use a class and addClass/removeClass
$(this).addClass('borderClass');
$(this).removeClass('borderClass');
and in your CSS:
.borderClass{
border-color: #C1E0FF;
border-width:1px;
border-style: solid;
/** OR USE INLINE
border: 1px solid #C1E0FF;
**/
}
jsfiddle working example: http://jsfiddle.net/gorelative/tVbvF/\
jsfiddle with animate: http://jsfiddle.net/gorelative/j9Xxa/
This just gives you an example of how it could work, you should get the idea.. There are better ways of doing this most likely.. like using a toggle()
My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.
I use a dictionary to memoize values. That seems to be a bottleneck.
This is evidence of a bug in your memoization method.
To get the titles for dates greater than a week ago today, use this:
SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7
Other people have suggested using in.nextLine()
to clear the buffer, which works for single-line input. As comments point out, however, sometimes System.in input can be multi-line.
You can instead create a new Scanner object where you want to clear the buffer if you are using System.in and not some other InputStream.
in = new Scanner(System.in);
If you do this, don't call in.close()
first. Doing so will close System.in, and so you will get NoSuchElementExceptions on subsequent calls to in.nextInt();
System.in probably shouldn't be closed during your program.
(The above approach is specific to System.in. It might not be appropriate for other input streams.)
If you really need to close your Scanner object before creating a new one, this StackOverflow answer suggests creating an InputStream wrapper for System.in that has its own close() method that doesn't close the wrapped System.in stream. This is overkill for simple programs, though.
You likely need to re-start VNC on both ends. i.e. when you say "restarted VNC", you probably just mean the client. But what about the other end? You likely need to re-start that end too. The root cause is likely a conflict. Many apps spy on the clipboard when they shouldn't. And many apps are not forgiving when they go to open the clipboard and can't. Robust ones will retry, others will simply not anticipate a failure and then they get fouled up and need to be restarted. Could be VNC, or it could be another app that's "listening" to the clipboard viewer chain, where it is obligated to pass along notifications to the other apps in the chain. If the notifications aren't sent, then VNC may not even know that there has been a clipboard update.
Here's a cool ASP.NET Web control called Multi-Select List Field at http://www.xnodesystems.com/. It's capable of:
(1) Multi-select; (2) Auto-complete; (3) Validation.
svn revert deletedDirectory
Here's the documentation for the svn revert
command.
If deletedDirectory
was deleted using rmdir
and not svn rm
, you'll need to do
svn update deletedDirectory
instead.
As explained in the documentation, the finally
clause is intended to define clean-up actions that must be executed under all circumstances.
If
finally
is present, it specifies a ‘cleanup’ handler. Thetry
clause is executed, including anyexcept
andelse
clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. Thefinally
clause is executed. If there is a saved exception it is re-raised at the end of thefinally
clause.
An example:
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
As you can see, the finally
clause is executed in any event. The TypeError
raised by dividing two strings is not handled by the except
clause and therefore re-raised after the finally
clause has been executed.
In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.
You can't do this in C#. Use a const int
instead.
Command line arguments is one way to pass the arguments in. This msdn sample is worth checking out. The MSDN Page for command line arguments is also worth reading.
From within visual studio you can set the command line arguments by Choosing the properties of your console application then selecting the Debug tab
You need to remove the object from your data array before you call deleteRowsAtIndexPaths:withRowAnimation:
. So, your code should look like this:
// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//when delete is tapped
[currentCart removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
You can also simplify your code a little by using the array creation shortcut @[]
:
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
I would do something like this:
;WITH x
AS (SELECT *,
Row_number()
OVER(
partition BY employeeid
ORDER BY datestart) rn
FROM employeehistory)
SELECT *
FROM x x1
LEFT OUTER JOIN x x2
ON x1.rn = x2.rn + 1
Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.
DBMS is the software program that is used to manage all the database that are stored on the network or system hard disk. whereas RDBMS is the database system in which the relationship among different tables are maintained.
Additional Solution: use Restul api wrapper libraries written in Java
/ python
/ Ruby
- An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.
For documentation and links: Remote Access API
I liked FakeRainBrigand's answer, however it contains a few problems: It can not handle whitespace between a quote and a comma, and does not support 2 consecutive commas. I tried editing his answer but my edit got rejected by reviewers that apparently did not understand my code. Here is my version of FakeRainBrigand's code. There is also a fiddle: http://jsfiddle.net/xTezm/46/
String.prototype.splitCSV = function() {
var matches = this.match(/(\s*"[^"]+"\s*|\s*[^,]+|,)(?=,|$)/g);
for (var n = 0; n < matches.length; ++n) {
matches[n] = matches[n].trim();
if (matches[n] == ',') matches[n] = '';
}
if (this[0] == ',') matches.unshift("");
return matches;
}
var string = ',"string, duppi, du" , 23 ,,, "string, duppi, du",dup,"", , lala';
var parsed = string.splitCSV();
alert(parsed.join('|'));
I faced same problem. And got the solution when I use this code to call context. I use Grid Layout. If you use another one you can change.
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),1));
if you have adapter to set. So you can follow this. Just call the getContext
adapter = new Adapter(getContext(), myModelList);
If you have Toast to show, use same thing above
Toast.makeText(getContext(), "Error in "+e, Toast.LENGTH_SHORT).show();
Hope this will work.
HappyCoding
You could try to force the browser to open a "Save As..." dialog by doing something like:
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');
echo "cell 1, cell 2";
Which should work across most major browsers.
var numexcute = 0;
var interval;
$(document).bind('click', function () {
interval = setInterval(function () {
if (numexcute >= 20) {
clearInterval(interval);
numexcute = 0;
}
$('#leftpane').css('height', 'auto');
$('#rightpane').css('height', 'auto');
if ($('#leftpane').height() < $('#rightpane').height())
$('#leftpane').height($('#rightpane').height());
if ($('#leftpane').height() > $('#rightpane').height())
$('#rightpane').height($('#leftpane').height());
numexcute++;
}, 10);
});
Two easy ways:
Using hive conf
hive> set USER_NAME='FOO';
hive> select * from foobar where NAME = '${hiveconf:USER_NAME}';
Using hive vars
On your CLI set vars and then use them in hive
set hivevar:USER_NAME='FOO';
hive> select * from foobar where NAME = '${USER_NAME}';
hive> select * from foobar where NAME = '${hivevar:USER_NAME}';
Documentation: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+VariableSubstitution
You can always start by making a lookup table based on common aspect ratios. Check https://en.wikipedia.org/wiki/Display_aspect_ratio Then you can simply do the division
For real life problems, you can do something like below
let ERROR_ALLOWED = 0.05
let STANDARD_ASPECT_RATIOS = [
[1, '1:1'],
[4/3, '4:3'],
[5/4, '5:4'],
[3/2, '3:2'],
[16/10, '16:10'],
[16/9, '16:9'],
[21/9, '21:9'],
[32/9, '32:9'],
]
let RATIOS = STANDARD_ASPECT_RATIOS.map(function(tpl){return tpl[0]}).sort()
let LOOKUP = Object()
for (let i=0; i < STANDARD_ASPECT_RATIOS.length; i++){
LOOKUP[STANDARD_ASPECT_RATIOS[i][0]] = STANDARD_ASPECT_RATIOS[i][1]
}
/*
Find the closest value in a sorted array
*/
function findClosest(arrSorted, value){
closest = arrSorted[0]
closestDiff = Math.abs(arrSorted[0] - value)
for (let i=1; i<arrSorted.length; i++){
let diff = Math.abs(arrSorted[i] - value)
if (diff < closestDiff){
closestDiff = diff
closest = arrSorted[i]
} else {
return closest
}
}
return arrSorted[arrSorted.length-1]
}
/*
Estimate the aspect ratio based on width x height (order doesn't matter)
*/
function estimateAspectRatio(dim1, dim2){
let ratio = Math.max(dim1, dim2) / Math.min(dim1, dim2)
if (ratio in LOOKUP){
return LOOKUP[ratio]
}
// Look by approximation
closest = findClosest(RATIOS, ratio)
if (Math.abs(closest - ratio) <= ERROR_ALLOWED){
return '~' + LOOKUP[closest]
}
return 'non standard ratio: ' + Math.round(ratio * 100) / 100 + ':1'
}
Then you simply give the dimensions in any order
estimateAspectRatio(1920, 1080) // 16:9
estimateAspectRatio(1920, 1085) // ~16:9
estimateAspectRatio(1920, 1150) // non standard ratio: 1.65:1
estimateAspectRatio(1920, 1200) // 16:10
estimateAspectRatio(1920, 1220) // ~16:10
Using regular expressions, you can use re.finditer
to find all (non-overlapping) occurences:
>>> import re
>>> text = 'Allowed Hello Hollow'
>>> for m in re.finditer('ll', text):
print('ll found', m.start(), m.end())
ll found 1 3
ll found 10 12
ll found 16 18
Alternatively, if you don't want the overhead of regular expressions, you can also repeatedly use str.find
to get the next index:
>>> text = 'Allowed Hello Hollow'
>>> index = 0
>>> while index < len(text):
index = text.find('ll', index)
if index == -1:
break
print('ll found at', index)
index += 2 # +2 because len('ll') == 2
ll found at 1
ll found at 10
ll found at 16
This also works for lists and other sequences.
2's complement of a given number is the no. got by adding 1 with the 1's complement of the no. suppose, we have a binary no.: 10111001101 It's 1's complement is : 01000110010 And it's 2's complement will be : 01000110011
In Python-3.6
I can see the suggestion in the traceback. That's quite helpful.
Hence I will say you guys to pay attention to the error you got, most of the time answers are within that problem ;).
And then as suggested by other folks here either using python terminal or using a command like python -c "import nltk; nltk.download('wordnet')"
we can install them on the fly.
You just need to run that command once and then it will save the data locally in your home directory.
@vladima replied to this issue on GitHub:
The way the compiler resolves modules is controlled by moduleResolution option that can be either
node
orclassic
(more details and differences can be found here). If this setting is omitted the compiler treats this setting to benode
if module iscommonjs
andclassic
- otherwise. In your case if you wantclassic
module resolution strategy to be used withcommonjs
modules - you need to set it explicitly by using{ "compilerOptions": { "moduleResolution": "node" } }
Try this,
element.style {
background: rgba(0, 0, 0, 0) url("img/shopping_bgImg.jpg") no-repeat scroll center center / cover;
}
Angular 2, 4 and Angular 5 compatible!
You have provided so few details, so I'll try to answer your question without them.
You can use Interpolation:
<img src={{imagePath}} />
Or you can use a template expression:
<img [src]="imagePath" />
In a ngFor loop it might look like this:
<div *ngFor="let student of students">
<img src={{student.ImagePath}} />
</div>
The best way to prevent direct access to files is to place them outside of the web-server document root (usually, one level above). You can still include them, but there is no possibility of someone accessing them through an http request.
I usually go all the way, and place all of my PHP files outside of the document root aside from the bootstrap file - a lone index.php in the document root that starts routing the entire website/application.
It's worth mentioning that
$('a').attr('href'); // gets the actual value
$('a').prop('href'); // gets the full URL always
How about:
select salesid from AXDelNotesNoTracking group by salesid having count(*) > 1;
You can simply do the following inside your TR loop:
$(this).find('td').each (function() {
// do your cool stuff
});
if (!Directory.Exists(Path.GetDirectoryName(fileName)))
{
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
}
Download this jar
It resolved my problem, this is 1.7.
Immutable variable with immutable (read only) list:
val users: List<User> = listOf( User("Tom", 32), User("John", 64) )
Immutable variable with mutable list:
val users: MutableList<User> = mutableListOf( User("Tom", 32), User("John", 64) )
or without initial value - empty list and without explicit variable type:
val users = mutableListOf<User>()
//or
val users = ArrayList<User>()
users.add(anohterUser)
or users += anotherUser
(under the hood it's users.add(anohterUser)
)Mutable variable with immutable list:
var users: List<User> = listOf( User("Tom", 32), User("John", 64) )
or without initial value - empty list and without explicit variable type:
var users = emptyList<User>()
users += anotherUser
- *it creates new ArrayList and assigns it to users
Mutable variable with mutable list:
var users: MutableList<User> = mutableListOf( User("Tom", 32), User("John", 64) )
or without initial value - empty list and without explicit variable type:
var users = emptyList<User>().toMutableList()
//or
var users = ArrayList<User>()
users.add(anohterUser)
users += anotherUser
Error: Kotlin: Assignment operators ambiguity:
public operator fun Collection.plus(element: String): List defined in kotlin.collections
@InlineOnly public inline operator fun MutableCollection.plusAssign(element: String): Unit defined in kotlin.collections
see also:
https://kotlinlang.org/docs/reference/collections.html
I happen to miss spaces in my query and this error comes.
Ex: $sql= "SELECT * FROM";
$sql .= "table1";
Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".
A HandlerInterceptor gives you more fine-grained control than a filter, because you have access to the actual target "handler" - this means that whatever action you perform can vary depending on what the request is actually doing (whereas the servlet filter is generically applied to all requests - only able to take into account the parameters of each request). The handlerInterceptor also provides 3 different methods, so that you can apply behavior prior to calling a handler, after the handler has completed but prior to view rendering (where you may even bypass view rendering altogether), or after the view itself has been rendered. Also, you can set up different interceptors for different groups of handlers - the interceptors are configured on the handlerMapping, and there may be multiple handlerMappings.
Therefore, if you have a need to do something completely generic (e.g. log all requests), then a filter is sufficient - but if the behavior depends on the target handler or you want to do something between the request handling and view rendering, then the HandlerInterceptor provides that flexibility.
Reference: http://static.springframework.org/sp...ng-interceptor
Just like that nice warning you got, you are trying to do something that is an Anti-Pattern in React. This is a no-no. React is intended to have an unmount happen from a parent to child relationship. Now if you want a child to unmount itself, you can simulate this with a state change in the parent that is triggered by the child. let me show you in code.
class Child extends React.Component {
constructor(){}
dismiss() {
this.props.unmountMe();
}
render(){
// code
}
}
class Parent ...
constructor(){
super(props)
this.state = {renderChild: true};
this.handleChildUnmount = this.handleChildUnmount.bind(this);
}
handleChildUnmount(){
this.setState({renderChild: false});
}
render(){
// code
{this.state.renderChild ? <Child unmountMe={this.handleChildUnmount} /> : null}
}
}
this is a very simple example. but you can see a rough way to pass through to the parent an action
That being said you should probably be going through the store (dispatch action) to allow your store to contain the correct data when it goes to render
I've done error/status messages for two separate applications, both went through the store. It's the preferred method... If you'd like I can post some code as to how to do that.
Few things to note first. this is in typescript so you would need to remove the type declarations :)
I am using the npm packages lodash for operations, and classnames (cx alias) for inline classname assignment.
The beauty of this setup is I use a unique identifier for each notification when the action creates it. (e.g. notify_id). This unique ID is a Symbol()
. This way if you want to remove any notification at any point in time you can because you know which one to remove. This notification system will let you stack as many as you want and they will go away when the animation is completed. I am hooking into the animation event and when it finishes I trigger some code to remove the notification. I also set up a fallback timeout to remove the notification just in case the animation callback doesn't fire.
import { USER_SYSTEM_NOTIFICATION } from '../constants/action-types';
interface IDispatchType {
type: string;
payload?: any;
remove?: Symbol;
}
export const notifySuccess = (message: any, duration?: number) => {
return (dispatch: Function) => {
dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: true, message, notify_id: Symbol(), duration } } as IDispatchType);
};
};
export const notifyFailure = (message: any, duration?: number) => {
return (dispatch: Function) => {
dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: false, message, notify_id: Symbol(), duration } } as IDispatchType);
};
};
export const clearNotification = (notifyId: Symbol) => {
return (dispatch: Function) => {
dispatch({ type: USER_SYSTEM_NOTIFICATION, remove: notifyId } as IDispatchType);
};
};
const defaultState = {
userNotifications: []
};
export default (state: ISystemNotificationReducer = defaultState, action: IDispatchType) => {
switch (action.type) {
case USER_SYSTEM_NOTIFICATION:
const list: ISystemNotification[] = _.clone(state.userNotifications) || [];
if (_.has(action, 'remove')) {
const key = parseInt(_.findKey(list, (n: ISystemNotification) => n.notify_id === action.remove));
if (key) {
// mutate list and remove the specified item
list.splice(key, 1);
}
} else {
list.push(action.payload);
}
return _.assign({}, state, { userNotifications: list });
}
return state;
};
in the base render for your application you would render the notifications
render() {
const { systemNotifications } = this.props;
return (
<div>
<AppHeader />
<div className="user-notify-wrap">
{ _.get(systemNotifications, 'userNotifications') && Boolean(_.get(systemNotifications, 'userNotifications.length'))
? _.reverse(_.map(_.get(systemNotifications, 'userNotifications', []), (n, i) => <UserNotification key={i} data={n} clearNotification={this.props.actions.clearNotification} />))
: null
}
</div>
<div className="content">
{this.props.children}
</div>
</div>
);
}
user notification class
/*
Simple notification class.
Usage:
<SomeComponent notifySuccess={this.props.notifySuccess} notifyFailure={this.props.notifyFailure} />
these two functions are actions and should be props when the component is connect()ed
call it with either a string or components. optional param of how long to display it (defaults to 5 seconds)
this.props.notifySuccess('it Works!!!', 2);
this.props.notifySuccess(<SomeComponentHere />, 15);
this.props.notifyFailure(<div>You dun goofed</div>);
*/
interface IUserNotifyProps {
data: any;
clearNotification(notifyID: symbol): any;
}
export default class UserNotify extends React.Component<IUserNotifyProps, {}> {
public notifyRef = null;
private timeout = null;
componentDidMount() {
const duration: number = _.get(this.props, 'data.duration', '');
this.notifyRef.style.animationDuration = duration ? `${duration}s` : '5s';
// fallback incase the animation event doesn't fire
const timeoutDuration = (duration * 1000) + 500;
this.timeout = setTimeout(() => {
this.notifyRef.classList.add('hidden');
this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
}, timeoutDuration);
TransitionEvents.addEndEventListener(
this.notifyRef,
this.onAmimationComplete
);
}
componentWillUnmount() {
clearTimeout(this.timeout);
TransitionEvents.removeEndEventListener(
this.notifyRef,
this.onAmimationComplete
);
}
onAmimationComplete = (e) => {
if (_.get(e, 'animationName') === 'fadeInAndOut') {
this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
}
}
handleCloseClick = (e) => {
e.preventDefault();
this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
}
assignNotifyRef = target => this.notifyRef = target;
render() {
const {data, clearNotification} = this.props;
return (
<div ref={this.assignNotifyRef} className={cx('user-notification fade-in-out', {success: data.isSuccess, failure: !data.isSuccess})}>
{!_.isString(data.message) ? data.message : <h3>{data.message}</h3>}
<div className="close-message" onClick={this.handleCloseClick}>+</div>
</div>
);
}
}
Use json_decode
to convert the JSON string to a PHP array, then use normal PHP array functions on it.
$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$data = json_decode($json);
var_dump($data[0]['var1']); // outputs '9'
If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1)
next to it and copy the formula down. This assumes you have your values in range A1:A100
and the de-duplicated values are in column B.
I've had the same problem you describe. The web site I'm building can be accessed from a mobile phone and from the browser so I need an api to allow users to signup, login and do some specific tasks. Furthermore, I need to support scalability, the same code running on different processes/machines.
Because users can CREATE resources (aka POST/PUT actions) you need to secure your api. You can use oauth or you can build your own solution but keep in mind that all the solutions can be broken if the password it's really easy to discover. The basic idea is to authenticate users using the username, password and a token, aka the apitoken. This apitoken can be generated using node-uuid and the password can be hashed using pbkdf2
Then, you need to save the session somewhere. If you save it in memory in a plain object, if you kill the server and reboot it again the session will be destroyed. Also, this is not scalable. If you use haproxy to load balance between machines or if you simply use workers, this session state will be stored in a single process so if the same user is redirected to another process/machine it will need to authenticate again. Therefore you need to store the session in a common place. This is typically done using redis.
When the user is authenticated (username+password+apitoken) generate another token for the session, aka accesstoken. Again, with node-uuid. Send to the user the accesstoken and the userid. The userid (key) and the accesstoken (value) are stored in redis with and expire time, e.g. 1h.
Now, every time the user does any operation using the rest api it will need to send the userid and the accesstoken.
If you allow the users to signup using the rest api, you'll need to create an admin account with an admin apitoken and store them in the mobile app (encrypt username+password+apitoken) because new users won't have an apitoken when they sign up.
The web also uses this api but you don't need to use apitokens. You can use express with a redis store or use the same technique described above but bypassing the apitoken check and returning to the user the userid+accesstoken in a cookie.
If you have private areas compare the username with the allowed users when they authenticate. You can also apply roles to the users.
Summary:
An alternative without apitoken would be to use HTTPS and to send the username and password in the Authorization header and cache the username in redis.
You must use the following:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:yourDateHere];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
[gregorian release];
There is no difference between NSDate* now and NSDate *now, it's just a matter of preference. From the compiler perspective, nothing changes.
Step 1: You only need to follow this step if you've deleted/altered the build directory in any way: Download and make/make install using the exact same procedure as you did before.
Step 2: try make uninstall.
cd $SOURCE_DIR
sudo make uninstall
If this succeeds you are done. If you're paranoid you may also try the steps of "Method #3" to make sure make uninstall
didn't miss any files.
Overview of the process
In debian based systems (e.g. Ubuntu) you can create a .deb
package very easily by using a tool named checkinstall
. You then install the .deb package (this will make your debian system realize that the all parts of your package have been indeed installed) and finally uninstall it to let your package manager properly cleanup your system.
Step by step
sudo apt-get -y install checkinstall
cd $SOURCE_DIR
sudo checkinstall
At this point checkinstall
will prompt for a package name. Enter something a bit descriptive and note it because you'll use it in a minute. It will also prompt for a few more data that you can ignore. If it complains about the version not been acceptable just enter something reasonable like 1.0
. When it completes you can install and finally uninstall:
sudo dpkg -i $PACKAGE_NAME_YOU_ENTERED
sudo dpkg -r $PACKAGE_NAME_YOU_ENTERED
If a file install_manifest.txt
exists in your source dir it should contain the filenames of every single file that the installation created.
So first check the list of files and their mod-time:
cd $SOURCE_DIR
sudo xargs -I{} stat -c "%z %n" "{}" < install_manifest.txt
You should get zero errors and the mod-times of the listed files should be on or after the installation time. If all is OK you can delete them in one go:
cd $SOURCE_DIR
mkdir deleted-by-uninstall
sudo xargs -I{} mv -t deleted-by-uninstall "{}" < install_manifest.txt
User Merlyn Morgan-Graham however has a serious notice regarding this method that you should keep in mind (copied here verbatim): "Watch out for files that might also have been installed by other packages. Simply deleting these files [...] could break the other packages.". That's the reason that we've created the deleted-by-uninstall
dir and moved files there instead of deleting them.
99% of this post existed in other answers. I just collected everything useful in a (hopefully) easy to follow how-to and tried to give extra attention to important details (like quoting xarg arguments and keeping backups of deleted files).
I've had to try to 'fix' a number of UTF8 broken situations in the past, and unfortunately it's never easy, and often rather impossible.
Unless you can determine exactly how it was broken, and it was always broken in that exact same way, then it's going to be hard to 'undo' the damage.
If you want to try to undo the damage, your best bet would be to start writing some sample code, where you attempt numerous variations on calls to mb_convert_encoding() to see if you can find a combination of 'from' and 'to' that fixes your data. In the end, it's often best to not even bother worrying about fixing the old data because of the pain levels involved, but instead to just fix things going forward.
However, before doing this, you need to make sure that you fix everything that is causing this issue in the first place. You've already mentioned that your DB table collation and editors are set properly. But there are more places where you need to check to make sure that everything is properly UTF-8:
If you miss up on any one step through your whole process, the encoding can be mangled and problems arise. Once you get in the 'groove' of doing utf-8 though, this all becomes second nature. And of course, PHP6 is supposed to be fully unicode complaint from the getgo, which will make lots of this easier (hopefully)
item.date = $filter('date')(item.date, "dd/MM/yyyy"); // for conversion to string
http://docs.angularjs.org/api/ng.filter:date
But if you are using HTML5 type="date" then the ISO format yyyy-MM-dd MUST be used.
item.dateAsString = $filter('date')(item.date, "yyyy-MM-dd"); // for type="date" binding
<input type="date" ng-model="item.dateAsString" value="{{ item.dateAsString }}" pattern="dd/MM/YYYY"/>
http://www.w3.org/TR/html-markup/input.date.html
NOTE: use of pattern="" with type="date" looks non-standard, but it appears to work in the expected way in Chrome 31.
Adding one more obnoxious alternative to the list:
perl -pe'$.<=1||last' file
# or
perl -pe'$.<=1||last' < file
# or
cat file | perl -pe'$.<=1||last'
Try using the non-breaking hyphen ‑
. I've replaced the dash with that character in your jsfiddle, shrunk the frame down as small as it can go, and the line doesn't split there any more.
rdtsc solution did not work for me.
Firstly, I use Visual Studio 2015 Express, for which installer "modify" query does not propose any "Common Tools for Visual C++ 2015" option you could uncheck.
Secondly, even after 2 uninstall/reinstall (many hours waiting for them to complete...), the problem still remains.
I finally fixed the issue by reinstalling the whole Windows SDK from a standalone installer (independently from Visual C++ 2015 install): https://developer.microsoft.com/fr-fr/windows/downloads/windows-8-1-sdk or https://developer.microsoft.com/fr-fr/windows/downloads/windows-10-sdk
This fixed the issue for me.
The existing explanations aren't really complete without the actual rule from the Standard, found in 6.7:
The zero-initialization of all block-scope variables with static storage duration or thread storage duration is performed before any other initialization takes place. Constant initialization of a block-scope entity with static storage duration, if applicable, is performed before its block is first entered. An implementation is permitted to perform early initialization of other block-scope variables with static or thread storage duration under the same conditions that an implementation is permitted to statically initialize a variable with static or thread storage duration in namespace scope. Otherwise such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.
You can try to do like this:
var daysPassed = (DateTime.UtcNow - expiryDate).Days;
if (daysPassed > 30)
{
// ...
}
Had the same problem. Here's how I solved it: Go to Package Explorer. Right click on JRE System Library and go to Properties. In the Classpath Container > Select JRE for the project build path select the third option (Workspace default JRE).
In the notification payload of the notification there is a sound key.
From the official documentation its use is:
Indicates a sound to play when the device receives a notification. Supports default or the filename of a sound resource bundled in the app. Sound files must reside in /res/raw/.
Eg:
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark",
"icon" : "myicon",
"sound" : "mySound"
}
}
If you want to use default sound of the device, you should use: "sound": "default"
.
See this link for all possible keys in the payloads: https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support
For those who don't know firebase handles notifications differently when the app is in background. In this case the onMessageReceived function is not called.
When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default. This includes messages that contain both notification and data payload. In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
Maybe this has been answered already (a few answers above are "correct" ways of doing this), but I thought I'd just add my solution as well.
Our iFrame is loaded within a div, hence I needed something else then window.height. And seeing our project already relies heavily on jQuery, I find this to be the most elegant solution:
$("iframe").height($("#middle").height());
Where of course "#middle" is the id of the div. The only extra thing you'll need to do is recall this size change whenever the user resizes the window.
$(window).resize(function() {
$("iframe").height($("#middle").height());
});
C doesn't have exceptions.
There are various hacky implementations that try to do it (one example at: http://adomas.org/excc/).
Found a site on google explaining some changes, according to the author of the page fb does not allow custom buttons. Heres the website.
Unfortunately, it’s against Facebook’s developer policies, which state:
You must not circumvent our intended limitations on core Facebook features.
The Facebook Connect button is intended to be rendered in FBML, which means it’s only meant to look the way Facebook lets it.
This isn't an answer. I was struggling but then realized that my install was trying to connect to internet to download dependencies.
So, I downloaded and installed dependencies first and then installed with below command. It worked
python -m pip install filename.tar.gz
I think it's worth looking at GNU "time" command source code. time It outputs user/system cpu time along with real elapsed time. It calls wait3/wait4 system call (if available) and otherwise it calls times system call. wait* system call returns a "rusage" struct variable and times system call returns "tms". Also, you can have a look at getrusage system call which also return very interesting timing information. time
All of these internally end up calling a method called InternalGetValueAsString
. The difference between ToString
and GetName
would be that GetName
has to verify a few things first:
GetType
on the value to check this. .ToString
doesn't have to worry about any of these above issues, because it is called on an instance of the class itself, and not on a passed in version, therefore, due to the fact that the .ToString
method doesn't have the same verification issues as the static methods, I would conclude that .ToString
is the fastest way to get the value as a string.
Redacted version of my article FTP Connection Modes (Active vs. Passive):
FTP connection mode (active or passive), determines how a data connection is established. In both cases, a client creates a TCP control connection to an FTP server command port 21. This is a standard outgoing connection, as with any other file transfer protocol (SFTP, SCP, WebDAV) or any other TCP client application (e.g. web browser). So, usually there are no problems when opening the control connection.
Where FTP protocol is more complicated comparing to the other file transfer protocols are file transfers. While the other protocols use the same connection for both session control and file (data) transfers, the FTP protocol uses a separate connection for the file transfers and directory listings.
In the active mode, the client starts listening on a random port for incoming data connections from the server (the client sends the FTP command PORT
to inform the server on which port it is listening). Nowadays, it is typical that the client is behind a firewall (e.g. built-in Windows firewall) or NAT router (e.g. ADSL modem), unable to accept incoming TCP connections.
For this reason the passive mode was introduced and is mostly used nowadays. Using the passive mode is preferable because most of the complex configuration is done only once on the server side, by experienced administrator, rather than individually on a client side, by (possibly) inexperienced users.
In the passive mode, the client uses the control connection to send a PASV
command to the server and then receives a server IP address and server port number from the server, which the client then uses to open a data connection to the server IP address and server port number received.
With the passive mode, most of the configuration burden is on the server side. The server administrator should setup the server as described below.
The firewall and NAT on the FTP server side have to be configured not only to allow/route the incoming connections on FTP port 21 but also a range of ports for the incoming data connections. Typically, the FTP server software has a configuration option to setup a range of the ports, the server will use. And the same range has to be opened/routed on the firewall/NAT.
When the FTP server is behind a NAT, it needs to know it's external IP address, so it can provide it to the client in a response to PASV
command.
With the active mode, most of the configuration burden is on the client side.
The firewall (e.g. Windows firewall) and NAT (e.g. ADSL modem routing rules) on the client side have to be configured to allow/route a range of ports for the incoming data connections. To open the ports in Windows, go to Control Panel > System and Security > Windows Firewall > Advanced Settings > Inbound Rules > New Rule. For routing the ports on the NAT (if any), refer to its documentation.
When there's NAT in your network, the FTP client needs to know its external IP address that the WinSCP needs to provide to the FTP server using PORT
command. So that the server can correctly connect back to the client to open the data connection. Some FTP clients are capable of autodetecting the external IP address, some have to be manually configured.
Some firewalls/NATs try to automatically open/close data ports by inspecting FTP control connection and/or translate the data connection IP addresses in control connection traffic.
With such a firewall/NAT, the above configuration is not necessary for a plain unencrypted FTP. But this cannot work with FTPS, as the control connection traffic is encrypted and the firewall/NAT cannot inspect nor modify it.
If you wish your class to be compatible with the Java Beans specification, so that tools utilizing reflection (e.g. JavaBuilders, JGoodies Binding) can recognize boolean getters, either use getXXXX()
or isXXXX()
as a method name. From the Java Beans spec:
8.3.2 Boolean properties
In addition, for boolean properties, we allow a getter method to match the pattern:
public boolean is
<PropertyName>()
;This “is<PropertyName>” method may be provided instead of a “get<PropertyName>” method, or it may be provided in addition to a “get<PropertyName>” method. In either case, if the “is<PropertyName>” method is present for a boolean property then we will use the “is<PropertyName>” method to read the property value. An example boolean property might be:
public boolean isMarsupial(); public void setMarsupial(boolean m);
hex_map = {0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:'A', 11:'B', 12:'C', 13:'D', 14:'E', 15:'F'}
def to_hex(n):
result = ""
if n == 0:
return '0'
while n != 0:
result += str(hex_map[(n % 16)])
n = n // 16
return '0x'+result[::-1]
The quickest fix would be to explicitly use the jQuery $ from the global context (which has been extended with your $.modal() because you referenced that in your script tag when you did ):
window.$('#scheduleentry-modal').modal('show') // to show
window.$('#scheduleentry-modal').modal('hide') // to hide
so this is how you can about it on react
import React, { Component } from 'react';
export default Modal extends Component {
componentDidMount() {
window.$('#Modal').modal('show');
}
handleClose() {
window.$('#Modal').modal('hide');
}
render() {
<
div className = 'modal fade'
id = 'ModalCenter'
tabIndex = '-1'
role = 'dialog'
aria - labelledby = 'ModalCenterTitle'
data - backdrop = 'static'
aria - hidden = 'true' >
<
div className = 'modal-dialog modal-dialog-centered'
role = 'document' >
<
div className = 'modal-content' >
// ...your modal body
<
button
type = 'button'
className = 'btn btn-secondary'
onClick = {
this.handleClose
} >
Close <
/button> < /
div > <
/div> < /
div >
}
}
MinGW
forked from version 1.3.3 ofCygwin
. Although bothCygwin
andMinGW
can be used to portUNIX
software toWindows
, they have different approaches:Cygwin
aims to provide a completePOSIX layer
that provides emulations of several system calls and libraries that exist onLinux
,UNIX
, and theBSD
variants. ThePOSIX layer
runs on top ofWindows
, sacrificing performance where necessary for compatibility. Accordingly, this approach requiresWindows
programs written withCygwin
to run on top of a copylefted compatibility library that must be distributed with the program, along with the program'ssource code
.MinGW
aims to provide native functionality and performance via directWindows API calls
. UnlikeCygwin
,MinGW
does not require a compatibility layerDLL
and thus programs do not need to be distributed withsource code
.Because
MinGW
is dependent uponWindows API calls
, it cannot provide a fullPOSIX API
; it is unable to compile someUNIX applications
that can be compiled withCygwin
. Specifically, this applies to applications that requirePOSIX
functionality likefork()
,mmap()
orioctl()
and those that expect to be run in aPOSIX environment
. Applications written using across-platform library
that has itself been ported toMinGW
, such asSDL
,wxWidgets
,Qt
, orGTK+
, will usually compile as easily inMinGW
as they would inCygwin
.The combination of
MinGW
andMSYS
provides a small, self-contained environment that can be loaded onto removable media without leaving entries in the registry or files on the computer.Cygwin
Portable provides a similar feature. By providing more functionality,Cygwin
becomes more complicated to install and maintain.It is also possible to
cross-compile Windows applications
withMinGW-GCC under POSIX systems
. This means that developers do not need a Windows installation withMSYS
to compile software that will run onWindows
withoutCygwin
.
The problem is how you've attached the listener:
<input type="checkbox" ... onchange="doalert(this.id)">
Inline listeners are effectively wrapped in a function which is called with the element as this. That function then calls the doalert function, but doesn't set its this so it will default to the global object (window in a browser).
Since the window object doesn't have a checked property, this.checked
always resolves to false.
If you want this within doalert to be the element, attach the listener using addEventListener:
window.onload = function() {
var input = document.querySelector('#g01-01');
if (input) {
input.addEventListener('change', doalert, false);
}
}
Or if you wish to use an inline listener:
<input type="checkbox" ... onchange="doalert.call(this, this.id)">
These specific lines are the usual wrapper for jQuery plugins:
"...to make sure that your plugin doesn't collide with other libraries that might use the dollar sign, it's a best practice to pass jQuery to a self executing function (closure) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution."
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
Here is what you should do in the CSS style, on the main div
display: block;
overflow: auto;
And do not touch height
I too had a similar problem. And I've got a solution .. Download the matching chromedriver, and place the chromedriver under the /usr/local/bin path. It works.
This sometimes happens when a string is converted from Windows-1252 to UTF-8 twice.
We had this in a Zend/PHP/MySQL application where characters like that were appearing in the database, probably due to the MySQL connection not specifying the correct character set. We had to:
Ensure Zend and PHP were communicating with the database in UTF-8 (was not by default)
Repair the broken characters with several SQL queries like this...
UPDATE MyTable SET
MyField1 = CONVERT(CAST(CONVERT(MyField1 USING latin1) AS BINARY) USING utf8),
MyField2 = CONVERT(CAST(CONVERT(MyField2 USING latin1) AS BINARY) USING utf8);
Do this for as many tables/columns as necessary.
You can also fix some of these strings in PHP if necessary. Note that because characters have been encoded twice, we actually need to do a reverse conversion from UTF-8 back to Windows-1252, which confused me at first.
mb_convert_encoding('’', 'Windows-1252', 'UTF-8'); // returns ’
td.setAttribute('rowspan',x);
I had successfully used the following on Arch Linux (where the -a
flag is used for attachments) for several years:
mailx -s "The Subject $( echo -e "\nContent-Type: text/html" [email protected] < email.html
This appended the Content-Type header to the subject header, which worked great until a recent update. Now the new line is filtered out of the -s
subject. Presumably, this was done to improve security.
Instead of relying on hacking the subject line, I now use a bash subshell:
(
echo -e "Content-Type: text/html\n"
cat mail.html
) | mail -s "The Subject" -t [email protected]
And since we are really only using mailx
's subject flag, it seems there is no reason not to switch to sendmail
as suggested by @dogbane:
(
echo "To: [email protected]"
echo "Subject: The Subject"
echo "Content-Type: text/html"
echo
cat mail.html
) | sendmail -t
The use of bash subshells avoids having to create a temporary file.
Gutch's code is close, but it'll only work right if:
The Approved Method is to do it the other way around. Open the existing document with a PdfStamper, and use the returned PdfContentByte from getOverContent() to write text (and whatever else you might need) directly to the page. No second document needed.
And you can use a ColumnText to handle layout and such for you... no need to get down and dirty with beginText(),setFontAndSize(),drawText(),drawText()...,endText().
Other than ERRORLEVEL, batch files have no error handling. You'd want to look at a more powerful scripting language. I've been moving code to PowerShell.
The ability to easily use .Net assemblies and methods was one of the major reasons I started with PowerShell. The improved error handling was another. The fact that Microsoft is now requiring all of its server programs (Exchange, SQL Server etc) to be PowerShell drivable was pure icing on the cake.
Right now, it looks like any time invested in learning and using PowerShell will be time well spent.
Search
> File Search
Check the Regular expression
box.
Use this expression:
\n[\s]*
Select whatever file types (*.java
, *.xml
, etc..) and working sets are appropriate for you.
You should be able to use the Clear()
method.
do this in two steps:
and use preg_replace
:
$stringWithoutNonLetterCharacters = preg_replace("/[\/\&%#\$]/", "_", $yourString);
$stringWithQuotesReplacedWithSpaces = preg_replace("/[\"\']/", " ", $stringWithoutNonLetterCharacters);
var datos = $("#id_formulario").serialize();
$.ajax({
url: "url.php",
type: "POST",
dataType: "html",
data: datos,
success: function (prueba) {
alert("funciona!");
}//FIN SUCCES
});//FIN AJAX
This worked for me: (notice that java 8 is required)
String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);
UserJsonParse is a class that shows gson how to parse the json formant.
class is like that:
public class UserJsonParser {
private String username;
private String name;
private String lastname;
private String mail;
private String pass1;
//then put setters and getters
}
the json string that is parsed is like that:
$jsonData: { "username": "testuser", "pass1": "clave1234" }
The rest of values (mail, lastname, name) are set to null
Here I have added code, the way you want line by line.
The .=
helps you to echo multiple lines of code.
$html = '<div>';
$html .= '<h3><a href="#">First</a></h3>';
$html .= '<div>Lorem ipsum dolor sit amet.</div>';
$html .= '</div>';
$html .= '<div>';
echo $html;
The problem with all of these answers is they set the field to the default value even if you're trying to edit your record.
You need to set the default to your existing value and then only set it to the actual default if you don't have a value. Like so:
f.select :field, options_for_select(value_array, f.object.field || default_value)
For anyone not familiar with f.object.field
you always use f.object
then add your field name to the end of that.
If you still have problem then please try this.
Build Settings -> User Defined -> Provisioning profile (Remove this.)
It will solved my issue.
Thanks
Something like this would work
/^\d{2}$/
the main method should be declared in the your class like this :
public class derivativeQuiz_source{
// bunch of methods .....
public static void main(String args[])
{
// code
}
}
You just need to add in map options:
scrollwheel: false
It is mostly used for importing symbols from / exporting symbols to a shared library (DLL). Both Visual C++ and GCC compilers support __declspec(dllimport)
and __declspec(dllexport)
. Other uses (some Microsoft-only) are documented in the MSDN.
This small research proves and refines the answer by Magnus
The most platform-independent syntax is
(empty line)
[comment]: # (This actually is the most platform independent comment)
Both conditions are important:
#
(and not <>
)The strict Markdown specification CommonMark only works as intended with this syntax (and not with <>
and/or an empty line)
To prove this we shall use the Babelmark2, written by John MacFarlane. This tool checks the rendering of particular source code in 28 Markdown implementations.
(+
— passed the test, -
— didn't pass, ?
— leaves some garbage which is not shown in rendered HTML).
<>
13+, 15-<>
20+, 8-<>
20+, 8-#
13+ 1? 14-#
23+ 1? 4-#
23+ 1? 4-This proves the statements above.
These implementations fail all 7 tests. There's no chance to use excluded-on-render comments with them.
Select Product
from formula bar in your answer cell.
Select cells you want to multiply.
The Official Documentation is clear about Path
.
Linux Syntax: /home/joe/foo
Windows Syntax: C:\home\joe\foo
Note: joe
is your username for these examples.
Adding this for completeness. If you (like me) use a script in your package.json
file, just add the --timeout
option to mocha:
"scripts": {
"test": "mocha 'test/**/*.js' --timeout 10000",
"test-debug": "mocha --debug 'test/**/*.js' --timeout 10000"
},
Then you can run npm run test
to run your test suite with the timeout set to 10,000 milliseconds.
You can drop the database
and then recreate it with the below:-
mysql> drop database [database name];
mysql> create database [database name];
It sounds as you really just want to track the changes made to the model, not to actually keep an untracked model in memory. May I suggest an alternative approach wich will remove the problem entirely?
EF will automticallly track changes for you. How about making use of that built in logic?
Ovverride SaveChanges()
in your DbContext
.
public override int SaveChanges()
{
foreach (var entry in ChangeTracker.Entries<Client>())
{
if (entry.State == EntityState.Modified)
{
// Get the changed values.
var modifiedProps = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).GetModifiedProperties();
var currentValues = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).CurrentValues;
foreach (var propName in modifiedProps)
{
var newValue = currentValues[propName];
//log changes
}
}
}
return base.SaveChanges();
}
Good examples can be found here:
Entity Framework 6: audit/track changes
Implementing Audit Log / Change History with MVC & Entity Framework
EDIT:
Client
can easily be changed to an interface. Let's say ITrackableEntity
. This way you can centralize the logic and automatically log all changes to all entities that implement a specific interface. The interface itself doesn't have any specific properties.
public override int SaveChanges()
{
foreach (var entry in ChangeTracker.Entries<ITrackableClient>())
{
if (entry.State == EntityState.Modified)
{
// Same code as example above.
}
}
return base.SaveChanges();
}
Also, take a look at eranga's great suggestion to subscribe instead of actually overriding SaveChanges().
For me this was simply calling route()
on a named route that I had not created/created incorrectly. This caused the Forbidden error page.
Restarting the web server allowed proper Whoops! error to display:
Route [my-route-name] not defined.
Fixing the route name ->name('my-route-name')
fixed the error.
This is on Laravel 5.5 & using wampserver.
untested:
using System;
using System.Management;
ManagementObject disk = new
ManagementObject("win32_logicaldisk.deviceid="c:"");
disk.Get();
Console.WriteLine("Logical Disk Size = " + disk["Size"] + " bytes");
Console.WriteLine("Logical Disk FreeSpace = " + disk["FreeSpace"] + "
bytes");
Btw what is the outcome of free diskspace on c:\temp ? you will get the space free of c:\
Now that we have LINQ, you can create an array with your two values (DateTimes, TimeSpans, whatever) and then use the .Max() extension method.
var values = new[] { Date1, Date2 };
var max = values.Max();
It reads nice, it's as efficient as Max can be, and it's reusable for more than 2 values of comparison.
The whole problem below worrying about .Kind is a big deal... but I avoid that by never working in local times, ever. If I have something important regarding times, I always work in UTC, even if it means more work to get there.
In .NET 5 / C# 8:
You can write the code marked as the answer as:
public static class StringExtensions
{
public static string TrimLastCharacters(this string str) => string.IsNullOrEmpty(str) ? str : str.TrimEnd(str[^1]);
}
However, as mentioned in the answer, this removes all occurrences of that last character. If you only want to remove the last character you should instead do:
public static string RemoveLastCharacter(this string str) => string.IsNullOrEmpty(str) ? str : str[..^1];
A quick explanation for the new stuff in C# 8:
The ^
is called the "index from end operator". The ..
is called the "range operator". ^1
is a shortcut for arr.length - 1
. You can get all items after the first character of an array with arr[1..]
or all items before the last with arr[..^1]
. These are just a few quick examples. For more information, see https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8, "Indices and ranges" section.
I had the same problem even when I created a fresh project.
I was creating the Java project within Eclipse, then mavenize it, then going into java build path properties removing src/
and adding src/main/java
and src/test/java
. When I run Maven update it used to give nested path error.
Then I finally realized -because I had not seen that entry before- there is a <sourceDirectory>src</sourceDirectory>
line in pom file written when I mavenize it. It was resolved after removing it.
As @Musa comments it, it seems that the reason is that:
Postman doesn't care about SOP, it's a dev tool not a browser
By the way here's a chrome extension in order to make it work on your browser (this one is for chrome, but you can find either for FF or Safari).
Check here if you want to learn more about Cross-Origin and why it's working for extensions.
You should NOT use ::ng-deep
, it is deprecated. In Angular, the proper way to change the style of children's component from the parent is to use encapsulation
(read the warning below to understand the implications):
import { ViewEncapsulation } from '@angular/core';
@Component({
....
encapsulation: ViewEncapsulation.None
})
And then, you will be able to modify the css form your component without a need from ::ng-deep
.mat-sort-header-container {
display: flex;
justify-content: center;
}
WARNING: Doing this will make all css rules you write for this component to be global.
In order to limit the scope of your css to this component and his child only, add a css class to the top tag of your component and put your css "inside" this tag:
template:
<div class='my-component'>
<child-component class="first">First</child>
</div>,
Scss file:
.my-component {
// All your css goes in there in order not to be global
}
You can create your own extension method to do this:
public static bool Contains(this string source, string toCheck, StringComparison comp)
{
return source != null && toCheck != null && source.IndexOf(toCheck, comp) >= 0;
}
And then call:
mystring.Contains(myStringToCheck, StringComparison.OrdinalIgnoreCase);
You need Pexpect to get the best of both worlds (expect and ssh wrappers).
Python 3:
pip3 install -r requirements.txt
Python 2:
pip install -r requirements.txt
To get all the dependencies for the virtual environment or for the whole system:
pip freeze
To push all the dependencies to the requirements.txt (Linux):
pip freeze > requirements.txt
Here is simpliest way to clear items from this list.
there we go.
In most cases, when you find yourself using forEach
on a Stream, you should rethink whether you are using the right tool for your job or whether you are using it the right way.
Generally, you should look for an appropriate terminal operation doing what you want to achieve or for an appropriate Collector. Now, there are Collectors for producing Map
s and List
s, but no out of-the-box collector for combining two different collectors, based on a predicate.
Now, this answer contains a collector for combining two collectors. Using this collector, you can achieve the task as
Pair<Map<KeyType, Animal>, List<KeyType>> pair = animalMap.entrySet().stream()
.collect(conditional(entry -> entry.getValue() != null,
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
Collectors.mapping(Map.Entry::getKey, Collectors.toList()) ));
Map<KeyType,Animal> myMap = pair.a;
List<KeyType> myList = pair.b;
But maybe, you can solve this specific task in a simpler way. One of you results matches the input type; it’s the same map just stripped off the entries which map to null
. If your original map is mutable and you don’t need it afterwards, you can just collect the list and remove these keys from the original map as they are mutually exclusive:
List<KeyType> myList=animalMap.entrySet().stream()
.filter(pair -> pair.getValue() == null)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
animalMap.keySet().removeAll(myList);
Note that you can remove mappings to null
even without having the list of the other keys:
animalMap.values().removeIf(Objects::isNull);
or
animalMap.values().removeAll(Collections.singleton(null));
If you can’t (or don’t want to) modify the original map, there is still a solution without a custom collector. As hinted in Alexis C.’s answer, partitioningBy
is going into the right direction, but you may simplify it:
Map<Boolean,Map<KeyType,Animal>> tmp = animalMap.entrySet().stream()
.collect(Collectors.partitioningBy(pair -> pair.getValue() != null,
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
Map<KeyType,Animal> myMap = tmp.get(true);
List<KeyType> myList = new ArrayList<>(tmp.get(false).keySet());
The bottom line is, don’t forget about ordinary Collection operations, you don’t have to do everything with the new Stream API.
I found a plugin that helped me do this within seconds without editing code:
https://wordpress.org/plugins/quick-pagepost-redirect-plugin/
I found it here: http://premium.wpmudev.org/blog/wordpress-link-title-external-url/
You can use the following command:
zip -r nameoffile.zip directory
Hope this helps.
If you want to force the issue, you can do:
git reset --hard c14809fafb08b9e96ff2879999ba8c807d10fb07
send you back to how your git clone looked like at the time of the checkin
In your code you are assigning a native method to a property of custom object.
When you call support.animationFrame(function () {})
, it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window
.
So the correct usage here is support.animationFrame.call(window, function() {});
.
The same happens with alert too:
var myObj = {
myAlert : alert //copying native alert to an object
};
myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window
Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.
var _raf = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var support = {
animationFrame: _raf ? _raf.bind(window) : null
};
\usepackage{array}
in the preamble
then this:
\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}
note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"
Unless you really want to keep the dictionary, I think the best solution is to use the csv
Python module to read the file.
Then, you get rows of data and you can change member_phone
or whatever you want ;
finally, you can use the csv
module again to save the file in the same format
as you opened it.
Code for reading:
import csv
with open("my_input_file.txt", "r") as f:
reader = csv.reader(f, delimiter=":")
lines = list(reader)
Code for writing:
with open("my_output_file.txt", "w") as f:
writer = csv.writer(f, delimiter=":")
writer.writerows(lines)
Of course, you need to adapt your change()
function:
def change(lines):
a = input('ID')
for line in lines:
if line[0] == a:
d=str(input("phone"))
line[3]=d
break
else:
print "not"
Using Sourcetree | The easiest way.
With so many solutions proposed, I'm amazed nobody's proposed what I'd consider an obvious one (for non-hashable but comparable elements) -- [itertools.groupby
][1]. itertools
offers fast, reusable functionality, and lets you delegate some tricky logic to well-tested standard library components. Consider for example:
import itertools
import operator
def most_common(L):
# get an iterable of (item, iterable) pairs
SL = sorted((x, i) for i, x in enumerate(L))
# print 'SL:', SL
groups = itertools.groupby(SL, key=operator.itemgetter(0))
# auxiliary function to get "quality" for an item
def _auxfun(g):
item, iterable = g
count = 0
min_index = len(L)
for _, where in iterable:
count += 1
min_index = min(min_index, where)
# print 'item %r, count %r, minind %r' % (item, count, min_index)
return count, -min_index
# pick the highest-count/earliest item
return max(groups, key=_auxfun)[0]
This could be written more concisely, of course, but I'm aiming for maximal clarity. The two print
statements can be uncommented to better see the machinery in action; for example, with prints uncommented:
print most_common(['goose', 'duck', 'duck', 'goose'])
emits:
SL: [('duck', 1), ('duck', 2), ('goose', 0), ('goose', 3)]
item 'duck', count 2, minind 1
item 'goose', count 2, minind 0
goose
As you see, SL
is a list of pairs, each pair an item followed by the item's index in the original list (to implement the key condition that, if the "most common" items with the same highest count are > 1, the result must be the earliest-occurring one).
groupby
groups by the item only (via operator.itemgetter
). The auxiliary function, called once per grouping during the max
computation, receives and internally unpacks a group - a tuple with two items (item, iterable)
where the iterable's items are also two-item tuples, (item, original index)
[[the items of SL
]].
Then the auxiliary function uses a loop to determine both the count of entries in the group's iterable, and the minimum original index; it returns those as combined "quality key", with the min index sign-changed so the max
operation will consider "better" those items that occurred earlier in the original list.
This code could be much simpler if it worried a little less about big-O issues in time and space, e.g....:
def most_common(L):
groups = itertools.groupby(sorted(L))
def _auxfun((item, iterable)):
return len(list(iterable)), -L.index(item)
return max(groups, key=_auxfun)[0]
same basic idea, just expressed more simply and compactly... but, alas, an extra O(N) auxiliary space (to embody the groups' iterables to lists) and O(N squared) time (to get the L.index
of every item). While premature optimization is the root of all evil in programming, deliberately picking an O(N squared) approach when an O(N log N) one is available just goes too much against the grain of scalability!-)
Finally, for those who prefer "oneliners" to clarity and performance, a bonus 1-liner version with suitably mangled names:-).
from itertools import groupby as g
def most_common_oneliner(L):
return max(g(sorted(L)), key=lambda(x, v):(len(list(v)),-L.index(x)))[0]
The way I usually do that is by creating a regular list, then append my stuff into it, and finally transform the list to a numpy array as follows :
import numpy as np
big_array = [] # empty regular list
for i in range(5):
arr = i*np.ones((2,4)) # for instance
big_array.append(arr)
big_np_array = np.array(big_array) # transformed to a numpy array
of course your final object takes twice the space in the memory at the creation step, but appending on python list is very fast, and creation using np.array() also.
There are 8 bits in a byte (normally speaking in Windows).
However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.
In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.
EDITED
Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.
If you're getting this, you may have forgotten to put #include <thread>
at the beginning of your file. OP's signature seems like it should work.
If you have plugin for Maven in Eclipse, you can do following:
right click on your project -> Maven -> Enable Dependency Management
This will convert your project to Maven and creates a pom.xml
. Fast and simple...
I was facing this error while I deployed my Web API project locally and I was calling API project only with this URL given below:
localhost//myAPIProject
Since the error message says it is not http:// then I changed the URL and put a prefix http as given below and the error was gone.
If you want to accomplish the same in Gecko (NS6+, Mozilla, etc) and IE4+ simultaneously, I believe this should do the trick:V
body {
overflow: -moz-scrollbars-vertical;
overflow-x: hidden;
overflow-y: auto;
}
This will be applied to entire body tag, please update it to your relevant css and apply this properties.
The extension method IsNot<T>
is a nice way to extend the syntax. Keep in mind
var container = child as IContainer;
if(container != null)
{
// do something w/ contianer
}
performs better than doing something like
if(child is IContainer)
{
var container = child as IContainer;
// do something w/ container
}
In your case, it doesn't matter as you are returning from the method. In other words, be careful to not do both the check for type and then the type conversion immediately after.
You need to use Concat operation