Let me add an example here:
I'm trying to build Alluxio
on windows platform and got the same issue, it's because the pom.xml
contains below step:
<plugin>
<artifactId>exec-maven-plugin</artifactId>
<groupId>org.codehaus.mojo</groupId>
<inherited>false</inherited>
<executions>
<execution>
<id>Check that there are no Windows line endings</id>
<phase>compile</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>${build.path}/style/check_no_windows_line_endings.sh</executable>
</configuration>
</execution>
</executions>
</plugin>
The .sh
file is not executable on windows so the error throws.
Comment it out if you do want build Alluxio
on windows.
It's an implicit conversion to bool
. I.e. wherever implicit conversions are allowed, your class can be converted to bool
by calling that method.
The idea of a linear index for arrays in matlab is an important one. An array in MATLAB is really just a vector of elements, strung out in memory. MATLAB allows you to use either a row and column index, or a single linear index. For example,
A = magic(3)
A =
8 1 6
3 5 7
4 9 2
A(2,3)
ans =
7
A(8)
ans =
7
We can see the order the elements are stored in memory by unrolling the array into a vector.
A(:)
ans =
8
3
4
1
5
9
6
7
2
As you can see, the 8th element is the number 7. In fact, the function find returns its results as a linear index.
find(A>6)
ans =
1
6
8
The result is, we can access each element in turn of a general n-d array using a single loop. For example, if we wanted to square the elements of A (yes, I know there are better ways to do this), one might do this:
B = zeros(size(A));
for i = 1:numel(A)
B(i) = A(i).^2;
end
B
B =
64 1 36
9 25 49
16 81 4
There are many circumstances where the linear index is more useful. Conversion between the linear index and two (or higher) dimensional subscripts is accomplished with the sub2ind and ind2sub functions.
The linear index applies in general to any array in matlab. So you can use it on structures, cell arrays, etc. The only problem with the linear index is when they get too large. MATLAB uses a 32 bit integer to store these indexes. So if your array has more then a total of 2^32 elements in it, the linear index will fail. It is really only an issue if you use sparse matrices often, when occasionally this will cause a problem. (Though I don't use a 64 bit MATLAB release, I believe that problem has been resolved for those lucky individuals who do.)
in rare cases when you can't use strncat
, strcat
or strcpy
. And you don't have access to <string.h>
so you can't use strlen
. Also you maybe don't even know the size of the char arrays and you still want to concatenate because you got only pointers. Well, you can do old school malloc and count characters yourself like..
char *combineStrings(char* inputA, char* inputB) {
size_t len = 0, lenB = 0;
while(inputA[len] != '\0') len++;
while(inputB[lenB] != '\0') lenB++;
char* output = malloc(len+lenB);
sprintf((char*)output,"%s%s",inputA,inputB);
return output;
}
It just needs #include <stdio.h>
which you will have most likely included already
I know this is old but I have come across this issue as well but found a fix for this that worked for me:
Go to your MySQL workbench and select "Startup / Shutdown" under "INSTANCE" and you should be good to go. Hope this helps anyone that comes across this.
For a realistic approach that emulates the most human behavior, you may want to add a referer in your curl options. You may also want to add a follow_location to your curl options. Trust me, whoever said that cURLING Google results is impossible, is a complete dolt and should throw his/her computer against the wall in hopes of never returning to the internetz again. Everything that you can do "IRL" with your own browser can all be emulated using PHP cURL or libCURL in Python. You just need to do more cURLS to get buff. Then you will see what I mean. :)
$url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
$ch = curl_init();
curl_setopt($ch, CURLOPT_REFERER, 'http://www.example.com/1');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, urlencode($url));
$response = curl_exec($ch);
curl_close($ch);
Another option:
a = [2,4,6,3,8]
a -= [3]
which results in
=> [2, 4, 6, 8]
$timestamp='2014-11-21 16:38:00';
list($date,$time)=explode(' ',$timestamp);
// just time
preg_match("/ (\d\d:\d\d):\d\d$/",$timestamp,$match);
echo "\n<br>".$match[1];
You could use jQuery to add an event listener on the document DOM.
$(document).on("click", function () {_x000D_
console.log('clicked');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
You can combine the find command and the ls command. Use the path (.) and selector (*) to narrow down the files you're after. Surround the find command in back quotes. The argument to -name is doublequote star doublequote in case you can't read it.
ls -lart `find . -type f -name "*" `
How about something like this?
<html>
<head>
<script type="text/javascript">
var HoverListener = {
addElem: function( elem, callback, delay )
{
if ( delay === undefined )
{
delay = 1000;
}
var hoverTimer;
addEvent( elem, 'mouseover', function()
{
hoverTimer = setTimeout( callback, delay );
} );
addEvent( elem, 'mouseout', function()
{
clearTimeout( hoverTimer );
} );
}
}
function tester()
{
alert( 'hi' );
}
// Generic event abstractor
function addEvent( obj, evt, fn )
{
if ( 'undefined' != typeof obj.addEventListener )
{
obj.addEventListener( evt, fn, false );
}
else if ( 'undefined' != typeof obj.attachEvent )
{
obj.attachEvent( "on" + evt, fn );
}
}
addEvent( window, 'load', function()
{
HoverListener.addElem(
document.getElementById( 'test' )
, tester
);
HoverListener.addElem(
document.getElementById( 'test2' )
, function()
{
alert( 'Hello World!' );
}
, 2300
);
} );
</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>
Providing disabled
property as true inside FormControl surely disables the input field.
this.form=this.fb.group({
FirstName:[{value:'first name', disabled:true}],
LastValue:['last name,[Validators.required]]
})
The above example will disable the FirstName
input field.
But real problem arises when you try to access disabled field value through form like this
console.log(this.form.value.FirstName);
and it shows as undefined
instead of printing field's actual value. So, to access disabled field's value, one must use getRawValue()
method provided by Reactive Forms
. i.e. console.log(this.form.getRawValue().FirstName);
would print the actual value of form field and not undefined.
Have a look at HttpUtility.ParseQueryString() It'll give you a NameValueCollection
instead of a dictionary, but should still do what you need.
The other option is to use string.Split()
.
string url = @"http://example.com/file?a=1&b=2&c=string%20param";
string[] parts = url.Split(new char[] {'?','&'});
///parts[0] now contains http://example.com/file
///parts[1] = "a=1"
///parts[2] = "b=2"
///parts[3] = "c=string%20param"
At the very least, if this were true a compiler could trivially optimise a <= b to !(a > b), and so even if the comparison itself were actually slower, with all but the most naive compiler you would not notice a difference.
// Angular
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
/**
* Sanitize HTML
*/
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
/**
* Pipe Constructor
*
* @param _sanitizer: DomSanitezer
*/
// tslint:disable-next-line
constructor(protected _sanitizer: DomSanitizer) {
}
/**
* Transform
*
* @param value: string
* @param type: string
*/
transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html':
return this._sanitizer.bypassSecurityTrustHtml(value);
case 'style':
return this._sanitizer.bypassSecurityTrustStyle(value);
case 'script':
return this._sanitizer.bypassSecurityTrustScript(value);
case 'url':
return this._sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl':
return this._sanitizer.bypassSecurityTrustResourceUrl(value);
default:
return this._sanitizer.bypassSecurityTrustHtml(value);
}
}
}
{{ data.url | safe:'url' }}
// Public properties
itsSafe: SafeHtml;
// Private properties
private safePipe: SafePipe = new SafePipe(this.domSanitizer);
/**
* Component constructor
*
* @param safePipe: SafeHtml
* @param domSanitizer: DomSanitizer
*/
constructor(private safePipe: SafePipe, private domSanitizer: DomSanitizer) {
}
/**
* On init
*/
ngOnInit(): void {
this.itsSafe = this.safePipe.transform('<h1>Hi</h1>', 'html');
}
The JSON Ruby Gem is bundled with a shell script to prettify JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
Script download: gist.github.com/3738968
Keeping the element's size relative to its content can also be done with display: inline-flex
and display: table
The centering can be done with..
text-align: center;
on the parent (or above, it's inherited)
display: flex;
and justify-content: center;
on the parent
position: absolute;
left: 50%;
transform: translateX(-50%);
on
the element with position: relative; (at least) on the parent.
Here's a flexbox guide from CSS Tricks
Here's an article on centering from CSS Tricks.
Keeping an element only as wide as its content..
Can use display: table;
Or inline-anything including inline-flex
as used in my snippet
example below.
Keep in mind that when centering with flexbox's justify-content: center;
when the text wraps the text will align left. So you will still need text-align: center;
if your site is responsive and you expect lines to wrap.
body {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 100vh;_x000D_
padding: 20px;_x000D_
}_x000D_
.container {_x000D_
display: flex;_x000D_
justify-content: center; /* center horizontally */_x000D_
align-items: center; /* center vertically */_x000D_
height: 50%;_x000D_
}_x000D_
.container.c1 {_x000D_
text-align: center; /* needed if the text wraps */_x000D_
/* text-align is inherited, it can be put on the parent or the target element */_x000D_
}_x000D_
.container.c2 {_x000D_
/* without text-align: center; */_x000D_
}_x000D_
.button {_x000D_
padding: 5px 10px;_x000D_
font-size: 30px;_x000D_
text-decoration: none;_x000D_
color: hsla(0, 0%, 90%, 1);_x000D_
background: linear-gradient(hsla(21, 85%, 51%, 1), hsla(21, 85%, 61%, 1));_x000D_
border-radius: 10px;_x000D_
box-shadow: 2px 2px 15px -5px hsla(0, 0%, 0%, 1);_x000D_
}_x000D_
.button:hover {_x000D_
background: linear-gradient(hsl(207.5, 84.8%, 51%), hsla(207, 84%, 62%, 1));_x000D_
transition: all 0.2s linear;_x000D_
}_x000D_
.button.b1 {_x000D_
display: inline-flex; /* element only as wide as content */_x000D_
}_x000D_
.button.b2 {_x000D_
display: table; /* element only as wide as content */_x000D_
}
_x000D_
<div class="container c1">_x000D_
<a class="button b1" href="https://stackoverflow.com/questions/27722872/">This Text Is Centered Before And After Wrap</a>_x000D_
</div>_x000D_
<div class="container c2">_x000D_
<a class="button b2" href="https://stackoverflow.com/questions/27722872/">This Text Is Centered Only Before Wrap</a>_x000D_
</div>
_x000D_
Fiddle
On the back of James Lee Baker's reply, I prefer this solution as it removes the reliance on browser support for :first :selected ...
$('#target').children().prop('selected', false);
$($('#target').children()[0]).prop('selected', 'selected');
Watch out for pitfalls. If the field Name
in Table1
contain Nulls you are in for surprises.
Better is:
SELECT name
FROM table2
WHERE name NOT IN
(SELECT ISNULL(name ,'')
FROM table1)
Disclaimer: I'm not a MySQL expert ... but this is my understanding of the issues.
I think TEXT is stored outside the mysql row, while I think VARCHAR is stored as part of the row. There is a maximum row length for mysql rows .. so you can limit how much other data you can store in a row by using the VARCHAR.
Also due to VARCHAR forming part of the row, I suspect that queries looking at that field will be slightly faster than those using a TEXT chunk.
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'xxx',
'smtp_pass' => 'xxx',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
// Set to, from, message, etc.
$result = $this->email->send();
From the CodeIgniter Forums
Open .iml file. Look for keyword 'NewModuleRootManager'. Check if attribute 'inherit-compiler-output' is set to true or not. If not set to true.
Like this :
component name="NewModuleRootManager" inherit-compiler-output="true">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/spec" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/app" isTestSource="false" />
Just install Google Repository form your sdk manager and than restart Android Studio.
What is a monkey patch?
Simply put, monkey patching is making changes to a module or class while the program is running.
There's an example of monkey-patching in the Pandas documentation:
import pandas as pd
def just_foo_cols(self):
"""Get a list of column names containing the string 'foo'
"""
return [x for x in self.columns if 'foo' in x]
pd.DataFrame.just_foo_cols = just_foo_cols # monkey-patch the DataFrame class
df = pd.DataFrame([list(range(4))], columns=["A","foo","foozball","bar"])
df.just_foo_cols()
del pd.DataFrame.just_foo_cols # you can also remove the new method
To break this down, first we import our module:
import pandas as pd
Next we create a method definition, which exists unbound and free outside the scope of any class definitions (since the distinction is fairly meaningless between a function and an unbound method, Python 3 does away with the unbound method):
def just_foo_cols(self):
"""Get a list of column names containing the string 'foo'
"""
return [x for x in self.columns if 'foo' in x]
Next we simply attach that method to the class we want to use it on:
pd.DataFrame.just_foo_cols = just_foo_cols # monkey-patch the DataFrame class
And then we can use the method on an instance of the class, and delete the method when we're done:
df = pd.DataFrame([list(range(4))], columns=["A","foo","foozball","bar"])
df.just_foo_cols()
del pd.DataFrame.just_foo_cols # you can also remove the new method
If you're using name-mangling (prefixing attributes with a double-underscore, which alters the name, and which I don't recommend) you'll have to name-mangle manually if you do this. Since I don't recommend name-mangling, I will not demonstrate it here.
How can we use this knowledge, for example, in testing?
Say we need to simulate a data retrieval call to an outside data source that results in an error, because we want to ensure correct behavior in such a case. We can monkey patch the data structure to ensure this behavior. (So using a similar method name as suggested by Daniel Roseman:)
import datasource
def get_data(self):
'''monkey patch datasource.Structure with this to simulate error'''
raise datasource.DataRetrievalError
datasource.Structure.get_data = get_data
And when we test it for behavior that relies on this method raising an error, if correctly implemented, we'll get that behavior in the test results.
Just doing the above will alter the Structure
object for the life of the process, so you'll want to use setups and teardowns in your unittests to avoid doing that, e.g.:
def setUp(self):
# retain a pointer to the actual real method:
self.real_get_data = datasource.Structure.get_data
# monkey patch it:
datasource.Structure.get_data = get_data
def tearDown(self):
# give the real method back to the Structure object:
datasource.Structure.get_data = self.real_get_data
(While the above is fine, it would probably be a better idea to use the mock
library to patch the code. mock
's patch
decorator would be less error prone than doing the above, which would require more lines of code and thus more opportunities to introduce errors. I have yet to review the code in mock
but I imagine it uses monkey-patching in a similar way.)
Taking help from above answer link mentioned in the above answer sets the max value with option
yAxis: { max: 100 },
On similar line min value can be set.So if you want to set min-max value then
yAxis: {
min: 0,
max: 100
},
If you are using HighRoller php library for integration if Highchart graphs then you just need to set the option
$series->yAxis->min=0;
$series->yAxis->max=100;
function Continue({show, onContinue}) {
return(<div className="row continue">
{ show ? <div className="col-11">
<button class="btn btn-primary btn-lg float-right" onClick= {onContinue}>Continue</button>
</div>
: null }
</div>);
}
You can try it:
ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);
Or in one line:
label.setIcon(new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)));
The execution time is much more faster than File and ImageIO.
I recommend you to compare the two solutions in a loop.
If you want to remove all whitespace:
$str = preg_replace('/\s+/', '', $str);
See the 5th example on the preg_replace documentation. (Note I originally copied that here.)
Edit: commenters pointed out, and are correct, that str_replace
is better than preg_replace
if you really just want to remove the space character. The reason to use preg_replace
would be to remove all whitespace (including tabs, etc.).
dangerouslySetInnerHTML
should not be used unless absolutely necessary. According to the docs, "This is mainly for cooperating with DOM string manipulation libraries". When you use it, you're giving up the benefit of React's DOM management.
In your case, it is pretty straightforward to convert to valid JSX syntax; just change class
attributes to className
. Or, as mentioned in the comments above, you can use the ReactBootstrap library which encapsulates Bootstrap elements into React components.
This maybe what you're looking for:
awk 'BEGIN {FS=" ";} {printf "'\''%s'\'' ", $1}'
That is, with '\''
you close the opening '
, then print a literal '
by escaping it and finally open the '
again.
Example to show last 3 digits of account number.
x = '1234567890'
x.replace(x[:7], '')
o/p: '890'
insertion or shell sort!
The DBCC CHECKIDENT
management command is used to reset identity counter. The command syntax is:
DBCC CHECKIDENT (table_name [, { NORESEED | { RESEED [, new_reseed_value ]}}])
[ WITH NO_INFOMSGS ]
Example:
DBCC CHECKIDENT ('[TestTable]', RESEED, 0);
GO
It was not supported in previous versions of the Azure SQL Database but is supported now.
Thanks to Solomon Rutzky the docs for the command are now fixed.
You can use timezone.now()
for created and auto_now
for modified:
from django.utils import timezone
class User(models.Model):
created = models.DateTimeField(default=timezone.now())
modified = models.DateTimeField(auto_now=True)
If you are using a custom primary key instead of the default auto- increment int
, auto_now_add
will lead to a bug.
Here is the code of Django's default DateTimeField.pre_save withauto_now
and auto_now_add
:
def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = timezone.now()
setattr(model_instance, self.attname, value)
return value
else:
return super(DateTimeField, self).pre_save(model_instance, add)
I am not sure what the parameter add
is. I hope it will some thing like:
add = True if getattr(model_instance, 'id') else False
The new record will not have attr
id
, sogetattr(model_instance, 'id')
will return False will lead to not setting any value in the field.
You can use js for prevent scroll:
let body = document.body;
let hideScroll = function(e) {
e.preventDefault();
};
function toggleScroll (bool) {
if (bool === true) {
body.addEventListener("touchmove", hideScroll);
} else {
body.removeEventListener("touchmove", hideScroll);
}
}
And than just run/stop toggleScroll
func when you opnen/close modal.
Like this toggleScroll(true) / toggleScroll(false)
(This is only for iOS, on Android not working)
this helps for me:
on your build.gradle:
implementation 'com.android.support:design:28.0.0'
you can use show
instead of shown
for making the function to load just before modal open, instead of after modal open.
$('#code').on('show.bs.modal', function (e) {
// do something...
})
use buildSrc with Gradle Kotlin DSL see full worked example here: GitHub daggerok/spring-fu-jafu-example buildSrc/src/main/java/Globals.kt
Edit your .classpath file. (Or via the project build path).
I used easyengine to set up my vultr cloud based server.
I found my bash file at /etc/bash.bashrc
.
So source /etc/bash.bashrc
did the trick for me!
update
When setting up a bare server (ubuntu 16.04), you can use the above info, when you have not yet set up a username, and are logging in via root.
It's best to create a user (with sudo privledges), and login as this username instead.
This will create a directory for your settings, including .profile and .bashrc files.
https://linuxize.com/post/how-to-create-a-sudo-user-on-ubuntu/
Now, you will edit and (and "source") the ~/.bashrc
file.
On my server, this was located at /home/your_username/.bashrc
(where your_username
is actually the new username you created above, and now login with)
A way to do this is to rest the servelet context path from request URI.
String p = request.getRequestURI();
String cp = getServletContext().getContextPath();
if (p.startsWith(cp)) {
String.err.println(p.substring(cp.length());
}
Read here .
:unchecked
is not defined in the Selectors or CSS UI level 3 specs, nor has it appeared in level 4 of Selectors.
In fact, the quote from W3C is taken from the Selectors 4 spec. Since Selectors 4 recommends using :not(:checked)
, it's safe to assume that there is no corresponding :unchecked
pseudo. Browser support for :not()
and :checked
is identical, so that shouldn't be a problem.
This may seem inconsistent with the :enabled
and :disabled
states, especially since an element can be neither enabled nor disabled (i.e. the semantics completely do not apply), however there does not appear to be any explanation for this inconsistency.
(:indeterminate
does not count, because an element can similarly be neither unchecked, checked nor indeterminate because the semantics don't apply.)
If you just want the content as string
, then the simple solution is to use the ReadFile
function from the io/ioutil
package. This function returns a slice of bytes
which you can easily convert to a string
.
package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("file.txt") // just pass the file name
if err != nil {
fmt.Print(err)
}
fmt.Println(b) // print the content as 'bytes'
str := string(b) // convert content to a 'string'
fmt.Println(str) // print the content as a 'string'
}
http://www.java2s.com/Code/Java/Data-Type/Obtainingtheintegerandfractionalparts.htm
double num;
long iPart;
double fPart;
// Get user input
num = 2.3d;
iPart = (long) num;
fPart = num - iPart;
System.out.println("Integer part = " + iPart);
System.out.println("Fractional part = " + fPart);
Outputs:
Integer part = 2
Fractional part = 0.2999999999999998
I know this question has been answered, but in case you only want something to trigger when the actual BROWSER is closed, and not just when a pageload occurs, you can use this code:
window.onbeforeunload = function (e) {
if ((window.event.clientY < 0)) {
//window.localStorage.clear();
//alert("Y coords: " + window.event.clientY)
}
};
In my example, I am clearing local storage and alerting the user with the mouses y coords, only when the browser is closed, this will be ignored on all page loads from within the program.
You could try using Linq to project the list:
var output = lst.Select(x => x % 2 == 0).ToList();
This will return a new list of bools such that {1, 2, 3, 4, 5}
will map to {false, true, false, true, false}
.
There is also
which aims
- To encode entire script in a proprietary PHP application
- To encode some classes and/or functions in a proprietary PHP application
- To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe.
- To do the feasibility study for a PHP to C converter
The extension is available from PECL.
Like this:
> df[df==""]<-NA
> df
A B
1 <NA> 12
2 xyz <NA>
3 jkl 100
A user account is like relatives who holds a key to your home, but does not own anything i.e. a user account does not own any database object...no data dictionary...
Whereas a schema is an encapsulation of database objects. It's like the owner of the house who owns everything in your house and a user account will be able to access the goods at the home only when the owner i.e. schema gives needed grants to it.
To open at a specific line straight from the command line, use:
less +320123 filename
If you want to see the line numbers too:
less +320123 -N filename
You can also choose to display a specific line of the file at a specific line of the terminal, for when you need a few lines of context. For example, this will open the file with line 320123 on the 10th line of the terminal:
less +320123 -j 10 filename
Your index.html can just do src="images/logo.png"
and from sub.html you would do src="../images/logo.png"
I reached the point that I set, up to max_iter=1200000
on my LinearSVC
classifier, but still the "ConvergenceWarning" was still present. I fix the issue by just setting dual=False
and leaving max_iter
to its default.
With LogisticRegression(solver='lbfgs')
classifier, you should increase max_iter
. Mine have reached max_iter=7600
before the "ConvergenceWarning" disappears when training with large dataset's features.
Sydius outlined the types fairly well:
How about when you should use them? You will either make heavy use of scoped pointers or shared pointers. How many threads are running in your application? If the answer is "potentially a lot", shared pointers can turn out to be a performance bottleneck if used everywhere. The reason being that creating/copying/destructing a shared pointer needs to be an atomic operation, and this can hinder performance if you have many threads running. However, it won't always be the case - only testing will tell you for sure.
There is an argument (that I like) against shared pointers - by using them, you are allowing programmers to ignore who owns a pointer. This can lead to tricky situations with circular references (Java will detect these, but shared pointers cannot) or general programmer laziness in a large code base.
There are two reasons to use scoped pointers. The first is for simple exception safety and cleanup operations - if you want to guarantee that an object is cleaned up no matter what in the face of exceptions, and you don't want to stack allocate that object, put it in a scoped pointer. If the operation is a success, you can feel free to transfer it over to a shared pointer, but in the meantime save the overhead with a scoped pointer.
The other case is when you want clear object ownership. Some teams prefer this, some do not. For instance, a data structure may return pointers to internal objects. Under a scoped pointer, it would return a raw pointer or reference that should be treated as a weak reference - it is an error to access that pointer after the data structure that owns it is destructed, and it is an error to delete it. Under a shared pointer, the owning object can't destruct the internal data it returned if someone still holds a handle on it - this could leave resources open for much longer than necessary, or much worse depending on the code.
I have created following class
@Configuration
public class ConfigUtility {
@Autowired
private Environment env;
public String getProperty(String pPropertyKey) {
return env.getProperty(pPropertyKey);
}
}
and called as follow to get application.properties value
@Autowired
private ConfigUtility configUtil;
public AppResponse getDetails() {
AppResponse response = new AppResponse();
String email = configUtil.getProperty("emailid");
return response;
}
unit tested, working as expected...
I just wrote my own sleep which called the Win32 Sleep API function.
I found a dirty trick but it works, you could use the hover function to get the value before change!
Take a look at the JSONObject reference:
http://www.json.org/javadoc/org/json/JSONObject.html
Without actually using the object, it looks like using either getNames() or keys() which returns an Iterator is the way to go.
You need to create an object since printInformation()
is non-static. Try:
int main() {
MyClass o;
o.printInformation();
fgetc( stdin );
return(0);
}
WAMP server generally provide addond for different php/mysql versions. However you mentioned you have downloaded latest wamp server. As of now, latest Wamp server v2.5 provide PHP version 5.5.12
So you need to upgrade it manually as follow:
Although not asked, I'd recommend to vagrant/puppet or docker for local development. Check puphpet.com for details. It has slight learning curve but it will give you much better control of different versions of every tool.
You can navigate to your parent root like this
this.router.navigate(['.'], { relativeTo: this.activeRoute.parent });
You will need to inject the current active Route in the constructor
constructor(
private router: Router,
private activeRoute: ActivatedRoute) {
}
Just use simple code
<%
if(condition)
{%>
html code
<% }
else
{
%>
html code
<% } %>
Open the hosts file located at : **C:\windows\system32\drivers\etc**.
Add the following at end of this file :
YourServerIP YourDNS
Example:
198.168.1.1 maps.google.com
Either make your friends download the runtime DLL (@Kay's answer), or compile the app with static linking.
In visual studio, go to Project tab -> properties - > configuration properties -> C/C++ -> Code Generation
on runtime library choose /MTd
for debug mode and /MT
for release mode.
This will cause the compiler to embed the runtime into the app. The executable will be significantly bigger, but it will run without any need of runtime dlls.
In C++, a constructor with only one required parameter is considered an implicit conversion function. It converts the parameter type to the class type. Whether this is a good thing or not depends on the semantics of the constructor.
For example, if you have a string class with constructor String(const char* s)
, that's probably exactly what you want. You can pass a const char*
to a function expecting a String
, and the compiler will automatically construct a temporary String
object for you.
On the other hand, if you have a buffer class whose constructor Buffer(int size)
takes the size of the buffer in bytes, you probably don't want the compiler to quietly turn int
s into Buffer
s. To prevent that, you declare the constructor with the explicit
keyword:
class Buffer { explicit Buffer(int size); ... }
That way,
void useBuffer(Buffer& buf);
useBuffer(4);
becomes a compile-time error. If you want to pass a temporary Buffer
object, you have to do so explicitly:
useBuffer(Buffer(4));
In summary, if your single-parameter constructor converts the parameter into an object of your class, you probably don't want to use the explicit
keyword. But if you have a constructor that simply happens to take a single parameter, you should declare it as explicit
to prevent the compiler from surprising you with unexpected conversions.
You can't. CSS does not support "events". Dare I ask what you need it for? Check out this post here on SO. I can't think of a reason why you would want to hook up an event to a style change. I'm assuming here that the style change is triggered somwhere else by a piece of javascript. Why not add extra logic there?
As others have pointed out, this is very probably a problem with the path of the function file not being in Matlab's 'path'.
One easy way to verify this is to open your function in the Editor and press the F5 key. This would make the Editor try to run the file, and in case the file is not in path, it will prompt you with a message box. Choose Add to Path
in that, and you must be fine to go.
One side note: at the end of the above process, Matlab command window will give an error saying arguments missing: obviously, we didn't provide any arguments when we tried to run from the editor. But from now on you can use the function from the command line giving the correct arguments.
By using the SqlCommand
and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.
Here is an example, taken from one of the articles above:
private static void UpdateDemographics(Int32 customerID,
string demoXml, string connectionString)
{
// Update the demographics for a store, which is stored
// in an xml column.
string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
+ "WHERE CustomerID = @ID;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters["@ID"].Value = customerID;
// Use AddWithValue to assign Demographics.
// SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("@demographics", demoXml);
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
In case you want the difference recursively, I have written a package for python: https://github.com/seperman/deepdiff
Install from PyPi:
pip install deepdiff
Importing
>>> from deepdiff import DeepDiff
>>> from pprint import pprint
>>> from __future__ import print_function # In case running on Python 2
Same object returns empty
>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = t1
>>> print(DeepDiff(t1, t2))
{}
Type of an item has changed
>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:"2", 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{ 'type_changes': { 'root[2]': { 'newtype': <class 'str'>,
'newvalue': '2',
'oldtype': <class 'int'>,
'oldvalue': 2}}}
Value of an item has changed
>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:4, 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}
Item added and/or removed
>>> t1 = {1:1, 2:2, 3:3, 4:4}
>>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff)
{'dic_item_added': ['root[5]', 'root[6]'],
'dic_item_removed': ['root[4]'],
'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}
String difference
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}}
>>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { 'root[2]': {'newvalue': 4, 'oldvalue': 2},
"root[4]['b']": { 'newvalue': 'world!',
'oldvalue': 'world'}}}
String difference 2
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { "root[4]['b']": { 'diff': '--- \n'
'+++ \n'
'@@ -1,5 +1,4 @@\n'
'-world!\n'
'-Goodbye!\n'
'+world\n'
' 1\n'
' 2\n'
' End',
'newvalue': 'world\n1\n2\nEnd',
'oldvalue': 'world!\n'
'Goodbye!\n'
'1\n'
'2\n'
'End'}}}
>>>
>>> print (ddiff['values_changed']["root[4]['b']"]["diff"])
---
+++
@@ -1,5 +1,4 @@
-world!
-Goodbye!
+world
1
2
End
Type change
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n\n\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'type_changes': { "root[4]['b']": { 'newtype': <class 'str'>,
'newvalue': 'world\n\n\nEnd',
'oldtype': <class 'list'>,
'oldvalue': [1, 2, 3]}}}
List difference
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3, 4]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{'iterable_item_removed': {"root[4]['b'][2]": 3, "root[4]['b'][3]": 4}}
List difference 2:
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'iterable_item_added': {"root[4]['b'][3]": 3},
'values_changed': { "root[4]['b'][1]": {'newvalue': 3, 'oldvalue': 2},
"root[4]['b'][2]": {'newvalue': 2, 'oldvalue': 3}}}
List difference ignoring order or duplicates: (with the same dictionaries as above)
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2, ignore_order=True)
>>> print (ddiff)
{}
List that contains dictionary:
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'dic_item_removed': ["root[4]['b'][2][2]"],
'values_changed': {"root[4]['b'][2][1]": {'newvalue': 3, 'oldvalue': 1}}}
Sets:
>>> t1 = {1, 2, 8}
>>> t2 = {1, 2, 3, 5}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (DeepDiff(t1, t2))
{'set_item_added': ['root[3]', 'root[5]'], 'set_item_removed': ['root[8]']}
Named Tuples:
>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> t1 = Point(x=11, y=22)
>>> t2 = Point(x=11, y=23)
>>> pprint (DeepDiff(t1, t2))
{'values_changed': {'root.y': {'newvalue': 23, 'oldvalue': 22}}}
Custom objects:
>>> class ClassA(object):
... a = 1
... def __init__(self, b):
... self.b = b
...
>>> t1 = ClassA(1)
>>> t2 = ClassA(2)
>>>
>>> pprint(DeepDiff(t1, t2))
{'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}
Object attribute added:
>>> t2.c = "new attribute"
>>> pprint(DeepDiff(t1, t2))
{'attribute_added': ['root.c'],
'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}
No, because that would open up the floodgates for phishing. The only part of the URI you can change is the fragment (everything after the #
). You can do so by setting window.location.hash
.
From tom, on http://www.php.net/manual/en/function.uniqid.php
$r = unpack('v*', fread(fopen('/dev/random', 'r'),16));
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
$r[1], $r[2], $r[3], $r[4] & 0x0fff | 0x4000,
$r[5] & 0x3fff | 0x8000, $r[6], $r[7], $r[8])
The purpose of using this is to implement an additional layer of security between the user interface and the database. By using this layer, data can be normalized before being inserted into your data structure. (Capitals are Capitals, no leading or trailing spaces, all dates at properly formed.)
But there are a few nuances to this which you might not be aware of.
First of all, up until now, you've probably written all your queries in something similar to the URL, and you pass the parameters using the URL itself. Using the PDO, all of this is done under the user interface level. User interface hands off the ball to the PDO which carries it down field and plants it into the database for a 7-point TOUCHDOWN.. he gets seven points, because he got it there and did so much more securely than passing information through the URL.
You can also harden your site to SQL injection by using a data-layer. By using this intermediary layer that is the ONLY 'player' who talks to the database itself, I'm sure you can see how this could be much more secure. Interface to datalayer to database, datalayer to database to datalayer to interface.
And:
By implementing best practices while writing your code you will be much happier with the outcome.
Additional sources:
Re: MySQL Functions in the url php dot net/manual/en/ref dot pdo-mysql dot php
Re: three-tier architecture - adding security to your applications https://blog.42.nl/articles/introducing-a-security-layer-in-your-application-architecture/
Re: Object Oriented Design using UML If you really want to learn more about this, this is the best book on the market, Grady Booch was the father of UML http://dl.acm.org/citation.cfm?id=291167&CFID=241218549&CFTOKEN=82813028
Or check with bitmonkey. There's a group there I'm sure you could learn a lot with.
>
>
Here are a variety of ways to do this in base R
including an alternative aggregate
approach. The examples below return means per month, which I think is what you requested. Although, the same approach could be used to return means per person:
Using ave
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
Rate1.mean <- with(my.data, ave(Rate1, Month, FUN = function(x) mean(x, na.rm = TRUE)))
Rate2.mean <- with(my.data, ave(Rate2, Month, FUN = function(x) mean(x, na.rm = TRUE)))
my.data <- data.frame(my.data, Rate1.mean, Rate2.mean)
my.data
Using by
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
by.month <- as.data.frame(do.call("rbind", by(my.data, my.data$Month, FUN = function(x) colMeans(x[,3:4]))))
colnames(by.month) <- c('Rate1.mean', 'Rate2.mean')
by.month <- cbind(Month = rownames(by.month), by.month)
my.data <- merge(my.data, by.month, by = 'Month')
my.data
Using lapply
and split
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
ly.mean <- lapply(split(my.data, my.data$Month), function(x) c(Mean = colMeans(x[,3:4])))
ly.mean <- as.data.frame(do.call("rbind", ly.mean))
ly.mean <- cbind(Month = rownames(ly.mean), ly.mean)
my.data <- merge(my.data, ly.mean, by = 'Month')
my.data
Using sapply
and split
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.data
sy.mean <- t(sapply(split(my.data, my.data$Month), function(x) colMeans(x[,3:4])))
colnames(sy.mean) <- c('Rate1.mean', 'Rate2.mean')
sy.mean <- data.frame(Month = rownames(sy.mean), sy.mean, stringsAsFactors = FALSE)
my.data <- merge(my.data, sy.mean, by = 'Month')
my.data
Using aggregate
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.summary <- with(my.data, aggregate(list(Rate1, Rate2), by = list(Month),
FUN = function(x) { mon.mean = mean(x, na.rm = TRUE) } ))
my.summary <- do.call(data.frame, my.summary)
colnames(my.summary) <- c('Month', 'Rate1.mean', 'Rate2.mean')
my.summary
my.data <- merge(my.data, my.summary, by = 'Month')
my.data
EDIT: June 28, 2020
Here I use aggregate
to obtain the column means
of an entire matrix
by group where group is defined in an external vector
:
my.group <- c(1,2,1,2,2,3,1,2,3,3)
my.data <- matrix(c( 1, 2, 3, 4, 5,
10, 20, 30, 40, 50,
2, 4, 6, 8, 10,
20, 30, 40, 50, 60,
20, 18, 16, 14, 12,
1000, 1100, 1200, 1300, 1400,
2, 3, 4, 3, 2,
50, 40, 30, 20, 10,
1001, 2001, 3001, 4001, 5001,
1000, 2000, 3000, 4000, 5000), nrow = 10, ncol = 5, byrow = TRUE)
my.data
my.summary <- aggregate(list(my.data), by = list(my.group), FUN = function(x) { my.mean = mean(x, na.rm = TRUE) } )
my.summary
# Group.1 X1 X2 X3 X4 X5
#1 1 1.666667 3.000 4.333333 5.000 5.666667
#2 2 25.000000 27.000 29.000000 31.000 33.000000
#3 3 1000.333333 1700.333 2400.333333 3100.333 3800.333333
InputStream raw = context.getAssets().open("filename.ext");
Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}
I simplified the test a bit - if all(x%y
instead of if not any(not x%y
I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.
pairs = {(x, x+2) for x in primes if x+2 in primes}
Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.
One of the advantages of map, filter and reduce is how legible they become when you "chain" them together to do something complex. However, the built-in syntax isn't legible and is all "backwards". So, I suggest using the PyFunctional
package (https://pypi.org/project/PyFunctional/).
Here's a comparison of the two:
flight_destinations_dict = {'NY': {'London', 'Rome'}, 'Berlin': {'NY'}}
PyFunctional version
Very legible syntax. You can say:
"I have a sequence of flight destinations. Out of which I want to get the dict key if city is in the dict values. Finally, filter out the empty lists I created in the process."
from functional import seq # PyFunctional package to allow easier syntax
def find_return_flights_PYFUNCTIONAL_SYNTAX(city, flight_destinations_dict):
return seq(flight_destinations_dict.items()) \
.map(lambda x: x[0] if city in x[1] else []) \
.filter(lambda x: x != []) \
Default Python version
It's all backwards. You need to say:
"OK, so, there's a list. I want to filter empty lists out of it. Why? Because I first got the dict key if the city was in the dict values. Oh, the list I'm doing this to is flight_destinations_dict."
def find_return_flights_DEFAULT_SYNTAX(city, flight_destinations_dict):
return list(
filter(lambda x: x != [],
map(lambda x: x[0] if city in x[1] else [], flight_destinations_dict.items())
)
)
t = datetime.strptime('Jul 9, 2009 @ 20:02:58 UTC',"%b %d, %Y @ %H:%M:%S %Z")
The same applies to stdout:
print 'spam'
sys.stdout.write('spam\n')
As stated in the other answers, print offers a pretty interface that is often more convenient (e.g. for printing debug information), while write is faster and can also be more convenient when you have to format the output exactly in certain way. I would consider maintainability as well:
You may later decide to switch between stdout/stderr and a regular file.
print() syntax has changed in Python 3, so if you need to support both versions, write() might be better.
We are following the below steps in our project for debugging a website on mobile.
You should introduce a cast inside the click
event handler
MouseEventArgs me = (MouseEventArgs) e;
LocalDate // Represent a date-only, without time-of-day and without time zone.
.now() // Better to pass a `ZoneId` optional argument to `now` as shown below than rely implicitly on the JVM’s current default time zone.
.getDayOfMonth() // Interrogate for the day of the month (1-31).
The modern approach is the LocalDate
class to represent a date-only value.
A time zone is crucial in determine the current date. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate ld = LocalDate.now( z ) ;
int dayOfMonth = ld.getDayOfMonth();
You can also get the day-of-week.
DayOfWeek dow = ld.getDayOfWeek();
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
UPDATE: The Joda-Time project is now in maintenance mode, and advises migration to the java.time classes. This section left intact for history.
Using the Joda-Time 2.5 library rather than the notoriously troublesome java.util.Date and .Calendar classes.
Time zone is crucial to determining a date. Better to specify the zone rather than rely implicitly on the JVM’s current default time zone being assigned.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone ).withTimeAtStartOfDay();
int dayOfMonth = now.getDayOfMonth();
Or use similar code with the LocalDate
class that has no time-of-day portion.
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
I also recommend to use SerializationUtils tool. I want to make a ajust on a wrong comment by @Abilash. The SerializationUtils.serialize()
method is not restricted to 1024 bytes, contrary to another answer here.
public static byte[] serialize(Object object) {
if (object == null) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
oos.flush();
}
catch (IOException ex) {
throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
}
return baos.toByteArray();
}
At first sight, you may think that new ByteArrayOutputStream(1024)
will only allow a fixed size. But if you take a close look at the ByteArrayOutputStream
, you will figure out the the stream will grow if necessary:
This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using
toByteArray()
andtoString()
.
You need to alias the subquery. Thus, your statement should be:
Select Z.id
From (
Select id, time
From dbo.tablea
Union All
Select id, time
From dbo.tableb
) As Z
Group By Z.id
I am adding this answer for others who are still seeking a solution to this problem if you don't want to upload your app on playstore then temporarily there is a workaround for this problem.
Google is providing safety device verification api which you need to call only once in your application and after that your application will not be blocked by play protect:
Here are there the links:
https://developer.android.com/training/safetynet/attestation#verify-attestation-response
Link for sample code project:
Just do a simple .keys()
>>> dct = {
... "1": "a",
... "3": "b",
... "8": {
... "12": "c",
... "25": "d"
... }
... }
>>>
>>> dct.keys()
['1', '8', '3']
>>> for key in dct.keys(): print key
...
1
8
3
>>>
If you need a sorted list:
keylist = dct.keys()
keylist.sort()
for(n in 1:5) {
if(n==3) next # skip 3rd iteration and go to next iteration
cat(n)
}
In my case the problem occurred since I wanted to use a SDK that doesnt include the required library. When I increased the min. SDK level the problem dissappeared. Of course directly including the library's itself, should remove the error as well.
(I just got this working, with my main issue being that I don't have a real internet hostname, so answering this question in case it helps someone)
You need to specify a hostname with HELO. Even so, you should get an error, so Postfix is probably not running.
Also, the => is not a command. The '.' on a single line without any text around it is what tells Postfix that the entry is complete. Here are the entries I used:
telnet localhost 25
(says connected)
EHLO howdy.com
(returns a bunch of 250 codes)
MAIL FROM: [email protected]
RCPT TO: (use a real email address you want to send to)
DATA (type whatever you want on muliple lines)
. (this on a single line tells Postfix that the DATA is complete)
You should get a response like:
250 2.0.0 Ok: queued as 6E414C4643A
The email will probably end up in a junk folder. If it is not showing up, then you probably need to setup the 'Postfix on hosts without a real Internet hostname'. Here is the breakdown on how I completed that step on my Ubuntu box:
sudo vim /etc/postfix/main.cf
smtp_generic_maps = hash:/etc/postfix/generic (add this line somewhere)
(edit or create the file 'generic' if it doesn't exist)
sudo vim /etc/postfix/generic
(add these lines, I don't think it matters what names you use, at least to test)
[email protected] [email protected]
[email protected] [email protected]
@localdomain.local [email protected]
then run:
postmap /etc/postfix/generic (this needs to be run whenever you change the
generic file)
Happy Trails
If you add file ipython_config.py into the ~/.ipython/profile_default directory with lines like below, then the autoreload functionality will be loaded on IPython startup (tested on 2.0.0):
print "--------->>>>>>>> ENABLE AUTORELOAD <<<<<<<<<------------"
c = get_config()
c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
In some cases when using numpy arrays, using random.shuffle
created duplicate data in the array.
An alternative is to use numpy.random.shuffle
. If you're working with numpy already, this is the preferred method over the generic random.shuffle
.
Example
>>> import numpy as np
>>> import random
Using random.shuffle
:
>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> random.shuffle(foo)
>>> foo
array([[1, 2, 3],
[1, 2, 3],
[4, 5, 6]])
Using numpy.random.shuffle
:
>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.random.shuffle(foo)
>>> foo
array([[1, 2, 3],
[7, 8, 9],
[4, 5, 6]])
Open Notepad++ and Settings -> Preferences -> Auto-Completion -> Check the Auto-insert options you want. this link will help alot: http://docs.notepad-plus-plus.org/index.php/Auto_Completion
I run into the same error with you when i run the jconsole command at remote. I want to modify a parameter at jconsole that run on a remote Linux host, i can login the host use the secureCRT, the terminal throw this error information. Fortunately, when use the Putty, it's ok. Weird....
AssemblyInformationalVersion
and AssemblyFileVersion
are displayed when you view the "Version" information on a file through Windows Explorer by viewing the file properties. These attributes actually get compiled in to a VERSION_INFO
resource that is created by the compiler.
AssemblyInformationalVersion
is the "Product version" value. AssemblyFileVersion
is the "File version" value.
The AssemblyVersion
is specific to .NET assemblies and is used by the .NET assembly loader to know which version of an assembly to load/bind at runtime.
Out of these, the only one that is absolutely required by .NET is the AssemblyVersion
attribute. Unfortunately it can also cause the most problems when it changes indiscriminately, especially if you are strong naming your assemblies.
Just make a rule for each case:
<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1) }">
Or use the ternary operator:
<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'">
On my install, FontProperties only changes the text size, but it's still too large and spaced out. I found a parameter in pyplot.rcParams
: legend.labelspacing
, which I'm guessing is set to a fraction of the font size. I've changed it with
pyplot.rcParams.update({'legend.labelspacing':0.25})
I'm not sure how to specify it to the pyplot.legend function - passing
prop={'labelspacing':0.25}
or
prop={'legend.labelspacing':0.25}
comes back with an error.
Be aware that some browser extensions can add code to the pages. In my case I had an "Emmet in all textareas" plugin that messed up with my requireJs. Make sure that no extra code is beign added to your document by inspecting it in the browser.
To duplicate a table and its structure without data from a different a database use this. On the new database sql type
CREATE TABLE currentdatabase.tablename LIKE olddatabase.tablename
solve using this code:
npm install npm@latest -g
The only thing that worked for me was the accepted answer of
$profile = '<p>???????????????????????9</p>';
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $profile);
echo $dom->saveHTML();
HOWEVER
This brought about new issues, of having <?xml encoding="utf-8" ?>
in the output of the document.
The solution for me was then to do
foreach ($doc->childNodes as $xx) {
if ($xx instanceof \DOMProcessingInstruction) {
$xx->parentNode->removeChild($xx);
}
}
Some solutions told me that to remove the xml
header, that I had to perform
$dom->saveXML($dom->documentElement);
This didn't work for me as for a partial document (e.g. a doc with two <p>
tags), only one of the <p>
tags where being returned.
The answer is:
gcc --version
Rather than searching on forums, for any possible option you can always type:
gcc --help
haha! :)
none of the above worked for me,
after a few hours debugging I found out that the problem is in createImageFile()
, specifically absolute path
vs relative path
I assume that you guys are using the official Android guide for taking photo. https://developer.android.com/training/camera/photobasics
private static File createImageFile(Context context) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
Take note of the storageDir
, this is the location where the file will be created. So in order to get the absolute path of this file, I simply use image.getAbsolutePath()
, this path will be used in onActivityResult
if you need the Bitmap image after taking photo
below is the file_path.xml
, simply use .
so that it uses the absolute path
<paths>
<external-path
name="my_images"
path="." />
</paths>
and if you need the bitmap after taking photo
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeFile(mCurrentPhotoPath);
} catch (Exception e) {
e.printStackTrace();
}
}
Making any Swift class subclass of NSObject makes sense also I prefer for using any Swift class to be seen in Objective-C classes like:
@objc(MySwiftClass)
@objcMembers class MySwiftClass {...}
Insert an XML comment. ;-)
/// <summary>
/// Describe your member here.
/// </summary>
public string Something
{
get;
set;
}
This may appear like a joke at the first glance, but it may actually be useful. For me it turned out to be helpful to think about what methods do even for private methods (unless really trivial, of course).
The built-in webserver is hardwired to use Default.aspx as the default page.
The project must have atleast an empty Default.aspx
file to overcome the Directory Listing problem for Global.asax
.
:)
Once you add that empty file all requests can be handled in one location.
public class Global : System.Web.HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
this.Response.Write("hi@ " + this.Request.Path + "?" + this.Request.QueryString);
this.Response.StatusCode = 200;
this.Response.ContentType = "text/plain";
this.Response.End();
}
}
While this is slightly off-topic, since people will find this by searching for "percentage sign in Python" (as I did), I wanted to note that the % sign is also used to prefix a "magic" function in iPython: https://ipython.org/ipython-doc/3/interactive/tutorial.html#magic-functions
In file - \vendor\autoload.php, define your gobals variable as follows, should be in the topmost line.
$global_variable = "Some value";//the global variable
Access that global variable anywhere as :-
$GLOBALS['global_variable'];
Enjoy :)
You just need to add in map options:
scrollwheel: false
When working on a supercomputer, I received this error when I ran:
module load python/3.4.0
screen
python
To resolve the error, I simply needed to reload the module in the screen terminal:
module load python/3.4.0
python
I tried most commands above on VS Code terminal and I got errors like:
fatal: pathspec '[dir]/[file]' did not match any files
I opened the project on GitHub Desktop and ignored from there and it worked.
change_column :things, :price_1, :integer, default: 123, null: false
Seems to be best way to add a default to an existing column that doesn't have null: false
already.
Otherwise:
change_column :things, :price_1, :integer, default: 123
Some research I did on this:
https://gist.github.com/Dorian/417b9a0e1a4e09a558c39345d50c8c3b
In Java create the pattern with Pattern p = Pattern.compile("^\\w{14}$");
for further information see the javadoc
One more reason, maybe your url include some hiden characters, such as '\n'.
If you define your url like below, this exception will raise:
url = '''
http://google.com
'''
because there are '\n' hide in the string. The url in fact become:
\nhttp://google.com\n
As a side note, consider passing strings in setWord() as const references to avoid excess copying. Also, in displayWord, consider making this a const function to follow const-correctness.
void setWord(const std::string& word) {
theWord = word;
}
Just change the first line as follows :
include ActionView::Helpers
that will make it works.
UPDATE: For Rails 3 use:
ActionController::Base.helpers.sanitize(str)
Credit goes to lornc's answer
In java we can do following operation:
String pattern="[\\s]";
String replace="";
part="name=john age=13 year=2001";
Pattern p=Pattern.compile(pattern);
Matcher m=p.matcher(part);
part=m.replaceAll(replace);
System.out.println(part);
for this you need to import following packages to your program:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
i hope it will help you.
Random Samples and Permutations ina dataframe If it is in matrix form convert into data.frame use the sample function from the base package indexes = sample(1:nrow(df1), size=1*nrow(df1)) Random Samples and Permutations
Here's how to do it in Prototype: $(id).update(data)
And jQuery: $('#id').replaceWith(data)
But document.getElementById(id).innerHTML=data
should work too.
EDIT: Prototype and jQuery automatically evaluate scripts for you.
There is one more solution to set column Full text to true.
These solution for example didn't work for me
ALTER TABLE news ADD FULLTEXT(headline, story);
My solution.
NEXT STEPS
Refresh
Version of mssql 2014
This issue is occurring because of the java version. I was using 1.8.0.231 JDK and getting this error. I have degraded my java version from 1.8.0.231 to 1.8.0.171, Now It is working fine.
I use spring 3.2.3 and here is how I solved similar problem.
1) Added RedirectAttributes redirectAttributes to the method parameter list in controller 1.
public String controlMapping1(
@ModelAttribute("mapping1Form") final Object mapping1FormObject,
final BindingResult mapping1BindingResult,
final Model model,
final RedirectAttributes redirectAttributes)
2) Inside the method added code to add flash attribute to redirectAttributes redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);
3) Then, in the second contoller use method parameter annotated with @ModelAttribute to access redirect Attributes
@ModelAttribute("mapping1Form") final Object mapping1FormObject
Here is the sample code from Controller 1:
@RequestMapping(value = { "/mapping1" }, method = RequestMethod.POST)
public String controlMapping1(
@ModelAttribute("mapping1Form") final Object mapping1FormObject,
final BindingResult mapping1BindingResult,
final Model model,
final RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);
return "redirect:mapping2";
}
From Contoller 2:
@RequestMapping(value = "/mapping2", method = RequestMethod.GET)
public String controlMapping2(
@ModelAttribute("mapping1Form") final Object mapping1FormObject,
final BindingResult mapping1BindingResult,
final Model model) {
model.addAttribute("transformationForm", mapping1FormObject);
return "new/view";
}
Laravel raw sql – Insert query:
lets create a get link to insert data which is accessible through url . so our link name is ‘insertintodb’ and inside that function we use db class . db class helps us to interact with database . we us db class static function insert . Inside insert function we will write our PDO query to insert data in database . in below query we will insert ‘ my title ‘ and ‘my content’ as data in posts table .
put below code in your web.php file inside routes directory :
Route::get('/insertintodb',function(){
DB::insert('insert into posts(title,content) values (?,?)',['my title','my content']);
});
Now fire above insert query from browser link below :
localhost/yourprojectname/insertintodb
You can see output of above insert query by going into your database table .you will find a record with id 1 .
Laravel raw sql – Read query :
Now , lets create a get link to read data , which is accessible through url . so our link name is ‘readfromdb’. we us db class static function read . Inside read function we will write our PDO query to read data from database . in below query we will read data of id ‘1’ from posts table .
put below code in your web.php file inside routes directory :
Route::get('/readfromdb',function() {
$result = DB::select('select * from posts where id = ?', [1]);
var_dump($result);
});
now fire above read query from browser link below :
localhost/yourprojectname/readfromdb
If you are asking for T-SQL then lets look at fundamentals first. There are three types of joins here each with its own set of logical processing phases as:
cross join
is simplest of all. It implements only one logical query processing phase, a Cartesian Product
. This phase operates on the two tables provided as inputs to the join and produces a Cartesian product of the two. That is, each row from one input is matched with all rows from the other. So if you have m rows in one table and n rows in the other, you get m×n rows in the result.Inner joins
: They apply two logical query processing phases: A Cartesian product
between the two input tables as in a cross join, and then it filters
rows based on a predicate that you specify in ON
clause (also known as Join condition
).Next comes the third type of joins, Outer Joins
:
In an outer join
, you mark a table as a preserved
table by using the keywords LEFT OUTER JOIN
, RIGHT OUTER JOIN
, or FULL OUTER JOIN
between the table names. The OUTER
keyword is optional
. The LEFT
keyword means that the rows of the left table
are preserved; the RIGHT
keyword means that the rows in the right table
are preserved; and the FULL
keyword means that the rows in both
the left
and right
tables are preserved.
The third logical query processing phase of an outer join
identifies the rows from the preserved table that did not find matches in the other table based on the ON
predicate. This phase adds those rows to the result table produced by the first two phases of the join, and uses NULL
marks as placeholders for the attributes from the nonpreserved side of the join in those outer rows.
Now if we look at the question: To return records from the left table which are not found in the right table use Left outer join
and filter out the rows with NULL
values for the attributes from the right side of the join.
The new hip way is argparse
for these reasons. argparse > optparse > getopt
update: As of py2.7 argparse is part of the standard library and optparse is deprecated.
When linger is on but the timeout is zero the TCP stack doesn't wait for pending data to be sent before closing the connection. Data could be lost due to this but by setting linger this way you're accepting this and asking that the connection be reset straight away rather than closed gracefully. This causes an RST to be sent rather than the usual FIN.
Thanks to EJP for his comment, see here for details.
One more answer:
var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]';_x000D_
_x000D_
obj = Object.keys(j).length;_x000D_
console.log(obj)
_x000D_
Use this...
$('#cat_icon').click(function () {
$('#categories').toggle("slow");
//$('#cat_icon').hide();
});
$('.panel_title').click(function () {
$('#categories').toggle("slow");
//$('#cat_icon').show();
});
See this Example
Greetings.
I needed to be able to sort by multiple things not just one. This answer is based on some of the other answers but it allows for more complex sorting.
static class Extensions
{
public static void Sort<T, TKey>(this ObservableCollection<T> collection, Func<ObservableCollection<T>, TKey> sort)
{
var sorted = (sort.Invoke(collection) as IOrderedEnumerable<T>).ToArray();
for (int i = 0; i < sorted.Count(); i++)
collection.Move(collection.IndexOf(sorted[i]), i);
}
}
When you use it, pass in a series of OrderBy/ThenBy calls. Like this:
Children.Sort(col => col.OrderByDescending(xx => xx.ItemType == "drive")
.ThenByDescending(xx => xx.ItemType == "folder")
.ThenBy(xx => xx.Path));
The easiest way would be to drop the tablespace then build the tablespace back up. But I'd rather not have to do that. This is similar to Henry's except that I just do a copy/paste on the resultset in my gui.
SELECT
'DROP'
,object_type
,object_name
,CASE(object_type)
WHEN 'TABLE' THEN 'CASCADE CONSTRAINTS;'
ELSE ';'
END
FROM user_objects
WHERE
object_type IN ('TABLE','VIEW','PACKAGE','PROCEDURE','FUNCTION','SEQUENCE')
Try This with Capital Letters, Small Letters, Numeric(s) and Special Characters
function generatePassword($_len) {
$_alphaSmall = 'abcdefghijklmnopqrstuvwxyz'; // small letters
$_alphaCaps = strtoupper($_alphaSmall); // CAPITAL LETTERS
$_numerics = '1234567890'; // numerics
$_specialChars = '`~!@#$%^&*()-_=+]}[{;:,<.>/?\'"\|'; // Special Characters
$_container = $_alphaSmall.$_alphaCaps.$_numerics.$_specialChars; // Contains all characters
$password = ''; // will contain the desired pass
for($i = 0; $i < $_len; $i++) { // Loop till the length mentioned
$_rand = rand(0, strlen($_container) - 1); // Get Randomized Length
$password .= substr($_container, $_rand, 1); // returns part of the string [ high tensile strength ;) ]
}
return $password; // Returns the generated Pass
}
Let's Say we need 10 Digit Pass
echo generatePassword(10);
Example Output(s) :
,IZCQ_IV\7
@wlqsfhT(d
1!8+1\4@uD
private void showError() {
mEditText.setError("Password and username didn't match");
}
Which will result in errors shown like this:
And if you want to remove it:
textView.setError(null);
I wrote a blog post that explains how to access an unpublished port of a container In different ways depending on the needs:
The post also goes through a brief introduction of both how port mapping works, the difference between exposing and publishing a port, and what is socat.
Here’s the link: https://lmcaraig.com/accessing-an-unpublished-port-of-a-running-docker-container
jq '.users[]|.first,.last' | paste - -
ILookup Interface is used in .net 3.5 with linq.
The HashTable is the base class that is weakly type; the DictionaryBase abstract class is stronly typed and uses internally a HashTable.
I found a a strange thing about Dictionary, when we add the multiple entries in Dictionary, the order in which the entries are added is maintained. Thus if I apply a foreach on the Dictionary, I will get the records in the same order I have inserted them.
Whereas, this is not true with normal HashTable, as when I add same records in Hashtable the order is not maintained. As far as my knowledge goes, Dictionary is based on Hashtable, if this is true, why my Dictionary maintains the order but HashTable does not?
As to why they behave differently, it's because Generic Dictionary implements a hashtable, but is not based on System.Collections.Hashtable. The Generic Dictionary implementation is based on allocating key-value-pairs from a list. These are then indexed with the hashtable buckets for random access, but when it returns an enumerator, it just walks the list in sequential order - which will be the order of insertion as long as entries are not re-used.
shiv govind Birlasoft.:)
Your question is vague but you could use ShowDialog to display form 2. Then when you close form 2, pass a DialogResult object back to let the user know how the form was closed - if the user clicked the button, then close form 1 as well.
yes stale element error is thrown when (taking your scenario) you have defined locator strategy to click on 'Add Item' first and then when you close the pop up the page gets refreshed hence the reference defined for 'Add Item' is lost in the memory so to overcome this you have to redefine the locator strategy for 'Add Item' again
understand it with a dummy code
// clicking on view details
driver.findElement(By.id("")).click();
// closing the pop up
driver.findElement(By.id("")).click();
// and when you try to click on Add Item
driver.findElement(By.id("")).click();
// you get stale element exception as reference to add item is lost
// so to overcome this you have to re identify the locator strategy for add item
// Please note : this is one of the way to overcome stale element exception
// Step 1 please add a universal wait in your script like below
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); // just after you have initiated browser
There are two easy ways, depending on if you want to deal with exceptions or get a default value.
You can use the First<T>()
or the FirstOrDefault<T>()
extension method to get the first result or default(T)
.
var list = new List<int> { 1, 2, 4 };
var result = list.Where(i => i == 3).First(); // throws InvalidOperationException
var result = list.Where(i => i == 3).FirstOrDefault(); // = 0
image.SetAbsolutePosition(1,1);
You can center a button
without using text-align
on the parent div
by simple using margin:auto; display:block;
For example:
HTML
<div>
<button>Submit</button>
</div>
CSS
button {
margin:auto;
display:block;
}
SEE IT IN ACTION: CodePen
I'm just using a predefined directory on the host to persist data for PostgreSQL. Also, this way it is possible to easily migrate existing PostgreSQL installations to Docker containers: https://crondev.com/persistent-postgresql-inside-docker/
Another idea is to do myVar.split(',')[1];
For simple case, not using a regexp is a good idea...
2011-01-15
= 2011-16
= 1995
. This is then being implicitly converted from an integer to a date, giving you the 1995th day, starting from 1st Jan 1900.
You need to use SET @test = '2011-02-15'
Try to declare it in menifest file
<activity android:name=".HomeActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateAlwaysHidden"
>
You have to correctly override method equals() from class Object
Edit: I think that my first response was misunderstood probably because I was not too precise. So I decided to to add more explanations.
Why do you have to override equals()? Well, because this is in the domain of a developer to decide what does it mean for two objects to be equal. Reference equality is not enough for most of the cases.
For example, imagine that you have a HashMap whose keys are of type Person. Each person has name and address. Now, you want to find detailed bean using the key. The problem is, that you usually are not able to create an instance with the same reference as the one in the map. What you do is to create another instance of class Person. Clearly, operator == will not work here and you have to use equals().
But now, we come to another problem. Let's imagine that your collection is very large and you want to execute a search. The naive implementation would compare your key object with every instance in a map using equals(). That, however, would be very expansive. And here comes the hashCode(). As others pointed out, hashcode is a single number that does not have to be unique. The important requirement is that whenever equals() gives true for two objects, hashCode() must return the same value for both of them. The inverse implication does not hold, which is a good thing, because hashcode separates our keys into kind of buckets. We have a small number of instances of class Person in a single bucket. When we execute a search, the algorithm can jump right away to a correct bucket and only now execute equals for each instance. The implementation for hashCode() therefore must distribute objects as evenly as possible across buckets.
There is one more point. Some collections require a proper implementation of a hashCode() method in classes that are used as keys not only for performance reasons. The examples are: HashSet and LinkedHashSet. If they don’t override hashCode(), the default Object hashCode() method will allow multiple objects that you might consider "meaningfully equal" to be added to your "no duplicates allowed" set.
Some of the collections that use hashCode()
Have a look at those two classes from apache commons that will allow you to implement equals() and hashCode() easily
It's 2020 now, for the latest solution, you can use Burp Suite to sniffing https traffic without rooting your Android device.
Steps:
Install Burp Suite
Enable Proxy
Import the certification in your Android phone
Change you Wifi configuration to listening to proxy
Profit!
I wrote the full tutorial and screenshot on how to do it at here: https://www.yodiw.com/monitor-android-network-traffic-with-burp/
You can take both the collections in two different lists, say list1 and list2.
Then just write
list1.RemoveAll(Item => list2.Contains(Item));
This will work.
You can enable entity scan by adding below annotation on Application .java @EntityScan(basePackageClasses=YourEntityClassName.class)
Or you can set the packageToScan in your session factory. sessionFactory.setPackagesToScan(“com.all.entity”);
I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):
If you wish (like me) to have results containing mulitple rows of various SELECT queries "labelled" and can't manage this within the constraints of the PRINT statement in concert with the Messages tab you could turn it around and simply add messages to the Results tab per the below:
SELECT 'Results from scenario 1'
SELECT
*
FROM tblSample
If there is a router doing NAT, especially a low end router with few resources, it will age the oldest TCP sessions first. To do this it sets the RST
flag in the packet that effectively tells the receiving station to (very ungracefully) close the connection. this is done to save resources.
In application.properties, please add this:
spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.http.multipart.enabled=false
and in your html form, you need an : enctype="multipart/form-data"
.
For example:
<form method="POST" enctype="multipart/form-data" action="/">
Hope this help!
In Swift 4.2, Create it via @IBDesignable
like this:
@IBDesignable
class DesignableViewCustomCorner: UIView {
@IBInspectable var cornerRadious: CGFloat = 0 {
didSet {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadious, height: cornerRadious))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
}
You can't find a consistent reference because it seems to go by at least six different names!
I think it can be simplified into:
grep sysa /etc/passwd || {
echo "ERROR - The user sysa could not be looked up"
exit 2
}
or in a single command line
$ grep sysa /etc/passwd || { echo "ERROR - The user sysa could not be looked up"; exit 2; }
For some reason, import as suggested by Ricardo didnt work for me. I got it working with following statement:
<import resource="classpath*:/spring-config.xml" />
Ok, so here was my process:
keytool -list -v -keystore permanent.jks
- got me the alias.
keytool -export -alias alias_name -file certificate_name -keystore permanent.jks
- got me the certificate to import.
Then I could import it with the keytool:
keytool -import -alias alias_name -file certificate_name -keystore keystore location
As @Christian Bongiorno says the alias can't already exist in your keystore.
This word, hence, VanillaJS
is a just damn joke that changed my life. I had gone to a German company for an interview, I was very poor in JavaScript
and CSS
, very poor, so the Interviewer said to me: We're working here with VanillaJs, So you should know this framework.
Definitely, I understood that I'was rejected, but for one week I seek for VanillaJS, After all, I found THIS LINK.
What I am just was because of that joke.
VanillaJS === plain `JavaScript`
using (StringReader sr = new StringReader(text)) {
string line;
while ((line = sr.ReadLine()) != null) {
// do something
}
}
The error is coming as your query is getting formed as
SELECT * FROM Employ where number = parseInt(val);
I dont know which DB you are using but no DB will understand parseInt
.
What you can do is use a variable say temp and store the value of parseInt(val)
in temp variable and make the query as
SELECT * FROM Employ where number = temp;
Editor's Note: All functions in JavaScript are closures as explained in this post. However we are only interested in identifying a subset of these functions which are interesting from a theoretical point of view. Henceforth any reference to the word closure will refer to this subset of functions unless otherwise stated.
A simple explanation for closures:
Now let's use this to figure out who uses closures and who doesn't (for the sake of explanation I have named the functions):
Case 1: Your Friend's Program
for (var i = 0; i < 10; i++) {
(function f() {
var i2 = i;
setTimeout(function g() {
console.log(i2);
}, 1000);
})();
}
In the above program there are two functions: f
and g
. Let's see if they are closures:
For f
:
i2
is a local variable.i
is a free variable.setTimeout
is a free variable.g
is a local variable.console
is a free variable.i
is bound to the global scope.setTimeout
is bound to the global scope.console
is bound to the global scope.i
is not closed over by f
.setTimeout
is not closed over by f
.console
is not closed over by f
.Thus the function f
is not a closure.
For g
:
console
is a free variable.i2
is a free variable.console
is bound to the global scope.i2
is bound to the scope of f
.setTimeout
.
console
is not closed over by g
.i2
is closed over by g
.Thus the function g
is a closure for the free variable i2
(which is an upvalue for g
) when it's referenced from within setTimeout
.
Bad for you: Your friend is using a closure. The inner function is a closure.
Case 2: Your Program
for (var i = 0; i < 10; i++) {
setTimeout((function f(i2) {
return function g() {
console.log(i2);
};
})(i), 1000);
}
In the above program there are two functions: f
and g
. Let's see if they are closures:
For f
:
i2
is a local variable.g
is a local variable.console
is a free variable.console
is bound to the global scope.console
is not closed over by f
.Thus the function f
is not a closure.
For g
:
console
is a free variable.i2
is a free variable.console
is bound to the global scope.i2
is bound to the scope of f
.setTimeout
.
console
is not closed over by g
.i2
is closed over by g
.Thus the function g
is a closure for the free variable i2
(which is an upvalue for g
) when it's referenced from within setTimeout
.
Good for you: You are using a closure. The inner function is a closure.
So both you and your friend are using closures. Stop arguing. I hope I cleared the concept of closures and how to identify them for the both of you.
Edit: A simple explanation as to why are all functions closures (credits @Peter):
First let's consider the following program (it's the control):
lexicalScope();_x000D_
_x000D_
function lexicalScope() {_x000D_
var message = "This is the control. You should be able to see this message being alerted.";_x000D_
_x000D_
regularFunction();_x000D_
_x000D_
function regularFunction() {_x000D_
alert(eval("message"));_x000D_
}_x000D_
}
_x000D_
lexicalScope
and regularFunction
aren't closures from the above definition.message
to be alerted because regularFunction
is not a closure (i.e. it has access to all the variables in its parent scope - including message
).message
is indeed alerted.Next let's consider the following program (it's the alternative):
var closureFunction = lexicalScope();_x000D_
_x000D_
closureFunction();_x000D_
_x000D_
function lexicalScope() {_x000D_
var message = "This is the alternative. If you see this message being alerted then in means that every function in JavaScript is a closure.";_x000D_
_x000D_
return function closureFunction() {_x000D_
alert(eval("message"));_x000D_
};_x000D_
}
_x000D_
closureFunction
is a closure from the above definition.message
not to be alerted because closureFunction
is a closure (i.e. it only has access to all its non-local variables at the time the function is created (see this answer) - this does not include message
).message
is actually being alerted.What do we infer from this?
if you want to use truncate
use this:
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE table $table_name;
SET FOREIGN_KEY_CHECKS = 1;
No, you can't.
There's no reason why you would need to. This is a one-time operation and so takes only an additional second or two to actually type and execute.
If you're adding columns in your web application this is more indicative of a flaw in your data-model as you shouldn't need to be doing it.
In response to your comment that a comment is a column attribute; it may seem so but behind the scenes Oracle stores this as an attribute of an object.
SQL> desc sys.com$
Name Null? Type
----------------------------------------- -------- ----------------------------
OBJ# NOT NULL NUMBER
COL# NUMBER
COMMENT$ VARCHAR2(4000)
SQL>
The column is optional and sys.col$
does not contain comment information.
I assume, I have no knowledge, that this was done in order to only have one system of dealing with comments rather than multiple.
You need to set postion:relative of outer DIV and position:absolute of inner div.
Try this. Here is the Demo
#one
{
background-color: #EEE;
margin: 62px 258px;
padding: 5px;
width: 200px;
position: relative;
}
#two
{
background-color: #F00;
display: inline-block;
height: 30px;
position: absolute;
width: 100px;
top:10px;
}?
Same as the above answer but allows for triple click. (Delay 500) http://jsfiddle.net/luenwarneke/rV78Y/1/
var DELAY = 500,
clicks = 0,
timer = null;
$(document).ready(function() {
$("a")
.on("click", function(e){
clicks++; //count clicks
timer = setTimeout(function() {
if(clicks === 1) {
alert('Single Click'); //perform single-click action
} else if(clicks === 2) {
alert('Double Click'); //perform single-click action
} else if(clicks >= 3) {
alert('Triple Click'); //perform Triple-click action
}
clearTimeout(timer);
clicks = 0; //after action performed, reset counter
}, DELAY);
})
.on("dblclick", function(e){
e.preventDefault(); //cancel system double-click event
});
});
If you really want to use the DEGREE CELSIUS character “?”, then copy and paste is OK, provided that your document is UTF-8 encoded and declared as such in HTTP headers. Using the character reference ℃
would work equally well, and would work independently of character encoding, but the source would be much less readable.
The problem with Blackberry is most probably a font issue. I don’t know about fonts on Blackberry, but the font repertoire might be limited. There’s nothing you can do about this in HTML, but you can use CSS, possibly with @font face
.
But there is seldom any reason to use the DEGREE CELSIUS. It is a compatibility character, included in Unicode due to its use in East Asian writing. The Unicode Standard explicitly says in Chapter 15 (section 15.2, page 497):
“In normal use, it is better to represent degrees Celsius “°C” with a sequence of U+00B0 degree sign + U+0043 latin capital letter c, rather than U+2103 degree celsius.”
The degree sign “°” can be entered in many ways, including the entity reference `°, but normally it is best to insert it as a character, via copy and paste or otherwise. On Windows, you can use Alt 0176.
Caveat: Some browsers may treat the degree sign as allowing a line break after it even when no space intervenes, putting “°” and the following “C” on separate lines. There are different ways to prevent this. A simple and effective method is this: <nobr>42 °C</nobr>
.
I came across this issue when running a wordpress web site. I tried all sorts of things to fix it and wasn't sure how, ultimately the issue was because I was using DNS forwarding with masking, and the links to external sites were not being addressed properly. i.e. my site was hosted at http://123.456.789/index.html but was masked to run at http://somewebSite.com/index.html. When i entered http://123.456.789/index.html in the browser clicking on those same links resulted in no X-frame-origins issues in the JS console, but running http://somewebSite.com/index.html did. In order to properly mask you must add your host's DNS name servers to your domain service, i.e. godaddy.com should have name servers of example, ns1.digitalocean.com, ns2.digitalocean.com, ns3.digitalocean.com, if you were using digitalocean.com as your hosting service.
In Oracle PL/SQL, if you are running a query that may return multiple rows, you need a cursor to iterate over the results. The simplest way is with a for loop, e.g.:
declare
myname varchar2(20) := 'tom';
begin
for result_cursor in (select * from mytable where first_name = myname) loop
dbms_output.put_line(result_cursor.first_name);
dbms_output.put_line(result_cursor.other_field);
end loop;
end;
If you have a query that returns exactly one row, then you can use the select...into...
syntax, e.g.:
declare
myname varchar2(20);
begin
select first_name into myname
from mytable
where person_id = 123;
end;
On mac this worked for me:
git stash list(see all your stashs)
git stash list
git stash apply (just the number that you want from your stash list)
like this:
git stash apply 1
You can use the ejb3-persistence.jar that's bundled with hibernate. This jar only includes the javax.persistence package.
The colon actually exists in conjunction with ?
int minVal = (a < b) ? a : b;
is equivalent to:
int minval;
if(a < b){ minval = a;}
else{ minval = b; }
Also in the for each loop:
for(Node n : List l){ ... }
literally:
for(Node n = l.head; n.next != null; n = n.next)
This one drove me crazy - how to render a DataTable successfully in a .NET MVC view. This worked:
**@model List<Student>
@{
ViewData["Title"] = "Index";
}
<h2>NEW VIEW Index</h2>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
@foreach (var element in Model)
{
<tr>
<td>@Html.DisplayFor(m => element.ID)</td>
<td>@Html.DisplayFor(m => element.FirstName)</td>
<td>@Html.DisplayFor(m => element.LastName)</td>
</tr>
}
</tbody>
</table>**
Script in JS file:
**$(document).ready(function () {
$('#example').DataTable();
});**
Another possibility to store numpy arrays efficiently is Bloscpack:
#!/usr/bin/python
import numpy as np
import bloscpack as bp
import time
n = 10000000
a = np.arange(n)
b = np.arange(n) * 10
c = np.arange(n) * -0.5
tsizeMB = sum(i.size*i.itemsize for i in (a,b,c)) / 2**20.
blosc_args = bp.DEFAULT_BLOSC_ARGS
blosc_args['clevel'] = 6
t = time.time()
bp.pack_ndarray_file(a, 'a.blp', blosc_args=blosc_args)
bp.pack_ndarray_file(b, 'b.blp', blosc_args=blosc_args)
bp.pack_ndarray_file(c, 'c.blp', blosc_args=blosc_args)
t1 = time.time() - t
print "store time = %.2f (%.2f MB/s)" % (t1, tsizeMB / t1)
t = time.time()
a1 = bp.unpack_ndarray_file('a.blp')
b1 = bp.unpack_ndarray_file('b.blp')
c1 = bp.unpack_ndarray_file('c.blp')
t1 = time.time() - t
print "loading time = %.2f (%.2f MB/s)" % (t1, tsizeMB / t1)
and the output for my laptop (a relatively old MacBook Air with a Core2 processor):
$ python store-blpk.py
store time = 0.19 (1216.45 MB/s)
loading time = 0.25 (898.08 MB/s)
that means that it can store really fast, i.e. the bottleneck is typically the disk. However, as the compression ratios are pretty good here, the effective speed is multiplied by the compression ratios. Here are the sizes for these 76 MB arrays:
$ ll -h *.blp
-rw-r--r-- 1 faltet staff 921K Mar 6 13:50 a.blp
-rw-r--r-- 1 faltet staff 2.2M Mar 6 13:50 b.blp
-rw-r--r-- 1 faltet staff 1.4M Mar 6 13:50 c.blp
Please note that the use of the Blosc compressor is fundamental for achieving this. The same script but using 'clevel' = 0 (i.e. disabling compression):
$ python bench/store-blpk.py
store time = 3.36 (68.04 MB/s)
loading time = 2.61 (87.80 MB/s)
is clearly bottlenecked by the disk performance.
You can squash (join) commits with an Interactive Rebase. There is a pretty nice YouTube video which shows how to do this on the command line or with SmartGit:
If you are already a SmartGit user then you can select all your outgoing commits (by holding down the Ctrl key) and open the context menu (right click) to squash your commits.
It's very comfortable:
There is also a very nice tutorial from Atlassian which shows how it works:
(This is the KISS answer.)
Let's say you have several .java files in the current directory:
$ ls -1 *.java
javaFileName1.java
javaFileName2.java
Let's say each of them have a main()
method (so they are programs, not libs), then to compile them do:
javac *.java -d .
This will generate as many subfolders as "packages" the .java files are associated to. In my case all java files where inside under the same package name packageName
, so only one folder was generated with that name, so to execute each of them:
java -cp . packageName.javaFileName1
java -cp . packageName.javaFileName2
The w
and h
variables in img.onload
function are not in the same scope with those in the getMeta()
function. One way to do it, is as follows:
Fiddle: http://jsfiddle.net/ppanagi/28UES/2/
function getMeta(varA, varB) {
if (typeof varB !== 'undefined') {
alert(varA + ' width ' + varB + ' height');
} else {
var img = new Image();
img.src = varA;
img.onload = getMeta(this.width, this.height);
}
}
getMeta("http://snook.ca/files/mootools_83_snookca.png");
Check out the AutoCompleteSource
, AutoCompleteCustomSource
and AutoCompleteMode
properties.
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
col.Add("Foo");
col.Add("Bar");
textBox1.AutoCompleteCustomSource = col;
Note that the designer allows you to do that without writing any code...
The quickest way is to switch default branch from master to another and you can remove master branch from the web interface.
A better solution would not rely on JS to set the height of your element. The following is a solution that animates a fixed height element to full ("auto") height:
var $selector = $('div');
$selector
.data('oHeight',$selector.height())
.css('height','auto')
.data('nHeight',$selector.height())
.height($selector.data('oHeight'))
.animate({height: $selector.data('nHeight')},400);
use this command
grep "your word" searchDirectory/*.log
Get more on this link
http://www.cyberciti.biz/faq/howto-recursively-search-all-files-for-words/
For reference, this is a Kotlin implementation of @danh32's solution:
private fun getWebviewScale (contentWidth : Int) : Int {
val dm = DisplayMetrics()
windowManager.defaultDisplay.getRealMetrics(dm)
val pixWidth = dm.widthPixels;
return (pixWidth.toFloat()/contentWidth.toFloat() * 100F)
.toInt()
}
In my case, width was determined by three images to be 300 pix so:
webview.setInitialScale(getWebviewScale(300))
It took me hours to find this post. Thanks!
Struggled with the same problem: Many applications, BUT make at least this part "pleasant": The trick is called Batch-Uninstall
.
So use one of these three programs i can recommend:
Take no.2 in imho, 1 is nice but sometimes encounters some bugs :-)
The Python standard library does provide sched and threading for this task. But this means your scheduler script will have be running all the time instead of leaving its execution to the OS, which may or may not be what you want.
There is a way of doing this with tags, which allows for multiple defaults.
Assume you have the following struct, with 2 default tags default0 and default1.
type A struct {
I int `default0:"3" default1:"42"`
S string `default0:"Some String..." default1:"Some Other String..."`
}
Now it's possible to Set the defaults.
func main() {
ptr := &A{}
Set(ptr, "default0")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=3 ptr.S=Some String...
Set(ptr, "default1")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=42 ptr.S=Some Other String...
}
Here's the complete program in a playground.
If you're interested in a more complex example, say with slices and maps, then, take a look at creasty/defaultse
raw_input
returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: "AB" * 3
is "ABABAB"
; how much is "L" * 3.14
? Please do not reply "LLL|"
). You need to parse the string to a numerical value.
You might want to try:
salesAmount = float(raw_input("Insert sale amount here\n"))
Use the built-in MSDB.DBO.AGENT_DATETIME(20150119,0)
https://blog.sqlauthority.com/2015/03/13/sql-server-interesting-function-agent_datetime/
To set radio button checked in edit mode in MVC razor view, please trying as follow:
<div class="col-lg-11 col-md-11">
@Html.RadioButtonFor(m => m.Role, "1", Model.Role == 1 ? "checked" : string.Empty)
<span>Admin</span>
@Html.RadioButtonFor(m => m.Role, "0", Model.Role == 0 ? "checked" : string.Empty)
<span>User</span>
@Html.HiddenFor(m => m.Role)
</div>
Hope it help!
CSS can not be used to animation, or any style modification on events.
The only way is to use a javascript function, which will return the width of a given element, then, subtract 100px to it, and set the new width size.
Assuming you are using jQuery, you could do something like that:
oldWidth = $('#yourElem').width();
$('#yourElem').width(oldWidth-100);
And with native javascript:
oldWidth = document.getElementById('yourElem').clientWidth;
document.getElementById('yourElem').style.width = oldWidth-100+'px';
We assume that you have a css style set with 100%;
I had this same problem, using an old version of the route-me library. I "skipped" all the libraries, and the libraries inside of libraries (proj4), but I still had the same problem. Turns out that route-me and proj4 were installing public header files, even when the libraries were being skipped, which was messing it up in the same way! So I just went into the route-me and proj4 targets "Build Phases" tab, opened "Copy Headers", opened "Public", and dragged those headers from "Public" into "Project". Now they don't get installed in $(BUILD)/usr/local/include, and I'm able to make an ipa file from the archive!
I hope Apple fixes this horrible usability problem with XCode. It gives absolutely no indication of what's wrong, it just doesn't work. I hate dimmed out controls that don't tell you anything about why they're dimmed out. How about instead of ignoring clicks, the disabled controls could pop up a message telling you why the hell they're disabled when you click on them in frustration?
This error occurred for me because mod_rewrite was not enabled. Everything worked fine after enabling the rewrite module: https://www.debuntu.org/how-to-enable-apache-modules-under-debian-based-system-page-2/
You can use GAS, which is gcc's backend assembler:
Create a list of namedtuples
It can often be very handy to use namedtuple. For example, you have a dictionary of 'name' as keys and 'score' as values like:
d = {'John':5, 'Alex':10, 'Richard': 7}
You can list the items as tuples, sorted if you like, and get the name and score of, let's say the player with the highest score (index=0) very Pythonically like this:
>>> player = best[0]
>>> player.name
'Alex'
>>> player.score
10
How to do this:
list in random order or keeping order of collections.OrderedDict:
import collections
Player = collections.namedtuple('Player', 'name score')
players = list(Player(*item) for item in d.items())
in order, sorted by value ('score'):
import collections
Player = collections.namedtuple('Player', 'score name')
sorted with lowest score first:
worst = sorted(Player(v,k) for (k,v) in d.items())
sorted with highest score first:
best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)
You should run your entire script as superuser. If you want to run some command as non-superuser, use "-u" option of sudo:
#!/bin/bash
sudo -u username command1
command2
sudo -u username command3
command4
When running as root, sudo doesn't ask for a password.
Update:
You might need to edit your ~/.netrc file:
Original answer:
Why did you disable ssl? I think this might have to do with you not being able to push via https. I'd set it back and try to push again:
git config –global http.sslVerify true
Here's a simple example:
Pattern pattern = Pattern.compile(regexPattern);
List<String> list = new ArrayList<String>();
Matcher m = pattern.matcher(input);
while (m.find()) {
list.add(m.group());
}
(if you have more capturing groups, you can refer to them by their index as an argument of the group method. If you need an array, then use list.toArray()
)
interface in the Java programming language is an abstract type that is used to specify a behavior that classes must implement. They are similar to protocols. Interfaces are declared using the interface keyword
@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example:
@interface MyAnnotation {
String value();
String name();
int age();
String[] newNames();
}
This example defines an annotation called MyAnnotation which has four elements. Notice the @interface keyword. This signals to the Java compiler that this is a Java annotation definition.
Notice that each element is defined similarly to a method definition in an interface. It has a data type and a name. You can use all primitive data types as element data types. You can also use arrays as data type. You cannot use complex objects as data type.
To use the above annotation, you could use code like this:
@MyAnnotation(
value="123",
name="Jakob",
age=37,
newNames={"Jenkov", "Peterson"}
)
public class MyClass {
}
Reference - http://tutorials.jenkov.com/java/annotations.html
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
An example of retrieving data from a table having columns column1, column2 ,column3 column4, cloumn1 and 2 hold int values and column 3 and 4 hold varchar(10)
import java.sql.*;
// need to import this as the STEP 1. Has the classes that you mentioned
public class JDBCexample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://LocalHost:3306/databaseNameHere";
// DON'T PUT ANY SPACES IN BETWEEN and give the name of the database (case insensitive)
// database credentials
static final String USER = "root";
// usually when you install MySQL, it logs in as root
static final String PASS = "";
// and the default password is blank
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// registering the driver__STEP 2
Class.forName("com.mysql.jdbc.Driver");
// returns a Class object of com.mysql.jdbc.Driver
// (forName(""); initializes the class passed to it as String) i.e initializing the
// "suitable" driver
System.out.println("connecting to the database");
// opening a connection__STEP 3
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// executing a query__STEP 4
System.out.println("creating a statement..");
stmt = conn.createStatement();
// creating an object to create statements in SQL
String sql;
sql = "SELECT column1, cloumn2, column3, column4 from jdbcTest;";
// this is what you would have typed in CLI for MySQL
ResultSet rs = stmt.executeQuery(sql);
// executing the query__STEP 5 (and retrieving the results in an object of ResultSet)
// extracting data from result set
while(rs.next()){
// retrieve by column name
int value1 = rs.getInt("column1");
int value2 = rs.getInt("column2");
String value3 = rs.getString("column3");
String value4 = rs.getString("columnm4");
// displaying values:
System.out.println("column1 "+ value1);
System.out.println("column2 "+ value2);
System.out.println("column3 "+ value3);
System.out.println("column4 "+ value4);
}
// cleaning up__STEP 6
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
// handle sql exception
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception for class.forName
e.printStackTrace();
}finally{
//closing the resources..STEP 7
try {
if (stmt != null)
stmt.close();
} catch (SQLException e2) {
e2.printStackTrace();
}try {
if (conn != null) {
conn.close();
}
} catch (SQLException e2) {
e2.printStackTrace();
}
}
System.out.println("good bye");
}
}
First, remove the float
attribute on the inner div
s. Then, put text-align: center
on the main outer div
. And for the inner div
s,
use display: inline-block
. Might also be wise to give them explicit widths too.
<div style="margin: auto 1.5em; display: inline-block;">
<img title="Nadia Bjorlin" alt="Nadia Bjorlin" src="headshot.nadia.png"/>
<br/>
Nadia Bjorlin
</div>
Your jsfiddle does not work anymore. I've fixed it: http://jsfiddle.net/tkrotoff/bgC6E/40/ using React 16 and ES6 classes.
class Adaptive_Input extends React.Component {
handle_change(e) {
var new_text = e.currentTarget.value;
this.props.on_Input_Change(new_text);
}
render() {
return (
<div className="adaptive_placeholder_input_container">
<input
className="adaptive_input"
type="text"
required="required"
onChange={this.handle_change.bind(this)} />
<label
className="adaptive_placeholder"
alt={this.props.initial}
placeholder={this.props.focused} />
</div>
);
}
}
class Form extends React.Component {
render() {
return (
<form>
<Adaptive_Input
initial={'Name Input'}
focused={'Name Input'}
on_Input_Change={this.props.handle_text_input} />
<Adaptive_Input
initial={'Value 1'}
focused={'Value 1'}
on_Input_Change={this.props.handle_value_1_input} />
<Adaptive_Input
initial={'Value 2'}
focused={'Value 2'}
on_Input_Change={this.props.handle_value_2_input} />
</form>
);
}
}
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {
Name: 'No Name',
Value_1: '0',
Value_2: '0',
Display_Value: '0'
};
}
handle_text_input(new_text) {
this.setState({
Name: new_text
});
}
handle_value_1_input(new_value) {
new_value = parseInt(new_value);
var updated_display = new_value + parseInt(this.state.Value_2);
updated_display = updated_display.toString();
this.setState({
Value_1: new_value,
Display_Value: updated_display
});
}
handle_value_2_input(new_value) {
new_value = parseInt(new_value);
var updated_display = parseInt(this.state.Value_1) + new_value;
updated_display = updated_display.toString();
this.setState({
Value_2: new_value,
Display_Value: updated_display
});
}
render() {
return(
<div>
<h2>{this.state.Name}</h2>
<h2>Value 1 + Value 2 = {this.state.Display_Value}</h2>
<Form
handle_text_input={this.handle_text_input.bind(this)}
handle_value_1_input={this.handle_value_1_input.bind(this)}
handle_value_2_input={this.handle_value_2_input.bind(this)}
/>
</div>
);
}
}
ReactDOM.render(<Page />, document.getElementById('app'));
And now the same code hacked with form validation thanks to this library: https://github.com/tkrotoff/react-form-with-constraints => http://jsfiddle.net/tkrotoff/k4qa4heg/
const { FormWithConstraints, FieldFeedbacks, FieldFeedback } = ReactFormWithConstraints;
class Adaptive_Input extends React.Component {
static contextTypes = {
form: PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.state = {
field: undefined
};
this.fieldWillValidate = this.fieldWillValidate.bind(this);
this.fieldDidValidate = this.fieldDidValidate.bind(this);
}
componentWillMount() {
this.context.form.addFieldWillValidateEventListener(this.fieldWillValidate);
this.context.form.addFieldDidValidateEventListener(this.fieldDidValidate);
}
componentWillUnmount() {
this.context.form.removeFieldWillValidateEventListener(this.fieldWillValidate);
this.context.form.removeFieldDidValidateEventListener(this.fieldDidValidate);
}
fieldWillValidate(fieldName) {
if (fieldName === this.props.name) this.setState({field: undefined});
}
fieldDidValidate(field) {
if (field.name === this.props.name) this.setState({field});
}
handle_change(e) {
var new_text = e.currentTarget.value;
this.props.on_Input_Change(e, new_text);
}
render() {
const { field } = this.state;
let className = 'adaptive_placeholder_input_container';
if (field !== undefined) {
if (field.hasErrors()) className += ' error';
if (field.hasWarnings()) className += ' warning';
}
return (
<div className={className}>
<input
type={this.props.type}
name={this.props.name}
className="adaptive_input"
required
onChange={this.handle_change.bind(this)} />
<label
className="adaptive_placeholder"
alt={this.props.initial}
placeholder={this.props.focused} />
</div>
);
}
}
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
Name: 'No Name',
Value_1: '0',
Value_2: '0',
Display_Value: '0'
};
}
handle_text_input(e, new_text) {
this.form.validateFields(e.currentTarget);
this.setState({
Name: new_text
});
}
handle_value_1_input(e, new_value) {
this.form.validateFields(e.currentTarget);
if (this.form.isValid()) {
new_value = parseInt(new_value);
var updated_display = new_value + parseInt(this.state.Value_2);
updated_display = updated_display.toString();
this.setState({
Value_1: new_value,
Display_Value: updated_display
});
}
else {
this.setState({
Display_Value: 'Error'
});
}
}
handle_value_2_input(e, new_value) {
this.form.validateFields(e.currentTarget);
if (this.form.isValid()) {
new_value = parseInt(new_value);
var updated_display = parseInt(this.state.Value_1) + new_value;
updated_display = updated_display.toString();
this.setState({
Value_2: new_value,
Display_Value: updated_display
});
}
else {
this.setState({
Display_Value: 'Error'
});
}
}
render() {
return(
<div>
<h2>Name: {this.state.Name}</h2>
<h2>Value 1 + Value 2 = {this.state.Display_Value}</h2>
<FormWithConstraints ref={form => this.form = form} noValidate>
<Adaptive_Input
type="text"
name="name_input"
initial={'Name Input'}
focused={'Name Input'}
on_Input_Change={this.handle_text_input.bind(this)} />
<FieldFeedbacks for="name_input">
<FieldFeedback when="*" error />
<FieldFeedback when={value => !/^\w+$/.test(value)} warning>Should only contain alphanumeric characters</FieldFeedback>
</FieldFeedbacks>
<Adaptive_Input
type="number"
name="value_1_input"
initial={'Value 1'}
focused={'Value 1'}
on_Input_Change={this.handle_value_1_input.bind(this)} />
<FieldFeedbacks for="value_1_input">
<FieldFeedback when="*" />
</FieldFeedbacks>
<Adaptive_Input
type="number"
name="value_2_input"
initial={'Value 2'}
focused={'Value 2'}
on_Input_Change={this.handle_value_2_input.bind(this)} />
<FieldFeedbacks for="value_2_input">
<FieldFeedback when="*" />
</FieldFeedbacks>
</FormWithConstraints>
</div>
);
}
}
ReactDOM.render(<Form />, document.getElementById('app'));
The proposed solution here is hackish as I've tried to keep it close to the original jsfiddle. For proper form validation with react-form-with-constraints, check https://github.com/tkrotoff/react-form-with-constraints#examples