It doesn't - the C# compiler does :)
So this code:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
actually gets compiled as:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
(Gah - intervening edit removed other bits accidentally.)
The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y
which then needs to be copied again as part of the concatenation of (x + y)
and z
. Instead, we get it all done in one go.
EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:
string x = "";
foreach (string y in strings)
{
x += y;
}
just ends up as equivalent to:
string x = "";
foreach (string y in strings)
{
x = string.Concat(x, y);
}
... so this does generate a lot of garbage, and it's why you should use a StringBuilder
for such cases. I have an article going into more details about the two which will hopefully answer further questions.
For memory usage, the following will work,
long total = Runtime.getRuntime().totalMemory();
long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
For CPU usage, you'll need to use an external application to measure it.
If you are using Sql Server Management Studio, you can obtain a list of all schemas, create your own schema or remove an existing one by browsing to:
Databases - [Your Database] - Security - Schemas
[
The code is okay but you are in the wrong directory. You must run these commands inside your rails project-directory.
The normal way to get there from scratch is:
$ rails new PROJECT_NAME
$ cd PROJECT_NAME
$ rails generate model ad \
name:string \
description:text \
price:decimal \
seller_id:integer \
email:string img_url:string
You can use [FromQuery]
to bind a particular model to the querystring:
https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding
e.g.
[HttpGet()]
public IActionResult Get([FromQuery(Name = "page")] string page)
{...}
As of January 2018 the url is https://www.twitch.tv/username/dashboard/settings/streamkey
Two UDF to deal with UTF-8 in T-SQL:
CREATE Function UcsToUtf8(@src nvarchar(MAX)) returns varchar(MAX) as
begin
declare @res varchar(MAX)='', @pi char(8)='%[^'+char(0)+'-'+char(127)+']%', @i int, @j int
select @i=patindex(@pi,@src collate Latin1_General_BIN)
while @i>0
begin
select @j=unicode(substring(@src,@i,1))
if @j<0x800 select @res=@res+left(@src,@i-1)+char((@j&1984)/64+192)+char((@j&63)+128)
else select @res=@res+left(@src,@i-1)+char((@j&61440)/4096+224)+char((@j&4032)/64+128)+char((@j&63)+128)
select @src=substring(@src,@i+1,datalength(@src)-1), @i=patindex(@pi,@src collate Latin1_General_BIN)
end
select @res=@res+@src
return @res
end
CREATE Function Utf8ToUcs(@src varchar(MAX)) returns nvarchar(MAX) as
begin
declare @i int, @res nvarchar(MAX)=@src, @pi varchar(18)
select @pi='%[à-ï][€-¿][€-¿]%',@i=patindex(@pi,@src collate Latin1_General_BIN)
while @i>0 select @res=stuff(@res,@i,3,nchar(((ascii(substring(@src,@i,1))&31)*4096)+((ascii(substring(@src,@i+1,1))&63)*64)+(ascii(substring(@src,@i+2,1))&63))), @src=stuff(@src,@i,3,'.'), @i=patindex(@pi,@src collate Latin1_General_BIN)
select @pi='%[Â-ß][€-¿]%',@i=patindex(@pi,@src collate Latin1_General_BIN)
while @i>0 select @res=stuff(@res,@i,2,nchar(((ascii(substring(@src,@i,1))&31)*64)+(ascii(substring(@src,@i+1,1))&63))), @src=stuff(@src,@i,2,'.'),@i=patindex(@pi,@src collate Latin1_General_BIN)
return @res
end
From the documentation:
get cookie from response
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies
{'example_cookie_name': 'example_cookie_value'}
give cookie back to server on subsequent request
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)`
Linux
conda env export --no-builds | grep -v "prefix" > environment.yml
Windows
conda env export --no-builds | findstr -v "prefix" > environment.yml
Rationale: By default, conda env export
includes the build information:
$ conda env export
...
dependencies:
- backcall=0.1.0=py37_0
- blas=1.0=mkl
- boto=2.49.0=py_0
...
You can instead export your environment without build info:
$ conda env export --no-builds
...
dependencies:
- backcall=0.1.0
- blas=1.0
- boto=2.49.0
...
Which unties the environment from the Python version and OS.
URLs use forward slashes (/), not backward ones (as windows). Try:
serverURLS = "https://abc.my.domain.com:55555/update";
The reason why you get the error is that the URL class can't parse the host part of the string and therefore, host
is null
.
Or you can try to add in local name resolution (hosts
file found in the directory etc
in most operating systems, details differ) something like this:
192.168.1.1 Linksys
and next
var req = https.request({
host: 'Linksys',
port: 443,
path: '/',
method: 'GET'
...
will work.
You could do:
sub("*\\.[0-9]", "", a)
or
library(stringr)
str_sub(a, start=1, end=-3)
A solution that correctly handles all file names (including newlines) and extracts into a directory that is at the same location as the file, just with the extension removed:
find . -iname '*.zip' -exec sh -c 'unzip -o -d "${0%.*}" "$0"' '{}' ';'
Note that you can easily make it handle more file types (such as .jar
) by adding them using -o
, e.g.:
find . '(' -iname '*.zip' -o -iname '*.jar' ')' -exec ...
Half a second is 500,000,000 nanoseconds, so your code should read:
tim.tv_sec = 0;
tim.tv_nsec = 500000000L;
As things stand, you code is sleeping for 1.0000005s (1s + 500ns).
Several things here.
First off, you're defining your CSS in 3 places!
In line, in the head and externally. I suggest you only choose one. I'm going to suggest externally.
I suggest you update your code in your ASP form from
<td style="background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;"
class="style6">
to this:
<td class="style6">
And then update your css too
.style6
{
height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
}
This removes the inline.
Now, to move it from the head of the webForm.
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AR Toolbox</title>
<link rel="Stylesheet" href="css/master.css" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<table class="style1">
<tr>
<td class="style6">
<asp:Menu ID="Menu1" runat="server">
<Items>
<asp:MenuItem Text="Home" Value="Home"></asp:MenuItem>
<asp:MenuItem Text="About" Value="About"></asp:MenuItem>
<asp:MenuItem Text="Compliance" Value="Compliance">
<asp:MenuItem Text="Item 1" Value="Item 1"></asp:MenuItem>
<asp:MenuItem Text="Item 2" Value="Item 2"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Tools" Value="Tools"></asp:MenuItem>
<asp:MenuItem Text="Contact" Value="Contact"></asp:MenuItem>
</Items>
</asp:Menu>
</td>
</tr>
<tr>
<td class="style6">
<img alt="South University'" class="style7"
src="file:///C:/Users/jnewnam/Documents/Visual%20Studio%202010/WebSites/WebSite1/img/suo_n_seal_hor_pantone.png" /></td>
</tr>
<tr>
<td class="style2">
<table class="style3">
<tr>
<td>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="color: #FFFFFF; background-color: #A3A3A3">
This is the footer.</td>
</tr>
</table>
</form>
</body>
</html>
Now, in a new file called master.css (in your css folder) add
ul {
list-style-type:none;
margin:0;
padding:0;
}
li {
display:inline;
padding:20px;
}
.style1
{
width: 100%;
}
.style2
{
height: 459px;
}
.style3
{
width: 100%;
height: 100%;
}
.style6
{
height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
}
.style7
{
width: 345px;
height: 73px;
}
You can now make use of ES6 template literals.
const numbersAsString = `${5}${6}`;
console.log(numbersAsString); // Outputs 56
Or, if you have variables:
const someNumber = 5;
const someOtherNumber = 6;
const numbersAsString = `${someNumber}${someOtherNumber}`;
console.log(numbersAsString); // Outputs 56
Personally I find the new syntax much clearer, albeit slightly more verbose.
use array_rand()
see php manual -> http://php.net/manual/en/function.array-rand.php
Never mind, figured it out:
set wrap off
set linesize 3000 -- (or to a sufficiently large value to hold your results page)
Which I found by:
show all
And looking for some option that seemed relevant.
How about onblur event :
<input type="text" name="name" value="value" onblur="alert(1);"/>
use Handler
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// Code here will run in UI thread
}
});
WHERE `column` LIKE '%$needle%'
There are two issues here.
Firstly, you can't use the []
syntax like you may be able to in other languages. Square brackets only apply to arrays in Java, and so can only be used with integer indexes.
data.put
is correct but that is a statement and so must exist in a method block. Only field declarations can exist at the class level. Here is an example where everything is within the local scope of a method:
public class Data {
public static void main(String[] args) {
Map<String, String> data = new HashMap<String, String>();
data.put("John", "Taxi Driver");
data.put("Mark", "Professional Killer");
}
}
If you want to initialize a map as a static field of a class then you can use Map.of
, since Java 9:
public class Data {
private static final Map<String, String> DATA = Map.of("John", "Taxi Driver");
}
Before Java 9, you can use a static initializer block to accomplish the same thing:
public class Data {
private static final Map<String, String> DATA = new HashMap<>();
static {
DATA.put("John", "Taxi Driver");
}
}
if ($("#btn").data('events') != undefined && $("#btn").data('events').click != undefined) {
//do nothing as the click event is already there
} else {
$("#btn").click(function (e) {
alert('test');
});
}
You cannot directly copy a table into a destination server database from a different database if source db is not in your linked servers. But one way is possible that, generate scripts (schema with data) of the desired table into one table temporarily in the source server DB, then execute the script in the destination server DB to create a table with your data. Finally use INSERT INTO [DESTINATION_TABLE] select * from [TEMPORARY_SOURCE_TABLE]. After getting the data into your destination table drop the temporary one.
I found this solution when I faced the same situation. Hope this helps you too.
This works for me
msg.BodyFormat = MailFormat.Html;
and then you can use html in your body
msg.Body = "<em>It's great to use HTML in mail!!</em>"
It is also possible to load scripts and links into the header. I'll be adding it one of the examples above...
<!--load_essentials.js-->
document.write('<link rel="stylesheet" type="text/css" href="css/style.css" />');
document.write('<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />');
document.write('<script src="js/jquery.js" type="text/javascript"></script>');
document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright © " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:[email protected]'>Contact Us</a> / "
+ "<a href='mailto:[email protected]'>Report a problem.</a></p>";
<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>
<script src="load_essentials.js"></script>
I have a way to do it very simply, and I'd like to share it.
When I want to square mi TextViews, I just put them in a LinearLayout. I set the background color of my LinearLayout, and I add a margin to my TextView. The result is exactly as if you square the TextView.
As said before modulo isn't sufficient because it skews the distribution. Heres my code which masks off bits and uses them to ensure the distribution isn't skewed.
static uint32_t randomInRange(uint32_t a,uint32_t b) {
uint32_t v;
uint32_t range;
uint32_t upper;
uint32_t lower;
uint32_t mask;
if(a == b) {
return a;
}
if(a > b) {
upper = a;
lower = b;
} else {
upper = b;
lower = a;
}
range = upper - lower;
mask = 0;
//XXX calculate range with log and mask? nah, too lazy :).
while(1) {
if(mask >= range) {
break;
}
mask = (mask << 1) | 1;
}
while(1) {
v = rand() & mask;
if(v <= range) {
return lower + v;
}
}
}
The following simple code lets you look at the distribution:
int main() {
unsigned long long int i;
unsigned int n = 10;
unsigned int numbers[n];
for (i = 0; i < n; i++) {
numbers[i] = 0;
}
for (i = 0 ; i < 10000000 ; i++){
uint32_t rand = random_in_range(0,n - 1);
if(rand >= n){
printf("bug: rand out of range %u\n",(unsigned int)rand);
return 1;
}
numbers[rand] += 1;
}
for(i = 0; i < n; i++) {
printf("%u: %u\n",i,numbers[i]);
}
}
I have seen all answers. I want tell most robust way now a day. That will make you communicate between Activity - Service - Dialog - Fragments
(Everything).
This lib which i am using in my projects has great features related to messaging.
EventBus in 3 steps
Define events:
public static class MessageEvent { /* Additional fields if needed */ }
Prepare subscribers:
Declare and annotate your subscribing method, optionally specify a thread mode:
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
Post events:
EventBus.getDefault().post(new MessageEvent());
Just add this dependency in your app level gradle
compile 'org.greenrobot:eventbus:3.1.1'
keytool -exportcert -alias androiddebugkey -keystore "C:\Users**Deepak**.android\debug.keystore" | "C:\Users\Deepak\ssl\bin\openssl" sha1 -binary | "C:\Users\Deepak\ssl\bin\openssl" base64
2 Changes in this above command 1.Deepak===Replace by your System USERNAME 2.C:\Users\Deepak\ssl=== replce your Open SSL path
run this command and get output like this
C:\Users\Deepak>keytool -exportcert -alias androiddebugkey -keystore "C:\Users\D eepak.android\debug.keystore" | "C:\Users\Deepak\ssl\bin\openssl" sha1 -binary | "C:\Users\Deepak\ssl\bin\openssl" base64 Enter keystore password: ****** ga0RGNY******************=
Dumb mistake from my part, didn't archive the app after removing alpha. Just kept submitting my old archived app and finding same alpha/transparency error. Hope it helps someone.
The error suggests that the application you are trying to run cannot instantiate an instance of apache tomcat. Make sure you are running the application with tomcat.
if after checking all your dependencies you experience the same problem, try to add the following in your configuration class
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory factory =
new TomcatEmbeddedServletContainerFactory();
return factory;
}
If you are using an external instance of tomcat (especially for intellij), the problem could be that the IDE is trying to start the embedded tomcat. In this case, remove the following from your pom.xml then configure the external tomcat using the 'Edit Configurations' wizard.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
The Request Payload - or to be more precise: payload body of a HTTP Request
- is the data normally send by a POST or PUT Request.
It's the part after the headers and the CRLF
of a HTTP Request.
A request with Content-Type: application/json
may look like this:
POST /some-path HTTP/1.1
Content-Type: application/json
{ "foo" : "bar", "name" : "John" }
If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from.
If you submit a HTML-Form with method="POST"
and Content-Type: application/x-www-form-urlencoded
or Content-Type: multipart/form-data
your request may look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded
foo=bar&name=John
In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you.
So, they differ in the Content-Type
but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools.
A really good way to make a tooltip is described here: Simple D3 tooltip example
You have to append a div
var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("a simple tooltip");
Then you can just toggle it using
.on("mouseover", function(){return tooltip.style("visibility", "visible");})
.on("mousemove", function(){return tooltip.style("top",
(d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");});
d3.event.pageX
/ d3.event.pageY
is the current mouse coordinate.
If you want to change the text you can use tooltip.text("my tooltip text");
For those working with ant
, I use this to indicate a pause of 5 seconds:
<tr>
<td>pause</td>
<td>5000</td>
<td></td>
</tr>
That is, target: 5000
and value
empty. As the reference indicates:
pause(waitTime)
Arguments:
- waitTime - the amount of time to sleep (in milliseconds)
Wait for the specified amount of time (in milliseconds)
File/Settings/Inpsections/Imports
and change "Unused import" to Error. This marks them more clearly in the Inspections gutter and the Inspection Results panel.
I ran into this and realized I didn't fetch the upstream before trying to rebase. All I needed was to git fetch upstream
No ... on all Windows platforms DWORD is 32 bits. LONGLONG or LONG64 is used for 64 bit types.
I don't have a mysql database to test on at the moment, but have you tried specifying what to delete prior to the from clause? For example:
DELETE p, pa FROM `pets` p,
`pets_activities` pa
WHERE p.`order` > :order
AND p.`pet_id` = :pet_id
AND pa.`id` = p.`pet_id`
I think the syntax you used is limited to newer versions of mysql.
As Hunter McMillen mentioned, tuples are immutable, you need to create a new tuple in order to achieve this. For instance:
>>> tpl = ('275', '54000', '0.0', '5000.0', '0.0')
>>> change_value = 200
>>> tpl = (change_value,) + tpl[1:]
>>> tpl
(200, '54000', '0.0', '5000.0', '0.0')
The script below lists all the default constraints and the default values for the user tables in the database in which it is being run:
SELECT
b.name AS TABLE_NAME,
d.name AS COLUMN_NAME,
a.name AS CONSTRAINT_NAME,
c.text AS DEFAULT_VALUE
FROM sys.sysobjects a INNER JOIN
(SELECT name, id
FROM sys.sysobjects
WHERE xtype = 'U') b on (a.parent_obj = b.id)
INNER JOIN sys.syscomments c ON (a.id = c.id)
INNER JOIN sys.syscolumns d ON (d.cdefault = a.id)
WHERE a.xtype = 'D'
ORDER BY b.name, a.name
I had the same problem, but while using a library project. The issue has been solved in r17: Instead of using the package's namespace:
xmlns:app="http://schemas.android.com/apk/res/hu.droidium.exercises"
One has to use a dummy namespace:
xmlns:app="http://schemas.android.com/apk/res-auto"
This will fix the problem of the attributes not being accessible from the referencing project.
Since you have asked it in javascript so you can have something like this
function contains(selector, text) {
var elements = document.querySelectorAll(selector);
return Array.prototype.filter.call(elements, function(element){
return RegExp(text).test(element.textContent);
});
}
And then call it like this
contains('div', 'sometext'); // find "div" that contain "sometext"
contains('div', /^sometext/); // find "div" that start with "sometext"
contains('div', /sometext$/i); // find "div" that end with "sometext", case-insensitive
(Updated - Thanks to the people who commented)
Suppose you have a table named test1
, to which you want to add an auto-incrementing, primary-key id
(surrogate) column. The following command should be sufficient in recent versions of PostgreSQL:
ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;
In old versions of PostgreSQL (prior to 8.x?) you had to do all the dirty work. The following sequence of commands should do the trick:
ALTER TABLE test1 ADD COLUMN id INTEGER;
CREATE SEQUENCE test_id_seq OWNED BY test1.id;
ALTER TABLE test ALTER COLUMN id SET DEFAULT nextval('test_id_seq');
UPDATE test1 SET id = nextval('test_id_seq');
Again, in recent versions of Postgres this is roughly equivalent to the single command above.
i'm also facing that problem now solved.Give the onChange to the searchTool. then that problem will solve for you.
I agree with @MihaiIorga in the comments – use the PHPMailer script. You sound like you're rejecting it because you want the easier option. Trust me, PHPMailer is the easier option by a very large margin compared to trying to do it yourself with PHP's built-in mail()
function. PHP's mail()
function really isn't very good.
To use PHPMailer:
require_once('path/to/file/class.phpmailer.php');
Now, sending emails with attachments goes from being insanely difficult to incredibly easy:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$email = new PHPMailer();
$email->SetFrom('[email protected]', 'Your Name'); //Name is optional
$email->Subject = 'Message Subject';
$email->Body = $bodytext;
$email->AddAddress( '[email protected]' );
$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';
$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );
return $email->Send();
It's just that one line $email->AddAttachment();
-- you couldn't ask for any easier.
If you do it with PHP's mail()
function, you'll be writing stacks of code, and you'll probably have lots of really difficult to find bugs.
In case anyone would like to see this broken out into a very robust function
function getBaseURL() {
var loc = window.location;
var baseURL = loc.protocol + "//" + loc.hostname;
if (typeof loc.port !== "undefined" && loc.port !== "") baseURL += ":" + loc.port;
// strip leading /
var pathname = loc.pathname;
if (pathname.length > 0 && pathname.substr(0,1) === "/") pathname = pathname.substr(1, pathname.length - 1);
var pathParts = pathname.split("/");
if (pathParts.length > 0) {
for (var i = 0; i < pathParts.length; i++) {
if (pathParts[i] !== "") baseURL += "/" + pathParts[i];
}
}
return baseURL;
}
I created a script to ignore differences in line endings:
It will display the files which are not added to the commit list and were modified (after ignoring differences in line endings). You can add the argument "add" to add those files to your commit.
#!/usr/bin/perl
# Usage: ./gitdiff.pl [add]
# add : add modified files to git
use warnings;
use strict;
my ($auto_add) = @ARGV;
if(!defined $auto_add) {
$auto_add = "";
}
my @mods = `git status --porcelain 2>/dev/null | grep '^ M ' | cut -c4-`;
chomp(@mods);
for my $mod (@mods) {
my $diff = `git diff -b $mod 2>/dev/null`;
if($diff) {
print $mod."\n";
if($auto_add eq "add") {
`git add $mod 2>/dev/null`;
}
}
}
Source code: https://github.com/lepe/scripts/blob/master/gitdiff.pl
Updates:
I got stuck with this problem and found that it was the order of the call to
request.setCharacterEncoding("UTF-8");
that was causing the problem. It has to be called before any all call to request.getParameter(), so I made a special filter to use at the top of my filter chain.
https://rogerkeays.com/servletrequest-setcharactercoding-ignored
Assume you stored that dictionary in a variable called values. To get id
in to a variable, do:
idValue = values['criteria'][0]['id']
If that json is in a file, do the following to load it:
import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()
If that json is from a URL, do the following to load it:
import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()
To print ALL of the criteria, you could:
for criteria in values['criteria']:
for key, value in criteria.iteritems():
print key, 'is:', value
print ''
One liner, but be careful if you have a multi-user repository - this will change all commits to have the same (new) author and committer.
git filter-branch -f --env-filter "GIT_AUTHOR_NAME='Newname'; GIT_AUTHOR_EMAIL='new@email'; GIT_COMMITTER_NAME='Newname'; GIT_COMMITTER_EMAIL='new@email';" HEAD
With linebreaks in the string (which is possible in bash):
git filter-branch -f --env-filter "
GIT_AUTHOR_NAME='Newname'
GIT_AUTHOR_EMAIL='new@email'
GIT_COMMITTER_NAME='Newname'
GIT_COMMITTER_EMAIL='new@email'
" HEAD
There is a method specifically for this purpose:
data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
Reference array:
var array = [
{ ID: '100', },
{ ID: '200', },
{ ID: '300', },
{ ID: '400', },
{ ID: '500', }
];
Using filter
and indexOf
:
var in_array = array.filter(function(item) {
return item.ID == '200' // look for the item where ID is equal to value
});
var index = array.indexOf(in_array[0]);
Looping through each item in the array using indexOf
:
for (var i = 0; i < array.length; i++) {
var item= array[i];
if (item.ID == '200') {
var index = array.indexOf(item);
}
}
Also: git diff master..feature foo
Since git diff foo master:foo
doesn't work on directories for me.
write_text()
from pathlib.Path
can be used.
>>> from pathlib import Path
>>> Path('aa.txt').write_text("")
0
I created also a util/helper class (using jdk 8) which can format a string an replaces occurrences of variables.
For this purpose I used the Matchers "appendReplacement" method which does all the substitution and loops only over the affected parts of a format string.
The helper class isn't currently well javadoc documented. I will changes this in the future ;) Anyway I commented the most important lines (I hope).
public class FormatHelper {
//Prefix and suffix for the enclosing variable name in the format string.
//Replace the default values with any you need.
public static final String DEFAULT_PREFIX = "${";
public static final String DEFAULT_SUFFIX = "}";
//Define dynamic function what happens if a key is not found.
//Replace the defualt exception with any "unchecked" exception type you need or any other behavior.
public static final BiFunction<String, String, String> DEFAULT_NO_KEY_FUNCTION =
(fullMatch, variableName) -> {
throw new RuntimeException(String.format("Key: %s for variable %s not found.",
variableName,
fullMatch));
};
private final Pattern variablePattern;
private final Map<String, String> values;
private final BiFunction<String, String, String> noKeyFunction;
private final String prefix;
private final String suffix;
public FormatHelper(Map<String, String> values) {
this(DEFAULT_NO_KEY_FUNCTION, values);
}
public FormatHelper(
BiFunction<String, String, String> noKeyFunction, Map<String, String> values) {
this(DEFAULT_PREFIX, DEFAULT_SUFFIX, noKeyFunction, values);
}
public FormatHelper(String prefix, String suffix, Map<String, String> values) {
this(prefix, suffix, DEFAULT_NO_KEY_FUNCTION, values);
}
public FormatHelper(
String prefix,
String suffix,
BiFunction<String, String, String> noKeyFunction,
Map<String, String> values) {
this.prefix = prefix;
this.suffix = suffix;
this.values = values;
this.noKeyFunction = noKeyFunction;
//Create the Pattern and quote the prefix and suffix so that the regex don't interpret special chars.
//The variable name is a "\w+" in an extra capture group.
variablePattern = Pattern.compile(Pattern.quote(prefix) + "(\\w+)" + Pattern.quote(suffix));
}
public static String format(CharSequence format, Map<String, String> values) {
return new FormatHelper(values).format(format);
}
public static String format(
CharSequence format,
BiFunction<String, String, String> noKeyFunction,
Map<String, String> values) {
return new FormatHelper(noKeyFunction, values).format(format);
}
public static String format(
String prefix, String suffix, CharSequence format, Map<String, String> values) {
return new FormatHelper(prefix, suffix, values).format(format);
}
public static String format(
String prefix,
String suffix,
BiFunction<String, String, String> noKeyFunction,
CharSequence format,
Map<String, String> values) {
return new FormatHelper(prefix, suffix, noKeyFunction, values).format(format);
}
public String format(CharSequence format) {
//Create matcher based on the init pattern for variable names.
Matcher matcher = variablePattern.matcher(format);
//This buffer will hold all parts of the formatted finished string.
StringBuffer formatBuffer = new StringBuffer();
//loop while the matcher finds another variable (prefix -> name <- suffix) match
while (matcher.find()) {
//The root capture group with the full match e.g ${variableName}
String fullMatch = matcher.group();
//The capture group for the variable name resulting from "(\w+)" e.g. variableName
String variableName = matcher.group(1);
//Get the value in our Map so the Key is the used variable name in our "format" string. The associated value will replace the variable.
//If key is missing (absent) call the noKeyFunction with parameters "fullMatch" and "variableName" else return the value.
String value = values.computeIfAbsent(variableName, key -> noKeyFunction.apply(fullMatch, key));
//Escape the Map value because the "appendReplacement" method interprets the $ and \ as special chars.
String escapedValue = Matcher.quoteReplacement(value);
//The "appendReplacement" method replaces the current "full" match (e.g. ${variableName}) with the value from the "values" Map.
//The replaced part of the "format" string is appended to the StringBuffer "formatBuffer".
matcher.appendReplacement(formatBuffer, escapedValue);
}
//The "appendTail" method appends the last part of the "format" String which has no regex match.
//That means if e.g. our "format" string has no matches the whole untouched "format" string is appended to the StringBuffer "formatBuffer".
//Further more the method return the buffer.
return matcher.appendTail(formatBuffer)
.toString();
}
public String getPrefix() {
return prefix;
}
public String getSuffix() {
return suffix;
}
public Map<String, String> getValues() {
return values;
}
}
You can create a class instance for a specific Map with values (or suffix prefix or noKeyFunction) like:
Map<String, String> values = new HashMap<>();
values.put("firstName", "Peter");
values.put("lastName", "Parker");
FormatHelper formatHelper = new FormatHelper(values);
formatHelper.format("${firstName} ${lastName} is Spiderman!");
// Result: "Peter Parker is Spiderman!"
// Next format:
formatHelper.format("Does ${firstName} ${lastName} works as photographer?");
//Result: "Does Peter Parker works as photographer?"
Further more you can define what happens if a key in the values Map is missing (works in both ways e.g. wrong variable name in format string or missing key in Map). The default behavior is an thrown unchecked exception (unchecked because I use the default jdk8 Function which cant handle checked exceptions) like:
Map<String, String> map = new HashMap<>();
map.put("firstName", "Peter");
map.put("lastName", "Parker");
FormatHelper formatHelper = new FormatHelper(map);
formatHelper.format("${missingName} ${lastName} is Spiderman!");
//Result: RuntimeException: Key: missingName for variable ${missingName} not found.
You can define a custom behavior in the constructor call like:
Map<String, String> values = new HashMap<>();
values.put("firstName", "Peter");
values.put("lastName", "Parker");
FormatHelper formatHelper = new FormatHelper(fullMatch, variableName) -> variableName.equals("missingName") ? "John": "SOMETHING_WRONG", values);
formatHelper.format("${missingName} ${lastName} is Spiderman!");
// Result: "John Parker is Spiderman!"
or delegate it back to the default no key behavior:
...
FormatHelper formatHelper = new FormatHelper((fullMatch, variableName) -> variableName.equals("missingName") ? "John" :
FormatHelper.DEFAULT_NO_KEY_FUNCTION.apply(fullMatch,
variableName), map);
...
For better handling there are also static method representations like:
Map<String, String> values = new HashMap<>();
values.put("firstName", "Peter");
values.put("lastName", "Parker");
FormatHelper.format("${firstName} ${lastName} is Spiderman!", map);
// Result: "Peter Parker is Spiderman!"
Instead of using
response.sendRedirect("/demo.jsp");
Which does a permanent redirect to an absolute URL path,
Rather use RequestDispatcher
. Example:
RequestDispatcher dispatcher = request.getRequestDispatcher("demo.jsp");
dispatcher.forward(request, response);
You can simply use random_number
.
If a positive integer is given as n, random_number
returns an integer: 0 <= random_number
< n.
Use it like this:
any_number = SecureRandom.random_number(100)
The output will be any number between 0 and 100.
.contentBlock {_x000D_
width: {define width}_x000D_
width: 400px;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
margin-left: auto;_x000D_
margin-right: auto;_x000D_
_x000D_
}
_x000D_
You can use ElementRef as shown below,
DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.
import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';
@Directive({
selector:"[move]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){
}
show(){
console.log(this.el.nativeElement);
console.log('height---' + this.el.nativeElement.offsetHeight); //<<<===here
console.log('width---' + this.el.nativeElement.offsetWidth); //<<<===here
}
}
Same way you can use it within component itself wherever you need it.
Because you are choosing jre
dir. and not JDK
dir. JDK
dir. is for instance (depending on update and whether it's 64 bit or 32 bit): C:\Program Files (x86)\Java\jdk1.7.0_45
In my case it's 32 bit JDK 1.7
update 45
You can set the state of the checkbox based on the value:
$('#your-checkbox').prop('checked', value == 1);
You have several options for iterating over a dictionary.
If you iterate over the dictionary itself (for team in league
), you will be iterating over the keys of the dictionary. When looping with a for loop, the behavior will be the same whether you loop over the dict (league
) itself, or league.keys()
:
for team in league.keys():
runs_scored, runs_allowed = map(float, league[team])
You can also iterate over both the keys and the values at once by iterating over league.items()
:
for team, runs in league.items():
runs_scored, runs_allowed = map(float, runs)
You can even perform your tuple unpacking while iterating:
for team, (runs_scored, runs_allowed) in league.items():
runs_scored = float(runs_scored)
runs_allowed = float(runs_allowed)
There are actually two ways in which strings can be made in javascript.
var str = 'Javascript';
This creates a primitive string value.
var obj = new String('Javascript');
This creates a wrapper object
of type String
.
typeof str // string
typeof obj // object
So the best way to check for equality is using the ===
operator because it checks value as well as type of both operands.
If you want to check for equality between two objects then using String.prototype.valueOf
is the correct way.
new String('javascript').valueOf() == new String('javascript').valueOf()
if you want to read the file into a table at one time you should use BULK INSERT. ON the other hand if you preffer to parse the file line by line to make your own checks, you should take a look at this web: https://www.simple-talk.com/sql/t-sql-programming/reading-and-writing-files-in-sql-server-using-t-sql/ It is possible that you need to activate your xp_cmdshell or other OLE Automation features. Simple Google it and the script will appear. Hope to be useful.
You would typically first read from the input stream and then close it. You can wrap the FileInputStream in another InputStream (or Reader). It will be automatically closed when you close the wrapping stream/reader.
If this is a method returning an InputStream to the caller, then it is the caller's responsibility to close the stream when finished with it. If you close it in your method, the caller will not be able to use it.
To answer some of your comments...
To send the contents InputStream to a remote consumer, you would write the content of the InputStream to an OutputStream, and then close both streams.
The remote consumer does not know anything about the stream objects you have created. He just receives the content, in an InputStream which he will create, read from and close.
Looping the pointer to gain better performance:
#include <ctype.h>
char* toLower(char* s) {
for(char *p=s; *p; p++) *p=tolower(*p);
return s;
}
char* toUpper(char* s) {
for(char *p=s; *p; p++) *p=toupper(*p);
return s;
}
A quick benchmark:
import collections
import itertools
def count_iter_items(iterable):
counter = itertools.count()
collections.deque(itertools.izip(iterable, counter), maxlen=0)
return next(counter)
def count_lencheck(iterable):
if hasattr(iterable, '__len__'):
return len(iterable)
d = collections.deque(enumerate(iterable, 1), maxlen=1)
return d[0][0] if d else 0
def count_sum(iterable):
return sum(1 for _ in iterable)
iter = lambda y: (x for x in xrange(y))
%timeit count_iter_items(iter(1000))
%timeit count_lencheck(iter(1000))
%timeit count_sum(iter(1000))
The results:
10000 loops, best of 3: 37.2 µs per loop
10000 loops, best of 3: 47.6 µs per loop
10000 loops, best of 3: 61 µs per loop
I.e. the simple count_iter_items is the way to go.
Adjusting this for python3:
61.9 µs ± 275 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
74.4 µs ± 190 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
82.6 µs ± 164 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
(be sure to follow JPH feedback above about the proper ffmpeg download) Not sure why, but in my case here is the one that worked (in my case was on windows).
Initialize a writer:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
Writer = animation.FFMpegWriter(fps=30, codec='libx264') #or
Writer = animation.FFMpegWriter(fps=20, metadata=dict(artist='Me'), bitrate=1800) ==> This is WORKED FINE ^_^
Writer = animation.writers['ffmpeg'] ==> GIVES ERROR ""RuntimeError: Requested MovieWriter (ffmpeg) not available""
[^\[]
Match any character that is not [.
+
Match 1 or more of the anything that is not [
. Creates groups of these matches.
(?=\])
Positive lookahead ]
. Matches a group ending with ]
without including it in the result.
Done.
[^\[]+(?=\])
Proof.
Similar to the solution proposed by null. But the additional \]
is not required. As an additional note, it appears \
is not required to escape the [
after the ^
. For readability, I would leave it in.
Does not work in the situation in which the delimiters are identical. "more or less"
for example.
This is not a compiler error: the error is coming from the linker. After compilation, the linker will merge the object files resulting from the compilation of each of your translation units (.cpp
files).
The linker finds out that you have the same symbol defined multiple times in different translation units, and complains about it (it is a violation of the One Definition Rule).
The reason is most certainly that main.cpp
includes client.cpp
, and both these files are individually processed by the compiler to produce two separate object files. Therefore, all the symbols defined in the client.cpp
translation unit will be defined also in the main.cpp
translation unit. This is one of the reasons why you do not usually #include
.cpp
files.
Put the definition of your class in a separate client.hpp
file which does not contain also the definitions of the member functions of that class; then, let client.cpp
and main.cpp
include that file (I mean #include
). Finally, leave in client.cpp
the definitions of your class's member functions.
client.h
#ifndef SOCKET_CLIENT_CLASS
#define SOCKET_CLIENT_CLASS
#ifndef BOOST_ASIO_HPP
#include <boost/asio.hpp>
#endif
class SocketClient // Or whatever the name is...
{
// ...
bool read(int, char*); // Or whatever the name is...
// ...
};
#endif
client.cpp
#include "Client.h"
// ...
bool SocketClient::read(int, char*)
{
// Implementation goes here...
}
// ... (add the definitions for all other member functions)
main.h
#include <iostream>
#include <string>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include "client.h"
// ^^ Notice this!
main.cpp
#include "main.h"
The following are the ways to pass a arguments/parameters to function in C++.
1. by value.
// passing parameters by value . . .
void foo(int x)
{
x = 6;
}
2. by reference.
// passing parameters by reference . . .
void foo(const int &x) // x is a const reference
{
x = 6;
}
// passing parameters by const reference . . .
void foo(const int &x) // x is a const reference
{
x = 6; // compile error: a const reference cannot have its value changed!
}
3. by object.
class abc
{
display()
{
cout<<"Class abc";
}
}
// pass object by value
void show(abc S)
{
cout<<S.display();
}
// pass object by reference
void show(abc& S)
{
cout<<S.display();
}
So this function gets rid of most of a specified listener type on an element:
function removeListenersFromElement(element, listenerType){
const listeners = getEventListeners(element)[listenerType];
let l = listeners.length;
for(let i = l-1; i >=0; i--){
removeEventListener(listenerType, listeners[i].listener);
}
}
There have been a few rare exceptions where one can't be removed for some reason.
Alternative way of achieving same result is not to use JOIN
keyword at all.
UPDATE TABLE_A, TABLE_B
SET TABLE_A.column_c = TABLE_B.column_c + 1
WHERE TABLE_A.join_col = TABLE_B.join_col
If you
you can do that starting with git 2.10. 2.10 or later is required, because 2.10 fixed the behavior of text=auto together with eol=lf. Source.
Put a .gitattributes
file in the root of your git repository having following contents:
* text=auto eol=lf
Commit it.
You can also add an .editorconfig
in the root of your repository to ensure that modern tooling creates new files with the desired line endings.
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
The correct way to set the column width is by using the line as posted by Jahmic, however it is important to note that additionally, you have to apply styling after adding the data, and not before, otherwise on some configurations, the column width is not applied
Managed code is what C#.Net, VB.Net, F#.Net etc compilers create. It runs on the CLR, which among other things offers services like garbage collection, and reference checking, and much more. So think of it as, my code is managed by the CLR.
On the other hand, unmanaged code compiles straight to machine code. It doesn't manage by CLR.
You should not replace the text entirely. Add the text after the "# END WordPress".
setColor(). Assuming you use Graphics g in an AWT context.
Please refer to the documentation for additional information.
java -d64 -Xms512m -Xmx4g HelloWorld
where, -d64: Will enable 64-bit JVM -Xms512m: Will set initial heap size as 512 MB -Xmx4g: Will set maximum heap size as 4 GB (here java file name is : HelloWorld.java)
I stumbled upon this thread because I wanted to always reference the "cell to the left" but CRUCIALLY in a non-volatile way (no OFFSET, INDIRECT and similar disasters). Looking the web up and down, no answers. (This thread does not actually provide an answer either.) After some tinkering about I stumbled upon the most astonishing method, which I like to share with this community:
Suppose a starting value of 100 in E6. Suppose I enter a delta to this value in F5, say 5. We would then calculate the continuation value (105) in F6 = E6+F5. If you want to add another step, easy: just copy column F to column G and enter a new delta in G5.
This is what we do, periodically. Each column has a date and these dates MUST BE in chronological order (to help with MATCH etc). Every so often it happens that we forget to enter a step. Now suppose you want to insert a column between F and G (to catch up with your omission) and copy F into the new G (to repopulate the continuation formula). This is NOTHING SHORT of a total disaster. Try it - H6 will now say =F6+H5 and NOT (as we absolutely need it to) =G6+H5. (The new G6 will be correct.)
To make this work, we can obfuscate this banal calculation in the most astonishing manner F6=index($E6:F6;1;columns($E1:F1)-1)+F5. Copy right and you get G6=index($E6:G6;1;columns($E1:G1)-1)+G5.
This should never work, right? Circular reference, clearly! Try it out and be amazed. Excel seems to realize that although the INDEX range spans the cell we are recalculating, that cell itself is not addressed by the INDEX and thus DOES NOT create a circular reference.
So now I am home and dry. Insert a column between F and G and we get exactly what we need: The continuation value in the old H will refer back to the continuation value we inserted in the new G.
Sure. Just rename the branch locally, push the new branch, and push a deletion of the old.
The only real issue is that other users of the repository won't have local tracking branches renamed.
You can set height and width like this also:
viewinstance.setLayoutParams(new LayoutParams(width, height));
Use a Profiler
Your approach will work nevertheless, but if you are looking for more sophisticated approaches. I'd suggest using a C# Profiler.
The advantages they have is:
There are many available open-source as well.
Usually I wrap the output into a list, which is very flexible (you can have any combination of numbers, strings, vectors, matrices, arrays, lists, objects int he output)
so like:
func2<-function(input) {
a<-input+1
b<-input+2
output<-list(a,b)
return(output)
}
output<-func2(5)
for (i in output) {
print(i)
}
[1] 6
[1] 7
I think that You have memory leaks somewhere. You can find tips to avoid leaking memory here. Also you can learn about tools to track it down here.
Use the built-in functions for length and max on the description column:
SELECT MAX(LEN(DESC)) FROM table_name;
Note that if your table is very large, there can be performance issues.
When I caught the exception java.lang.NoClassDefFoundError: com/google/common/base/Function
it was caused by errors in Project Libraries.
Please check it in your project settings. For Intellij IDEA go to File - Project Structure and select Modules tab. All I needed to do to resolve this exception was re-adding the selenium library
$('div.alldivs :first-child');
Or you can just refer to the id directly:
$('#div1');
As suggested, you might be better of using the child selector:
$('div.alldivs > div:first-child')
If you dont have to use first-child
, you could use :first
as also suggested, or $('div.alldivs').children(0)
.
Sometimes you want to change the capitalization of a lot of file names on a case insensitive filesystem (e.g. on OS X or Windows). Doing git mv
commands will tire quickly. To make things a bit easier this is what I do:
git add . -A
to remove all files.git add .
. Git should see that the files are renamed.Now you can make a commit saying you have changed the file name capitalization.
This one was your solution.
$x = 0;
while($row = mysqli_fetch_array($result)) {
$posts[$x]['post_id'] = $row['post_id'];
$posts[$x]['post_title'] = $row['post_title'];
$posts[$x]['type'] = $row['type'];
$posts[$x]['author'] = $row['author'];
$x++;
}
g.setFont(new Font("TimesRoman", Font.PLAIN, fontSize));
Where fontSize is a int. The API for drawString states that the x and y parameters are coordinates, and have nothing to do with the size of the text.
In simple DOM usage you can check the condition
element.scrollTop + element.clientHeight == element.scrollHeight
if true then you have reached the end.
I've not seen this solution presented yet; this is my preference for its simpler readability:
select dateadd(month,-1,format(getutcdate(),'yyyy-MM-01'))
I have tried to compile everything that needs to be done for self-hosting icons in my answer. You need to follow these 4 simple steps.
Open the iconfont folder of the materialize repository
link- https://github.com/google/material-design-icons/tree/master/iconfont
Download these three icons files ->
MaterialIcons-Regular.woff2 - format('woff2')
MaterialIcons-Regular.woff - format('woff')
MaterialIcons-Regular.ttf - format('truetype');
Note- After Download you can rename it to whatever you like.
Now, go to your CSS and add this code
@font-face {
font-family: 'Material Icons';
font-style: normal;
font-weight: 400;
src: url(MaterialIcons-Regular.eot); /* For IE6-8 */
src: local('Material Icons'),
local('MaterialIcons-Regular'),
url(MaterialIcons-Regular.woff2) format('woff2'),
url(MaterialIcons-Regular.woff) format('woff'),
url(MaterialIcons-Regular.ttf) format('truetype');
}
.material-icons {
font-family: 'Material Icons';
font-weight: normal;
font-style: normal;
font-size: 24px; /* Preferred icon size */
display: inline-block;
line-height: 1;
text-transform: none;
letter-spacing: normal;
word-wrap: normal;
white-space: nowrap;
direction: ltr;
/* Support for all WebKit browsers. */
-webkit-font-smoothing: antialiased;
/* Support for Safari and Chrome. */
text-rendering: optimizeLegibility;
/* Support for Firefox. */
-moz-osx-font-smoothing: grayscale;
/* Support for IE. */
font-feature-settings: 'liga';
}
_x000D_
Note : The address provided in src:url(...) should be with respect to the 'CSS File' and not the index.html file. For example it can be src : url(../myicons/MaterialIcons-Regular.woff2)
<i class="material-icons">face</i>
_x000D_
Click here to see all the icons that can be used.
Hi this worked for me "/opt/lampp/xampp security" in Centos
[root@XXXXX ~]# /opt/lampp/xampp security
XAMPP: Quick security check...
XAMPP: Your XAMPP pages are secured by a password.
XAMPP: Do you want to change the password anyway? [no] yes
XAMPP: Password:
XAMPP: Password (again):
XAMPP: Password protection active. Please use 'xampp' as user name!
XAMPP: MySQL is not accessable via network. Good.
XAMPP: MySQL has a root passwort set. Fine! :)
XAMPP: The FTP password for user 'daemon' is still set to 'xampp'.
XAMPP: Do you want to change the password? [yes]
XAMPP: Password:
XAMPP: Password (again):
XAMPP: Reload ProFTPD...ok.
XAMPP: Done.
[root@XXXXX ~]#
There are two ways I know of
1) Console.ReadLine()
at the end of the program. Disadvantage, you have to change your code and have to remember to take it out
2) Run outside of the debugger CONTROL-F5
this opens a console window outside of visual studio and that window won't close when finished. Advantage, you don't have to change your code. Disadvantage, if there is an exception, it won't drop into the debugger (however when you do get exceptions, you can simply just rerun it in the debugger)
For Spring Boot 2.+, make sure you are using spring.servlet
instead of spring.http
.
---
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
If you have to use tomcat, you might end up creating EmbeddedServletContainerCustomizer, which is not really nice thing to do.
If you can live without tomat, you could replace tomcat with e.g. undertow and avoid this issue at all.
There is an illustrative example of how to create custom colormaps here.
The docstring is essential for understanding the meaning of
cdict
. Once you get that under your belt, you might use a cdict
like this:
cdict = {'red': ((0.0, 1.0, 1.0),
(0.1, 1.0, 1.0), # red
(0.4, 1.0, 1.0), # violet
(1.0, 0.0, 0.0)), # blue
'green': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0),
(0.1, 0.0, 0.0), # red
(0.4, 1.0, 1.0), # violet
(1.0, 1.0, 0.0)) # blue
}
Although the cdict
format gives you a lot of flexibility, I find for simple
gradients its format is rather unintuitive. Here is a utility function to help
generate simple LinearSegmentedColormaps:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
def make_colormap(seq):
"""Return a LinearSegmentedColormap
seq: a sequence of floats and RGB-tuples. The floats should be increasing
and in the interval (0,1).
"""
seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
cdict = {'red': [], 'green': [], 'blue': []}
for i, item in enumerate(seq):
if isinstance(item, float):
r1, g1, b1 = seq[i - 1]
r2, g2, b2 = seq[i + 1]
cdict['red'].append([item, r1, r2])
cdict['green'].append([item, g1, g2])
cdict['blue'].append([item, b1, b2])
return mcolors.LinearSegmentedColormap('CustomMap', cdict)
c = mcolors.ColorConverter().to_rgb
rvb = make_colormap(
[c('red'), c('violet'), 0.33, c('violet'), c('blue'), 0.66, c('blue')])
N = 1000
array_dg = np.random.uniform(0, 10, size=(N, 2))
colors = np.random.uniform(-2, 2, size=(N,))
plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=rvb)
plt.colorbar()
plt.show()
By the way, the for-loop
for i in range(0, len(array_dg)):
plt.plot(array_dg[i], markers.next(),alpha=alpha[i], c=colors.next())
plots one point for every call to plt.plot
. This will work for a small number of points, but will become extremely slow for many points. plt.plot
can only draw in one color, but plt.scatter
can assign a different color to each dot. Thus, plt.scatter
is the way to go.
Unfortunately, there is no perfect IDE for Android. Eclipse has more features as it is the only IDE google developed plugin for. However, if you are just like me, tired of crashes and weired debug/develop mode swithes, Use Netbeans plugin from http://nbandroid.kenai.com.
Live Demo : http://jsfiddle.net/abdennour/ba54W/
$(document).ready(function() {
$("#textA").bind({
copy : function(){
$('span').text('copy behaviour detected!');
},
paste : function(){
$('span').text('paste behaviour detected!');
},
cut : function(){
$('span').text('cut behaviour detected!');
}
});
});
Generics:
With Java generics, you don't actually get any of the execution efficiency that you get with .NET because when you compile a generic class in Java, the compiler takes away the type parameter and substitutes Object everywhere. For instance if you have a Foo<T>
class the java compiler generates Byte Code as if it was Foo<Object>
. This means casting and also boxing/unboxing will have to be done in the "background".
I've been playing with Java/C# for a while now and, in my opinion, the major difference at the language level are, as you pointed, delegates.
I ran into a similar issue when trying to get composer to install some dependencies. It turns out the .dll my version of Wamp came with had a conflict, I am guessing, with 64 bit Windows.
This url has fixed curl dlls: http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/
Scroll down to the section that says: Fixed Curl Extensions.
I downloaded "php_curl-5.4.3-VC9-x64.zip". I just overwrote the dll inside the wamp/bin/php/php5.4.3/ext directory with the dll that was in the zip file and composer worked again.
I am running 64 bit Windows 8.
Hope this helps.
Rails has its own names. See them with:
rake time:zones:us
You can also run rake time:zones:all
for all time zones.
To see more zone-related rake tasks: rake -D time
So, to convert to EST, catering for DST automatically:
Time.now.in_time_zone("Eastern Time (US & Canada)")
div.classList.add("foo");
div.classList.remove("foo");
More at https://developer.mozilla.org/en-US/docs/Web/API/element.classList
As explained here by Filip - http://www.filipekberg.se/2011/10/02/adding-properties-and-methods-to-an-expandoobject-dynamicly/
You can add a method too at runtime.
x.Add("Shout", new Action(() => { Console.WriteLine("Hellooo!!!"); }));
x.Shout();
Look at jQuery Toggle
HTML:
<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
jQuery:
jQuery(document).ready(function(){
jQuery('#hideshow').live('click', function(event) {
jQuery('#content').toggle('show');
});
});
For versions of jQuery 1.7 and newer use
jQuery(document).ready(function(){
jQuery('#hideshow').on('click', function(event) {
jQuery('#content').toggle('show');
});
});
For reference, kindly check this demo
defaultMember
already is an alias - it doesn't need to be the name of the exported function/thing. Just do
import alias from 'my-module';
Alternatively you can do
import {default as alias} from 'my-module';
but that's rather esoteric.
Try this, This was the solution that worked for me:
<div class="modal-dialog" style="min-width: 1500px" role="document">
view.subviews.forEach { $0.removeFromSuperview() }
Use dispatch groups: see here for an example, "Waiting on Groups of Queued Tasks" in the "Dispatch Queues" chapter of Apple's iOS Developer Library's Concurrency Programming Guide
Your example could look something like this:
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
// block1
NSLog(@"Block1");
[NSThread sleepForTimeInterval:5.0];
NSLog(@"Block1 End");
});
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
// block2
NSLog(@"Block2");
[NSThread sleepForTimeInterval:8.0];
NSLog(@"Block2 End");
});
dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
// block3
NSLog(@"Block3");
});
// only for non-ARC projects, handled automatically in ARC-enabled projects.
dispatch_release(group);
and could produce output like this:
2012-08-11 16:10:18.049 Dispatch[11858:1e03] Block1
2012-08-11 16:10:18.052 Dispatch[11858:1d03] Block2
2012-08-11 16:10:23.051 Dispatch[11858:1e03] Block1 End
2012-08-11 16:10:26.053 Dispatch[11858:1d03] Block2 End
2012-08-11 16:10:26.054 Dispatch[11858:1d03] Block3
In Jsp:
action="profile/proffiesional"
In Controller
@RequestMapping(value = "proffessional", method = RequestMethod.POST)
Spelling MisMatch !
You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause. It goes a little something like this:
WITH cte AS (
SELECT[foo], [bar],
row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
FROM TABLE
)
DELETE cte WHERE [rn] > 1
Play around with it and see what you get.
(Edit: In an attempt to be helpful, someone edited the ORDER BY
clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc
)
You have to specify negative spread
in the box shadow to remove side shadow
-webkit-box-shadow: 0 10px 10px -10px #000000;
-moz-box-shadow: 0 10px 10px -10px #000000;
box-shadow: 0 10px 10px -10px #000000;
Check out http://dabblet.com/gist/9532817 and try changing properties and know how it behaves
CSS
If this doesn't work:
.modal-backdrop {
background-color: red;
}
try this:
.modal {
background-color: red !important;
}
$_ is an alias for automatic variable $PSItem (introduced in PowerShell V3.0; Usage information found here) which represents the current item from the pipe.
PowerShell (v6.0) online documentation for automatic variables is here.
SELECT Col.Column_Name from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE
Col.Constraint_Name = Tab.Constraint_Name
AND Col.Table_Name = Tab.Table_Name
AND Constraint_Type = 'PRIMARY KEY'
AND Col.Table_Name = '<your table name>'
I have ubuntu 14 and the other answers where no working for me
iconv -f ISO-8859-1 -t UTF-8 in.tex > out.tex
I found this command here
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=
Finding of week number for each date of a month (considering Monday as beginning of the week)
Keep the first date of month contant $B$13
=WEEKNUM(B18,2)-WEEKNUM($B$13,2)+1
WEEKNUM(B18,2)
- returns the week number of the date mentioned in cell B18
WEEKNUM($B$13,2)
- returns the week number of the 1st date of month in cell B13
len(response['Items'])
will give you the count of the filtered rows
where,
fe = Key('entity').eq('tesla')
response = table.scan(FilterExpression=fe)
It is because there is a DLL that your program is missing or can't find.
In your case I believe you are missing the openCV dlls. You can find these under the "build" directory that comes with open CV. If you are using VS2010 and building to an x86 program you can locate your dlls here under "opencv\build\x86\vc10\bin". Simply copy all these files to your Debug and Release folders and it should resolve your issues.
Generally you can resolve this issue using the following procedure:
Remember that you will need to have these DLLs in the same directory as your .exe. If you copy the .exe from the Release folder to somewhere else then you will need those DLLs copied with the .exe as well. For portability I tend to try and have a test Virtual Machine with a clean install of Windows (no updates or programs installed), and I walk through the Dependencies using the Dependency Walker one by one until the program is running happily.
This is a common problem. Also see these questions:
Can't run a vc++, error code 0xc0150002
The application was unable to start (0xc0150002) with libcurl C++ Windows 7 VS 2010
0xc0150002 Error when trying to run VC++ libcurl
The application was unable to start correctly 0xc150002
The application was unable to start correctly (0*0150002) - OpenCv
Good Luck!
Unfortunately, there is no :click pseudo selector. If you want to change styling on click, you should use Jquery/Javascript. It certainly is better than the "hack" for pure HTML / CSS. But if you insist...
input {_x000D_
display: none;_x000D_
}_x000D_
span {_x000D_
padding: 20px;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
input:checked + span {_x000D_
background: #444;_x000D_
color: #fff;_x000D_
}
_x000D_
<label for="input">_x000D_
<input id="input" type="radio" />_x000D_
<span>NO JS styling</span>_x000D_
</label>
_x000D_
Or, if you prefer, you can toggle the styling:
input {_x000D_
display: none;_x000D_
}_x000D_
span {_x000D_
padding: 20px;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
input:checked + span {_x000D_
background: #444;_x000D_
color: #fff;_x000D_
}
_x000D_
<label for="input">_x000D_
<input id="input" type="checkbox" />_x000D_
<span>NO JS styling</span>_x000D_
</label>
_x000D_
When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake.
Strings using set()
:
set(MyString "Some Text")
set(MyStringWithVar "Some other Text: ${MyString}")
set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"")
Or with string()
:
string(APPEND MyStringWithContent " ${MyString}")
Lists using set()
:
set(MyList "a" "b" "c")
set(MyList ${MyList} "d")
Or better with list()
:
list(APPEND MyList "a" "b" "c")
list(APPEND MyList "d")
Lists of File Names:
set(MySourcesList "File.name" "File with Space.name")
list(APPEND MySourcesList "File.name" "File with Space.name")
add_excutable(MyExeTarget ${MySourcesList})
set()
Commandstring()
Commandlist()
CommandFirst there are the "Normal Variables" and things you need to know about their scope:
CMakeLists.txt
they are set in and everything called from there (add_subdirectory()
, include()
, macro()
and function()
).add_subdirectory()
and function()
commands are special, because they open-up their own scope.
set(...)
there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope).set(... PARENT_SCOPE)
function(xyz _resultVar)
is setting set(${_resultVar} 1 PARENT_SCOPE)
include()
or macro()
scripts will modify variables directly in the scope of where they are called from. Second there is the "Global Variables Cache". Things you need to know about the Cache:
CMakeCache.txt
file in your binary output directory.The values in the Cache can be modified in CMake's GUI application before they are generated. Therefore they - in comparison to normal variables - have a type
and a docstring
. I normally don't use the GUI so I use set(... CACHE INTERNAL "")
to set my global and persistant values.
Please note that the INTERNAL
cache variable type does imply FORCE
In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE)
syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value.
cmake -D var:type=value
, just cmake -D var=value
or with cmake -C CMakeInitialCache.cmake
.unset(... CACHE)
.The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...)
and set_property(GLOBAL APPEND PROPERTY ...)
syntax to define my own non-persistant global variables.
To avoid pitfalls you should know the following about variables:
find_...
commands - if successful - do write their results as cached variables "so that no call will search again"set(MyVar a b c)
is "a;b;c"
and set(MyVar "a b c")
is "a b c"
list()
command for handling listsfunctions()
instead of macros()
because you don't want your local variables to show up in the parent scope. project()
and enable_language()
calls. So it could get important to set some variables before those commands are used.Sometimes only debugging variables helps. The following may help you:
printf
debugging style by using the message()
command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmake, CMakePrintSystemInformation.cmakeCMakeCache.txt
file in your binary output directory. This file is even generated if the actual generation of your make environment fails.cmake --trace ...
to see the CMake's complete parsing process. That's sort of the last reserve, because it generates a lot of output.$ENV{...}
and write set(ENV{...} ...)
environment variables$<...>
are only evaluated when CMake's generator writes the make environment (it comparison to normal variables that are replaced "in-place" by the parser)${${...}}
you can give variable names in a variable and reference its content.if()
command)
if(MyVariable)
you can directly check a variable for true/false (no need here for the enclosing ${...}
)1
, ON
, YES
, TRUE
, Y
, or a non-zero number. 0
, OFF
, NO
, FALSE
, N
, IGNORE
, NOTFOUND
, the empty string, or ends in the suffix -NOTFOUND
.if(MSVC)
, but it can be confusing for someone who does not know this syntax shortcut.set(CMAKE_${lang}_COMPILER ...)
if()
commands. Here is an example where CMAKE_CXX_COMPILER_ID
is "MSVC"
and MSVC
is "1"
:
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
is true, because it evaluates to if("1" STREQUAL "1")
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
is false, because it evaluates to if("MSVC" STREQUAL "1")
if(MSVC)
cmake_policy(SET CMP0054 NEW)
to "only interpret if()
arguments as variables or keywords when unquoted."option()
command
ON
or OFF
and they allow some special handling like e.g. dependenciesoption
with the set
command. The value given to option
is really only the "initial value" (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake's GUI.You can use this attributes:
background-size: contain;
background-repeat: no-repeat;
and you code is then like this:
<div style="text-align:center;background-image: url(/media/img_1_bg.jpg); background-size: contain;
background-repeat: no-repeat;" id="mainpage">
Tweaked version from Techie Delight:
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delim) {
std::vector<std::string> strings;
size_t start;
size_t end = 0;
while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
end = str.find(delim, start);
strings.push_back(str.substr(start, end - start));
}
return strings;
}
body { text-align: center; }
/* center all items within body, this property is inherited */
body > * { text-align: left; }
/* left-align the CONTENTS all items within body, additionally
you can add this text-align: left property to all elements
manually */
form { display: inline-block; }
/* reduces the width of the form to only what is necessary */
?
Works & tested in Chrome/IE/FF
If you are going to run apps as jar file in command environment, just type "SERVER_PORT=*** " as prefix. The full command to execute will look like below:
SERVER_PORT=8080 java -jar ***.jar
If you wanna run app in background in Linux, command with 'nohup' will look like below:
SERVER_PORT=8080 nohup java -jar ***.jar &
Either use multiple keyword arguments in the definition, or create a Bullet
hierarchy whose instances are passed to the function.
For checkbox with an id
<input id="id_input_checkbox13" type="checkbox"></input>
you can simply do
$("#id_input_checkbox13").prop('checked')
you will get true
or false
as return value for above syntax. You can use it in if clause as normal boolean expression.
If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:
Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.
Basically, you can do something like this:
function doCall(urlToCall) {
return co(function *(){
var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return finalData;
});
}
Then,
var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.
By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.
You can use a 3rd party library like Shield UI for charting - that is tested and works well on all legacy and new web browsers and devices.
Is not possbile!
The only way is to obfuscate javascript or minify your javascript which makes it hard for the end user to reverse engineer. however its not impossible to reverse engineer.
To get a definitive reason, you'd need to ask the designer(s) of that API.
But one possible reason is that the intent of a (hypothetical) nextChar
would not fit into the scanning model very well.
If nextChar()
to behaved like read()
on a Reader
and simply returned the next unconsumed character from the scanner, then it is behaving inconsistently with the other next<Type>
methods. These skip over delimiter characters before they attempt to parse a value.
If nextChar()
to behaved like (say) nextInt
then:
the delimiter skipping would be "unexpected" for some folks, and
there is the issue of whether it should accept a single "raw" character, or a sequence of digits that are the numeric representation of a char
, or maybe even support escaping or something1.
No matter what choice they made, some people wouldn't be happy. My guess is that the designers decided to stay away from the tarpit.
1 - Would vote strongly for the raw character approach ... but the point is that there are alternatives that need to be analysed, etc.
this worked better for me,
@echo off
set temp=%DATE:/=%
set dirname="%temp:~4,4%%temp:~2,2%%temp:~0,2%"
mkdir %dirname%
Prior to Hibernate 5.4.1, the optimistic locking failure exceptions (e.g., StaleStateException
or OptimisticLockException
) didn't include the failing statement.
The HHH-12878 issue was created to improve Hibernate so that when throwing an optimistic locking exception, the JDBC PreparedStatement
implementation is logged as well:
if ( expectedRowCount > rowCount ) {
throw new StaleStateException(
"Batch update returned unexpected row count from update ["
+ batchPosition + "]; actual row count: " + rowCount
+ "; expected: " + expectedRowCount + "; statement executed: "
+ statement
);
}
I created the
BatchingOptimisticLockingTest
in my High-Performance Java Persistence GitHub repository to demonstrate how the new behavior works.
First, we will define a Post
entity that defines a @Version
property, therefore enabling the implicit optimistic locking mechanism:
@Entity(name = "Post")
@Table(name = "post")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String title;
@Version
private short version;
public Long getId() {
return id;
}
public Post setId(Long id) {
this.id = id;
return this;
}
public String getTitle() {
return title;
}
public Post setTitle(String title) {
this.title = title;
return this;
}
public short getVersion() {
return version;
}
}
We will enable the JDBC batching using the following 3 configuration properties:
properties.put("hibernate.jdbc.batch_size", "5");
properties.put("hibernate.order_inserts", "true");
properties.put("hibernate.order_updates", "true");
We are going to create 3 Post
entities:
doInJPA(entityManager -> {
for (int i = 1; i <= 3; i++) {
entityManager.persist(
new Post()
.setTitle(String.format("Post no. %d", i))
);
}
});
And Hibernate will execute a JDBC batch insert:
SELECT nextval ('hibernate_sequence')
SELECT nextval ('hibernate_sequence')
SELECT nextval ('hibernate_sequence')
Query: [
INSERT INTO post (title, version, id)
VALUES (?, ?, ?)
],
Params:[
(Post no. 1, 0, 1),
(Post no. 2, 0, 2),
(Post no. 3, 0, 3)
]
So, we know that JDBC batching works just fine.
Now, let's replicate the optimistic locking issue:
doInJPA(entityManager -> {
List<Post> posts = entityManager.createQuery("""
select p
from Post p
""", Post.class)
.getResultList();
posts.forEach(
post -> post.setTitle(
post.getTitle() + " - 2nd edition"
)
);
executeSync(
() -> doInJPA(_entityManager -> {
Post post = _entityManager.createQuery("""
select p
from Post p
order by p.id
""", Post.class)
.setMaxResults(1)
.getSingleResult();
post.setTitle(post.getTitle() + " - corrected");
})
);
});
The first transaction selects all Post
entities and modifies the title
properties.
However, before the first EntityManager
is flushed, we are going to execute a second transition using the executeSync
method.
The second transaction modifies the first Post
, so its version
is going to be incremented:
Query:[
UPDATE
post
SET
title = ?,
version = ?
WHERE
id = ? AND
version = ?
],
Params:[
('Post no. 1 - corrected', 1, 1, 0)
]
Now, when the first transaction tries to flush the EntityManager
, we will get the OptimisticLockException
:
Query:[
UPDATE
post
SET
title = ?,
version = ?
WHERE
id = ? AND
version = ?
],
Params:[
('Post no. 1 - 2nd edition', 1, 1, 0),
('Post no. 2 - 2nd edition', 1, 2, 0),
('Post no. 3 - 2nd edition', 1, 3, 0)
]
o.h.e.j.b.i.AbstractBatchImpl - HHH000010: On release of batch it still contained JDBC statements
o.h.e.j.b.i.BatchingBatch - HHH000315: Exception executing batch [
org.hibernate.StaleStateException:
Batch update returned unexpected row count from update [0];
actual row count: 0;
expected: 1;
statement executed:
PgPreparedStatement [
update post set title='Post no. 3 - 2nd edition', version=1 where id=3 and version=0
]
],
SQL: update post set title=?, version=? where id=? and version=?
So, you need to upgrade to Hibernate 5.4.1 or newer to benefit from this improvement.
Here´s how I do it:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2</version>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.project.MainClass</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
And then I just run:
mvn assembly:assembly
I had the following problem:
I had a Android phone without drivers, and it could not be recognized by the Windows 8.1. Neither as phone, neither as USB storage device.
I searched Device manager.
I opened Device manager, I right click on Android Phone->Android Composite Interface.
I selected "Update Driver Software"
I choose "Browse My Computer for Driver Software"
Then I choose "Let me pick from a list of devices"
I selected "USB Composite Device"
A new USB device is added to the list, and I can connect to my phone using adb and Android SDK.
Also I can use the phone as storage device.
Good luck
--Use data-interval="false" to stop automatic slide --Use data-wrap="false" to stop circular slide
...It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:
mysql> SELECT @@sql_mode;
+------------+
| @@sql_mode |
+------------+
| |
+------------+
1 row in set (0.00 sec)
mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @@sql_mode;
+----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode |
+----------------------------------------------------------------------------------------------------------------------+
| PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER |
+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
Don't forget to write the permissions without extra spaces in the manifest. In my case i had:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE " />
But look, at the end, there's an extra space. Just write it the right way
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And it's working now
Some permissions issue for default sample.
I wanted to see how it works, I am creating the first extension, so I downloaded a simpler one.
Downloaded 'Typed URL History' sample from
https://developer.chrome.com/extensions/examples/api/history/showHistory.zip
which can be found at
https://developer.chrome.com/extensions/samples
this worked great, hope it helps
remember that the use of "live" is for "jQuery 1.3" or higher
in version "jQuery 1.4.3" or higher is used "delegate"
and version "jQuery 1.7 +" or higher is used "on"
$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+
As of jQuery 1.7, the .live() method is deprecated.
check http://api.jquery.com/live/
Regards, Fernando
You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.
Here is a solution that cleans up a lot of code and makes the animation start from the center:
.gps_ring {
border: 3px solid #999;
-webkit-border-radius: 30px;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
You can see it in action here: http://jsfiddle.net/Fy8vD/
Pure Javascript only
var t1 = 0;_x000D_
window.onscroll = scroll1;_x000D_
_x000D_
function scroll1() {_x000D_
var toTop = document.getElementById('toTop');_x000D_
window.scrollY > 0 ? toTop.style.display = 'Block' : toTop.style.display = 'none';_x000D_
}_x000D_
_x000D_
function abcd() {_x000D_
var y1 = window.scrollY;_x000D_
y1 = y1 - 1000;_x000D_
window.scrollTo(0, y1);_x000D_
if (y1 > 0) {_x000D_
t1 = setTimeout("abcd()", 100);_x000D_
} else {_x000D_
clearTimeout(t1);_x000D_
}_x000D_
}
_x000D_
#toTop {_x000D_
display: block;_x000D_
position: fixed;_x000D_
bottom: 20px;_x000D_
right: 20px;_x000D_
font-size: 48px;_x000D_
}_x000D_
_x000D_
#toTop {_x000D_
transition: all 0.5s ease 0s;_x000D_
-moz-transition: all 0.5s ease 0s;_x000D_
-webkit-transition: all 0.5s ease 0s;_x000D_
-o-transition: all 0.5s ease 0s;_x000D_
opacity: 0.5;_x000D_
display: none;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
#toTop:hover {_x000D_
opacity: 1;_x000D_
}
_x000D_
<p>your text here</p>_x000D_
<img id="toTop" src="http://via.placeholder.com/50x50" onclick="abcd()" title="Go To Top">
_x000D_
The existing answers are better for how to get the correct value, but I can at least explain why getrusage isn't working for you.
man 2 getrusage:
The above struct [rusage] was taken from BSD 4.3 Reno. Not all fields are meaningful under Linux. Right now (Linux 2.4, 2.6) only the fields ru_utime, ru_stime, ru_minflt, ru_majflt, and ru_nswap are maintained.
Everything that is business logic belongs in a model, whether it is a database query, calculations, a REST call, etc.
You can have the data access in the model itself, the MVC pattern doesn't restrict you from doing that. You can sugar coat it with services, mappers and what not, but the actual definition of a model is a layer that handles business logic, nothing more, nothing less. It can be a class, a function, or a complete module with a gazillion objects if that's what you want.
It's always easier to have a separate object that actually executes the database queries instead of having them being executed in the model directly: this will especially come in handy when unit testing (because of the easiness of injecting a mock database dependency in your model):
class Database {
protected $_conn;
public function __construct($connection) {
$this->_conn = $connection;
}
public function ExecuteObject($sql, $data) {
// stuff
}
}
abstract class Model {
protected $_db;
public function __construct(Database $db) {
$this->_db = $db;
}
}
class User extends Model {
public function CheckUsername($username) {
// ...
$sql = "SELECT Username FROM" . $this->usersTableName . " WHERE ...";
return $this->_db->ExecuteObject($sql, $data);
}
}
$db = new Database($conn);
$model = new User($db);
$model->CheckUsername('foo');
Also, in PHP, you rarely need to catch/rethrow exceptions because the backtrace is preserved, especially in a case like your example. Just let the exception be thrown and catch it in the controller instead.
This will give you the two's complement efficiently using bitwise logic:
def twos_complement(value, bitWidth):
if value >= 2**bitWidth:
# This catches when someone tries to give a value that is out of range
raise ValueError("Value: {} out of range of {}-bit value.".format(value, bitWidth))
else:
return value - int((value << 1) & 2**bitWidth)
How it works:
First, we make sure that the user has passed us a value that is within the range of the supplied bit range (e.g. someone gives us 0xFFFF and specifies 8 bits) Another solution to that problem would be to bitwise AND (&) the value with (2**bitWidth)-1
To get the result, the value is shifted by 1 bit to the left. This moves the MSB of the value (the sign bit) into position to be anded with 2**bitWidth
. When the sign bit is '0' the subtrahend becomes 0 and the result is value - 0
. When the sign bit is '1' the subtrahend becomes 2**bitWidth
and the result is value - 2**bitWidth
Example 1: If the parameters are value=0xFF (255d, b11111111) and bitWidth=8
Example 2: If the parameters are value=0x1F (31d, b11111) and bitWidth=6
Example 3: value = 0x80, bitWidth = 7
ValueError: Value: 128 out of range of 7-bit value.
Example 4: value = 0x80, bitWitdh = 8
Now, using what others have already posted, pass your bitstring into int(bitstring,2) and pass to the twos_complement method's value parameter.
You can make ArrayList of ViewHolder :
ArrayList<MyViewHolder> myViewHolders = new ArrayList<>();
ArrayList<MyViewHolder> myViewHolders2 = new ArrayList<>();
and, all store ViewHolder(s) in the list like :
@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
final String str = arrayList.get(position);
myViewHolders.add(position,holder);
}
and add/remove other ViewHolder in the ArrayList as per your requirement.
Another way :
decimal.Round(decimalvalue, 2, MidpointRounding.AwayFromZero);
//note: use of stop function to prevent animation build-ups if called repeatedly
//subtracting container height brings scrollTo position to container bottom
scrollUp = function() {
$("#scroller").stop().animate({ scrollTop: 0 }, "slow");
}
scrollDown = function() {
var scroller = $('#scroller');
var height = scroller[0].scrollHeight - $(scroller).height();
$(scroller).stop().animate({ scrollTop: height }, "slow");
}
Check if there is whitespace before =
sign of excel formula
I think using dtype
where there is a name row is confusing the routine. Try
>>> r = np.genfromtxt(fname, delimiter=',', names=True)
>>> r
array([[ 6.11882430e+02, 9.08956010e+03, 5.13300000e+03,
8.64075140e+02, 1.71537476e+03, 7.65227770e+02,
1.29111196e+12],
[ 6.11882430e+02, 9.08956010e+03, 5.13300000e+03,
8.64075140e+02, 1.71537476e+03, 7.65227770e+02,
1.29111311e+12],
[ 6.11882430e+02, 9.08956010e+03, 5.13300000e+03,
8.64075140e+02, 1.71537476e+03, 7.65227770e+02,
1.29112065e+12]])
>>> r[:,0] # Slice 0'th column
array([ 611.88243, 611.88243, 611.88243])
For string comparisons in Perl, use eq
or ne
:
if ($str eq "")
{
// ...
}
The ==
and !=
operators are numeric comparison operators. They will attempt to convert both operands to integers before comparing them.
See the perlop man page for more information.
Creates n dimensional matrix array for Java Script, filling with initial default of value 0.
function arr (arg, def = 0){
if (arg.length > 2){
return Array(arg[0]).fill().map(()=>arr(arg.slice(1)));
} else {
return Array(arg[0]).fill().map(()=>Array(arg[1]).fill(def));
}
}
// Simple Usage of 4 dimensions
var s = arr([3,8,4,6])
// Use null default value with 2 dimensions
var k = arr([5,6] , null)
First some code, then the explanaition. The official docs describing this are here.
import { trigger, transition, animate, style } from '@angular/animations'
@Component({
...
animations: [
trigger('slideInOut', [
transition(':enter', [
style({transform: 'translateY(-100%)'}),
animate('200ms ease-in', style({transform: 'translateY(0%)'}))
]),
transition(':leave', [
animate('200ms ease-in', style({transform: 'translateY(-100%)'}))
])
])
]
})
In your template:
<div *ngIf="visible" [@slideInOut]>This element will slide up and down when the value of 'visible' changes from true to false and vice versa.</div>
I found the angular way a bit tricky to grasp, but once you understand it, it quite easy and powerful.
The animations part in human language:
->then animate the translateY value until we are at 0%, where the element would naturally be.
When the element is removed, animate the translateY value (currently 0), to -100% (off screen).
The easing function we're using is ease-in, in 200 milliseconds, you can change that to your liking.
Hope this helps!
I think for IE you will need to use the srcElement property of the Event object. if jQuery is an option for you, you may want to consider using it - as it abstracts most browser differences for you. Example jQuery:
$("#tableId tr").click(function() {
alert($(this).children("td").html());
});
PHPMailerAutoload
needs to be in the same folder as class.phpmailer.php
This is the PHPMailerAutoload
code that I assume this:
$filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';
It can be done in css and it is very simple. change the "a" to a "p". Your "page link" does not lead to somewhere anyway if you want to make it unclickable.
When you tell your css to do a hover action on this specific "p" tell it this:
(for this example I have given the "p" the "example" ID)
#example
{
cursor:default;
}
Now your cursor will stay the same as it does all over the page.
If you just need to make simple get requests and don't need support for any other HTTP methods take a look at: simple-get:
var get = require('simple-get');
get('http://example.com', function (err, res) {
if (err) throw err;
console.log(res.statusCode); // 200
res.pipe(process.stdout); // `res` is a stream
});
This works with multiple statements:
if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6
Or you can split it over multiple lines:
if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6
I guess you could use curl
and wget
, but since Oracle requires you to check of some checkmarks this will be painfull to emulate with the tools mentioned. You would have to download the page with the license agreement and from looking at it figure out what request is needed to get to the actual download.
Of course you could simply start a browser, but this might not qualify as 'from the command line'. So you might want to look into lynx
, a text based browser.
MrOBrian's answer shows why your current code doesn't work, with the missing trailing ]
and quotes, but here's an easier way to make it work:
onchange='mySelectHandler(this)'
And then:
function mySelectHandler(el){
var mySelect = $(el)
// get selected value
alert ("selected " + mySelect.val())
}
Or better still, remove the inline event handler altogether and bind the event handler with jQuery:
$('select[name="a[b]"]').change(function() {
var mySelect = $(this);
alert("selected " mySelect.val());
});
That last would need to be in a document.ready handler or in a script block that appears after the select element. If you want to run the same function for other selects simply change the selector to something that applies to all, e.g., all selects would be $('select')
, or all with a particular class would be $('select.someClass')
.
<html>
<head>
<title>orientation and device detection in css3</title>
<link rel="stylesheet" media="all and (max-device-width: 480px) and (orientation:portrait)" href="iphone-portrait.css" />
<link rel="stylesheet" media="all and (max-device-width: 480px) and (orientation:landscape)" href="iphone-landscape.css" />
<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait)" href="ipad-portrait.css" />
<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:landscape)" href="ipad-landscape.css" />
<link rel="stylesheet" media="all and (device-width: 800px) and (device-height: 1184px) and (orientation:portrait)" href="htcdesire-portrait.css" />
<link rel="stylesheet" media="all and (device-width: 800px) and (device-height: 390px) and (orientation:landscape)" href="htcdesire-landscape.css" />
<link rel="stylesheet" media="all and (min-device-width: 1025px)" href="desktop.css" />
</head>
<body>
<div id="iphonelandscape">iphone landscape</div>
<div id="iphoneportrait">iphone portrait</div>
<div id="ipadlandscape">ipad landscape</div>
<div id="ipadportrait">ipad portrait</div>
<div id="htcdesirelandscape">htc desire landscape</div>
<div id="htcdesireportrait">htc desire portrait</div>
<div id="desktop">desktop</div>
<script type="text/javascript">
function res() { document.write(screen.width + ', ' + screen.height); }
res();
</script>
</body>
</html>
You need to enable billing to access some of the Google Map APIs
The following solution assumes you are serving your dist/ folder using nodejs. Please use the following app.js in root level
const express = require('express'),http = require('http'),path = require('path'),compression = require('compression');
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.use(compression()) //compressing dist folder
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
})
const port = process.env.PORT || '4201';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log('Running at port ' + port))
Make sure you install dependencies;
npm install compression --save
npm install express --save;
Now build the app
ng build --prod --build-optimizer
If you want to further compress the build say reduce 300kb(approx) from , then follow the below process;
Create a folder called vendor
inside the src
folder and inside vendor folder create a file rxjs.ts
and paste the below code in it;
export {Subject} from 'rxjs/Subject';
export {Observable} from 'rxjs/Observable';
export {Subscription} from 'rxjs/Subscription';
And then add the follwing in the tsconfig.json
file in your angular-cli application. Then in the compilerOptions
, add the following json;
"paths": {
"rxjs": [
"./vendor/rxjs.ts"
]
}
This will make your build size way too smaller. In my project I reduced the size from 11mb to 1mb. Hope it helps
According to the below article:
http://tools.ietf.org/html/rfc3696 (Page 6, Section 3)
It's mentioned that:
"There is a length limit on email addresses. That limit is a maximum of 64 characters (octets) in the "local part" (before the "@") and a maximum of 255 characters (octets) in the domain part (after the "@") for a total length of 320 characters. Systems that handle email should be prepared to process addresses which are that long, even though they are rarely encountered."
So, the maximum total length for an email address is 320 characters ("local part": 64 + "@": 1 + "domain part": 255 which sums to 320)
Just now found where is it on Windows. Its View
-> Active Editor
-> Show Line Numbers
(changes only for current document) and File
-> Settings
-> Editor
-> Appearance
-> Show Line Numbers
(for all documents)
For Mac Version go to PhpStorm
-> Preferences
in menu.
In the preference window go to IDE settings
-> Editor
-> Appearance
-> Show Line Numbers
(To change setting for all documents)
OR if you want to quickly set show line number PER CURRENT WINDOW even easier - right click on the long white column (where breakpoints are set) then select Show Line Numbers.
Red dot on the screenshot is a place where you have to click
Not sure when this changed, but with the latest version of typescript, you just need to use import moment from 'moment';
and everything else should work as normal.
Looks like moment recent fixed their import. As of at least 2.24.0
you'll want to use import * as moment from 'moment';
What seems to be confusing this thread is the difference between:
$('.selector').append("<input type='text'/>");
Which appends the target element as a child of the .selector.
And
$("<input type='text' />").appendTo('.selector');
Which appends the target element as a child of the .selector.
Note how the position of the target element & the .selector change when using the different methods.
What you want to do is this:
$(function() {
// append input control at start of form
$("<input type='text' value='' />")
.attr("id", "myfieldid")
.attr("name", "myfieldid")
.prependTo("#form-0");
// OR
// append input control at end of form
$("<input type='text' value='' />")
.attr("id", "myfieldid")
.attr("name", "myfieldid")
.appendTo("#form-0");
// OR
// see .after() or .before() in the api.jquery.com library
});
I would try the following syntax - it works for me.
msiexec /x filename.msi /q
Use:
import os
print os.sep
to see how separator looks on a current OS.
In your code you can use:
import os
path = os.path.join('folder_name', 'file_name')
<script>
function change_css(){
document.getElementById('result').style.cssText = 'padding:20px; background-color:#b2b2ff; color:#0c0800; border:1px solid #0c0800; font-size:22px;';
}
</script>
</head>
<body>
<center>
<div id="error"></div>
<center>
<div id="result"><h2> Javascript Example On click Change Css style</h2></div>
<button onclick="change_css();">Check</button><br />
</center>
</center>
</body>
To switch the display-style between block
and none
you can do something like this:
function toggleDiv(id) {
var div = document.getElementById(id);
div.style.display = div.style.display == "none" ? "block" : "none";
}
working demo: http://jsfiddle.net/BQUyT/2/
If you would like to handle multiple inputs with one handler take a look at my approach where I'm using computed property
to get value of the input based on it's name.
import React, { useState } from "react";
import "./style.css";
export default function App() {
const [state, setState] = useState({
name: "John Doe",
email: "[email protected]"
});
const handleChange = e => {
setState({
[e.target.name]: e.target.value
});
};
return (
<div>
<input
type="text"
className="name"
name="name"
value={state.name}
onChange={handleChange}
/>
<input
type="text"
className="email"
name="email"
value={state.email}
onChange={handleChange}
/>
</div>
);
}
After updating to Android 3.4, I started to get the error, tried all the above solutions.
Root cause of the problem was, updating Android Studio enabled the Instant Run.
Hence, one of the solutions you can try is Disabling Instant Run, if its enabled for you, fixed my problem.
rev4: A very eloquent comment by user Sammaron has noted that, perhaps, this answer previously confused top-down and bottom-up. While originally this answer (rev3) and other answers said that "bottom-up is memoization" ("assume the subproblems"), it may be the inverse (that is, "top-down" may be "assume the subproblems" and "bottom-up" may be "compose the subproblems"). Previously, I have read on memoization being a different kind of dynamic programming as opposed to a subtype of dynamic programming. I was quoting that viewpoint despite not subscribing to it. I have rewritten this answer to be agnostic of the terminology until proper references can be found in the literature. I have also converted this answer to a community wiki. Please prefer academic sources. List of references: {Web: 1,2} {Literature: 5}
Dynamic programming is all about ordering your computations in a way that avoids recalculating duplicate work. You have a main problem (the root of your tree of subproblems), and subproblems (subtrees). The subproblems typically repeat and overlap.
For example, consider your favorite example of Fibonnaci. This is the full tree of subproblems, if we did a naive recursive call:
TOP of the tree
fib(4)
fib(3)...................... + fib(2)
fib(2)......... + fib(1) fib(1)........... + fib(0)
fib(1) + fib(0) fib(1) fib(1) fib(0)
fib(1) fib(0)
BOTTOM of the tree
(In some other rare problems, this tree could be infinite in some branches, representing non-termination, and thus the bottom of the tree may be infinitely large. Furthermore, in some problems you might not know what the full tree looks like ahead of time. Thus, you might need a strategy/algorithm to decide which subproblems to reveal.)
There are at least two main techniques of dynamic programming which are not mutually exclusive:
Memoization - This is a laissez-faire approach: You assume that you have already computed all subproblems and that you have no idea what the optimal evaluation order is. Typically, you would perform a recursive call (or some iterative equivalent) from the root, and either hope you will get close to the optimal evaluation order, or obtain a proof that you will help you arrive at the optimal evaluation order. You would ensure that the recursive call never recomputes a subproblem because you cache the results, and thus duplicate sub-trees are not recomputed.
fib(100)
, you would just call this, and it would call fib(100)=fib(99)+fib(98)
, which would call fib(99)=fib(98)+fib(97)
, ...etc..., which would call fib(2)=fib(1)+fib(0)=1+0=1
. Then it would finally resolve fib(3)=fib(2)+fib(1)
, but it doesn't need to recalculate fib(2)
, because we cached it.Tabulation - You can also think of dynamic programming as a "table-filling" algorithm (though usually multidimensional, this 'table' may have non-Euclidean geometry in very rare cases*). This is like memoization but more active, and involves one additional step: You must pick, ahead of time, the exact order in which you will do your computations. This should not imply that the order must be static, but that you have much more flexibility than memoization.
fib(2)
,fib(3)
,fib(4)
... caching every value so you can compute the next ones more easily. You can also think of it as filling up a table (another form of caching).(At it's most general, in a "dynamic programming" paradigm, I would say the programmer considers the whole tree, then writes an algorithm that implements a strategy for evaluating subproblems which can optimize whatever properties you want (usually a combination of time-complexity and space-complexity). Your strategy must start somewhere, with some particular subproblem, and perhaps may adapt itself based on the results of those evaluations. In the general sense of "dynamic programming", you might try to cache these subproblems, and more generally, try avoid revisiting subproblems with a subtle distinction perhaps being the case of graphs in various data structures. Very often, these data structures are at their core like arrays or tables. Solutions to subproblems can be thrown away if we don't need them anymore.)
[Previously, this answer made a statement about the top-down vs bottom-up terminology; there are clearly two main approaches called Memoization and Tabulation that may be in bijection with those terms (though not entirely). The general term most people use is still "Dynamic Programming" and some people say "Memoization" to refer to that particular subtype of "Dynamic Programming." This answer declines to say which is top-down and bottom-up until the community can find proper references in academic papers. Ultimately, it is important to understand the distinction rather than the terminology.]
Memoization is very easy to code (you can generally* write a "memoizer" annotation or wrapper function that automatically does it for you), and should be your first line of approach. The downside of tabulation is that you have to come up with an ordering.
*(this is actually only easy if you are writing the function yourself, and/or coding in an impure/non-functional programming language... for example if someone already wrote a precompiled fib
function, it necessarily makes recursive calls to itself, and you can't magically memoize the function without ensuring those recursive calls call your new memoized function (and not the original unmemoized function))
Note that both top-down and bottom-up can be implemented with recursion or iterative table-filling, though it may not be natural.
With memoization, if the tree is very deep (e.g. fib(10^6)
), you will run out of stack space, because each delayed computation must be put on the stack, and you will have 10^6 of them.
Either approach may not be time-optimal if the order you happen (or try to) visit subproblems is not optimal, specifically if there is more than one way to calculate a subproblem (normally caching would resolve this, but it's theoretically possible that caching might not in some exotic cases). Memoization will usually add on your time-complexity to your space-complexity (e.g. with tabulation you have more liberty to throw away calculations, like using tabulation with Fib lets you use O(1) space, but memoization with Fib uses O(N) stack space).
If you are also doing a extremely complicated problems, you might have no choice but to do tabulation (or at least take a more active role in steering the memoization where you want it to go). Also if you are in a situation where optimization is absolutely critical and you must optimize, tabulation will allow you to do optimizations which memoization would not otherwise let you do in a sane way. In my humble opinion, in normal software engineering, neither of these two cases ever come up, so I would just use memoization ("a function which caches its answers") unless something (such as stack space) makes tabulation necessary... though technically to avoid a stack blowout you can 1) increase the stack size limit in languages which allow it, or 2) eat a constant factor of extra work to virtualize your stack (ick), or 3) program in continuation-passing style, which in effect also virtualizes your stack (not sure the complexity of this, but basically you will effectively take the deferred call chain from the stack of size N and de-facto stick it in N successively nested thunk functions... though in some languages without tail-call optimization you may have to trampoline things to avoid a stack blowout).
Here we list examples of particular interest, that are not just general DP problems, but interestingly distinguish memoization and tabulation. For example, one formulation might be much easier than the other, or there may be an optimization which basically requires tabulation:
Put the loops in a subroutine and call return
As you can see from the error message the paths, that you specified, are wrong. Try it like this:
activate ..\..\temp\venv\test
However, when I needed to install Anaconda, I downloaded it from here and installed it to the default paths (C:\Anaconda
), than I put this path to the environment variables, so now Anacondas interpreter is used as default. If you are using PyCharm, for example, you can specify the interpreter there directly.
Starting simple, with no HTML:
foreach($database as $file) {
echo $file['filename'] . ' at ' . $file['filepath'];
}
And you can otherwise manipulate the fields in the foreach.
String[] token=s.split("[.-]");
There actually IS a way to do it in Python 2.3+, but it's a bit esoteric. I don't know if you realize this, but you can do the following:
$ unzip -l /tmp/example.zip
Archive: /tmp/example.zip
Length Date Time Name
-------- ---- ---- ----
8467 11-26-02 22:30 jwzthreading.py
-------- -------
8467 1 file
$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32)
>>> import sys
>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__
'/tmp/example.zip/jwzthreading.py'
According to the zipimport library:
Any files may be present in the ZIP archive, but only files .py and .py[co] are available for import. ZIP import of dynamic modules (.pyd, .so) is disallowed. Note that if an archive only contains .py files, Python will not attempt to modify the archive by adding the corresponding .pyc or .pyo file, meaning that if a ZIP archive doesn't contain .pyc files, importing may be rather slow.
Thus, all you have to do is zip the files up, add the zipfile to your sys.path and then import them.
If you're building this for UNIX, you might also consider packaging your script using this recipe: unix zip executable, but note that you might have to tweak this if you plan on using stdin or reading anything from sys.args (it CAN be done without too much trouble).
In my experience performance doesn't suffer too much because of this, but you should think twice before importing any very large modules this way.
Just implement an Interface given by PHP JsonSerializable.
CA's don't ask for your private keys! They only asks for CSR to issue a certificate for you.
If they have your private key, it's possible that your SSL certificate will be compromised and end up being revoked.
Your .key
file is generated during CSR generation and, most probably, it's somewhere on your PC where you generated the CSR.
That's why private key is called "Private" - because nobody can have that file except you.
This solution will only work if you have tree
installed on your system. However I'm leaving this solution here just in case it helps someone else out.
You can tell tree to output the tree structure as XML (tree -X
) or JSON (tree -J
). JSON of course can be parsed directly with python and XML can easily be read with lxml
.
With the following directory structure as an example:
[sri@localhost Projects]$ tree --charset=ascii bands
bands
|-- DreamTroll
| |-- MattBaldwinson
| |-- members.txt
| |-- PaulCarter
| |-- SimonBlakelock
| `-- Rob Stringer
|-- KingsX
| |-- DougPinnick
| |-- JerryGaskill
| |-- members.txt
| `-- TyTabor
|-- Megadeth
| |-- DaveMustaine
| |-- DavidEllefson
| |-- DirkVerbeuren
| |-- KikoLoureiro
| `-- members.txt
|-- Nightwish
| |-- EmppuVuorinen
| |-- FloorJansen
| |-- JukkaNevalainen
| |-- MarcoHietala
| |-- members.txt
| |-- TroyDonockley
| `-- TuomasHolopainen
`-- Rush
|-- AlexLifeson
|-- GeddyLee
`-- NeilPeart
5 directories, 25 files
XML
<?xml version="1.0" encoding="UTF-8"?>
<tree>
<directory name="bands">
<directory name="DreamTroll">
<file name="MattBaldwinson"></file>
<file name="members.txt"></file>
<file name="PaulCarter"></file>
<file name="RobStringer"></file>
<file name="SimonBlakelock"></file>
</directory>
<directory name="KingsX">
<file name="DougPinnick"></file>
<file name="JerryGaskill"></file>
<file name="members.txt"></file>
<file name="TyTabor"></file>
</directory>
<directory name="Megadeth">
<file name="DaveMustaine"></file>
<file name="DavidEllefson"></file>
<file name="DirkVerbeuren"></file>
<file name="KikoLoureiro"></file>
<file name="members.txt"></file>
</directory>
<directory name="Nightwish">
<file name="EmppuVuorinen"></file>
<file name="FloorJansen"></file>
<file name="JukkaNevalainen"></file>
<file name="MarcoHietala"></file>
<file name="members.txt"></file>
<file name="TroyDonockley"></file>
<file name="TuomasHolopainen"></file>
</directory>
<directory name="Rush">
<file name="AlexLifeson"></file>
<file name="GeddyLee"></file>
<file name="NeilPeart"></file>
</directory>
</directory>
<report>
<directories>5</directories>
<files>25</files>
</report>
</tree>
JSON
[sri@localhost Projects]$ tree -J bands
[
{"type":"directory","name":"bands","contents":[
{"type":"directory","name":"DreamTroll","contents":[
{"type":"file","name":"MattBaldwinson"},
{"type":"file","name":"members.txt"},
{"type":"file","name":"PaulCarter"},
{"type":"file","name":"RobStringer"},
{"type":"file","name":"SimonBlakelock"}
]},
{"type":"directory","name":"KingsX","contents":[
{"type":"file","name":"DougPinnick"},
{"type":"file","name":"JerryGaskill"},
{"type":"file","name":"members.txt"},
{"type":"file","name":"TyTabor"}
]},
{"type":"directory","name":"Megadeth","contents":[
{"type":"file","name":"DaveMustaine"},
{"type":"file","name":"DavidEllefson"},
{"type":"file","name":"DirkVerbeuren"},
{"type":"file","name":"KikoLoureiro"},
{"type":"file","name":"members.txt"}
]},
{"type":"directory","name":"Nightwish","contents":[
{"type":"file","name":"EmppuVuorinen"},
{"type":"file","name":"FloorJansen"},
{"type":"file","name":"JukkaNevalainen"},
{"type":"file","name":"MarcoHietala"},
{"type":"file","name":"members.txt"},
{"type":"file","name":"TroyDonockley"},
{"type":"file","name":"TuomasHolopainen"}
]},
{"type":"directory","name":"Rush","contents":[
{"type":"file","name":"AlexLifeson"},
{"type":"file","name":"GeddyLee"},
{"type":"file","name":"NeilPeart"}
]}
]},
{"type":"report","directories":5,"files":25}
]
I can't answer the why part.
But if you want something dynamic then why don't you consider Collection ArrayList.
ArrrayList can be of any Object type.
And if as an compulsion you want it as an array you can use the toArray() method on it.
For example:
ArrayList<String> al = new ArrayList<String>();
al.add("one");
al.add("two");
String[] strArray = (String[]) al.toArray(new String[0]);
I hope this might help you.
I just solved this exact issue for myself; even referenced this question.
I'm assuming you haven't written the "all" rule that Eclipse is complaining about. If this is the case, take these steps:
This lets Eclipse know you aren't trying to use a make target called "all". For some reason, that is the default.
fun fact: height-100% works in the latest chrome; but not in safari;
so solution in tailwind would be
https://tailwindcss.com/docs/align-items
and be applied recursively to the child's child's child ...
I had this question twice, and it was always caused by the corruption of the git cache file at my local branch. I fixed it by writing the missing commit hash into that file. I got the right commit hash from the server and ran the following command locally:
cat .git/refs/remotes/origin/feature/mybranch \
echo 1edf9668426de67ab764af138a98342787dc87fe \
>> .git/refs/remotes/origin/feature/mybranch
Your class MyClass
creates a new MyClassToBeTested
, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.
I guess you made it final
because you want to prevent other classes from extending RainOnTrees
. As Effective Java suggests (item 15), there's another way to keep a class close for extension without making it final
:
Remove the final
keyword;
Make its constructor private
. No class will be able to extend it because it won't be able to call the super
constructor;
Create a static factory method to instantiate your class.
// No more final keyword here.
public class RainOnTrees {
public static RainOnTrees newInstance() {
return new RainOnTrees();
}
private RainOnTrees() {
// Private constructor.
}
public void startRain() {
// some code here
}
}
By using this strategy, you'll be able to use Mockito and keep your class closed for extension with little boilerplate code.
Change the .env file as follow
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
And the go to the gmail security section ->Allow Less secure app access
Then run
php artisan config:clear
Refresh the site
To view git configuration type -
git config --list
To change username globally type -
git config --global user.name "your_name"
To change email globally type -
git config --global user.email "your_email"
dict((el,0) for el in a)
will work well.
Python 2.7 and above also support dict comprehensions. That syntax is {el:0 for el in a}
.
You have to set seed every time you want to get a reproducible random result.
set.seed(1)
rnorm(4)
set.seed(1)
rnorm(4)
Rethink your approach. Why would you copy only part of the sheet? You are referring to a named range "WholePrintArea" which doesn't exist. Also you should never use activate, select, copy or paste in your script. These make the "script" vulnerable to user actions and other simultaneous executions. In worst case scenario data ends up in wrong hands.
Using Docker, you may run this command to get Redis CLI:
docker run -it --rm redis redis-cli -h redis.mycompany.org -p 6379
where redis
is the redis
docker image from Docker Hub,
redis-cli
is pre-installed in that image, and all after that are parameters to redis-cli
:
-h
is hostname to connect to,
-p
is apparently the port to connect to.
You can also capture jquery ready event this way:
$('#iframeid').ready(function () {
//Everything you need.
});
Here is a working example: