Use below script to get back to normal 1 plot:
par(mfrow = c(1,1))
This 'just works' for me using jQuery, provided you don't try to append a subset the XHR-returned HTML to the document. (See this bug report showing the problem with jQuery.)
Here is an example showing it working:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>test_1.4</title>
<script type="text/javascript" charset="utf-8" src="jquery.1.4.2.js"></script>
<script type="text/javascript" charset="utf-8">
var snippet = "<div><span id='a'>JS did not run<\/span><script type='text/javascript'>" +
"$('#a').html('Hooray! JS ran!');" +
"<\/script><\/div>";
$(function(){
$('#replaceable').replaceWith($(snippet));
});
</script>
</head>
<body>
<div id="replaceable">I'm going away.</div>
</body>
</html>
Here is the equivalent of the above: http://jsfiddle.net/2CTLH/
You are actually trying to redirect a page which has some response to throw. So first you keep the information you have throw in a buffer using response.buffer = true
in beginning of the page and then flush it when required using response.flush
this error will get fixed
I solved this problem by deleting the temporary files of Microsoft .NET framework. Location: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files and C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
date -d @1278999698 +'%Y-%m-%d %H:%M:%S'
Where the number behind @
is the number in seconds
Use this code to ensure the user doesn't just enter spaces but a valid name:
pattern="[a-zA-Z][a-zA-Z0-9\s]*"
Just for all those people who say side effects are evil: a place where having two side effects in one condition is good would be reading two file objects in tandem.
While File1.Seek_Next_Row() And File2.Seek_Next_Row()
Str1 = File1.GetRow()
Str2 = File2.GetRow()
End While
Using the And
ensures that a row is consumed every time the condition is checked. Whereas AndAlso
might read the last line of File1
and leave File2
without a consumed line.
Of course the code above wouldn't work, but I use side effects like this all the time and wouldn't consider it "bad" or "evil" code as some would lead you to believe. It's easy to read and efficient.
The dash type of a linestyle
is given by the linetype
, which does also select the line color unless you explicitely set an other one with linecolor
.
However, the support for dashed lines depends on the selected terminal:
png
(uses libgd
)pngcairo
, support dashed lines, but it is disables by default. To enable it, use set termoption dashed
, or set terminal pngcairo dashed ...
.linetype
, use the test
command:Running
set terminal pngcairo dashed
set output 'test.png'
test
set output
gives:
whereas, the postscript
terminal shows different dash patterns:
set terminal postscript eps color colortext
set output 'test.eps'
test
set output
Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:
A new dashtype
parameter was introduced:
To get the predefined dash patterns, use e.g.
plot x dashtype 2
You can also specify custom dash patterns like
plot x dashtype (3,5,10,5),\
2*x dashtype '.-_'
The terminal options dashed
and solid
are ignored. By default all lines are solid. To change them to dashed, use e.g.
set for [i=1:8] linetype i dashtype i
The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic
:
You can try this:
Map<String,String> map = new HashMap<>();
Map.Entry<String,String> entry = map.entrySet().iterator().next();
String key = entry.getKey();
String value = entry.getValue();
Keep in mind, HashMap
does not guarantee the insertion order. Use a LinkedHashMap
to keep the order intact.
Eg:
Map<String,String> map = new LinkedHashMap<>();
map.put("Active","33");
map.put("Renewals Completed","3");
map.put("Application","15");
Map.Entry<String,String> entry = map.entrySet().iterator().next();
String key= entry.getKey();
String value=entry.getValue();
System.out.println(key);
System.out.println(value);
Output:
Active
33
I run into same problem.
What I found from documentation, we should use namedspace.
in your case {% url login:login_view %}
Try this please, <a target="_blank" routerLink="/Page2">
Update1: Custom directives to the rescue! Full code is here: https://github.com/pokearound/angular2-olnw
import { Directive, ElementRef, HostListener, Input, Inject } from '@angular/core';
@Directive({ selector: '[olinw007]' })
export class OpenLinkInNewWindowDirective {
//@Input('olinwLink') link: string; //intro a new attribute, if independent from routerLink
@Input('routerLink') link: string;
constructor(private el: ElementRef, @Inject(Window) private win:Window) {
}
@HostListener('mousedown') onMouseEnter() {
this.win.open(this.link || 'main/default');
}
}
Notice, Window is provided and OpenLinkInNewWindowDirective declared below:
import { AppAboutComponent } from './app.about.component';
import { AppDefaultComponent } from './app.default.component';
import { PageNotFoundComponent } from './app.pnf.component';
import { OpenLinkInNewWindowDirective } from './olinw.directive';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
const appRoutes: Routes = [
{ path: '', pathMatch: 'full', component: AppDefaultComponent },
{ path: 'home', component: AppComponent },
{ path: 'about', component: AppAboutComponent },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
declarations: [
AppComponent, AppAboutComponent, AppDefaultComponent, PageNotFoundComponent, OpenLinkInNewWindowDirective
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(appRoutes)
],
providers: [{ provide: Window, useValue: window }],
bootstrap: [AppComponent]
})
export class AppModule { }
First link opens in new Window, second one will not:
<h1>
{{title}}
<ul>
<li><a routerLink="/main/home" routerLinkActive="active" olinw007> OLNW</a></li>
<li><a routerLink="/main/home" routerLinkActive="active"> OLNW - NOT</a></li>
</ul>
<div style="background-color:#eee;">
<router-outlet></router-outlet>
</div>
</h1>
Tada! ..and you are welcome =)
Update2: As of v2.4.10 <a target="_blank" routerLink="/Page2">
works
There's a theme available specifically for this
options: {
theme: 'maximized'
}
from the Google chart docs:
Currently only one theme is available:
'maximized' - Maximizes the area of the chart, and draws the legend and all of the labels inside the chart area. Sets the following options:
chartArea: {width: '100%', height: '100%'},
legend: {position: 'in'},
titlePosition: 'in', axisTitlesPosition: 'in',
hAxis: {textPosition: 'in'}, vAxis: {textPosition: 'in'}
This way you don't need to add the CSS outside of the component:
@Component({
selector: 'body',
template: 'app-element',
// prefer decorators (see below)
// host: {'[class.someClass]':'someField'}
})
export class App implements OnInit {
constructor(private cdRef:ChangeDetectorRef) {}
someField: boolean = false;
// alternatively also the host parameter in the @Component()` decorator can be used
@HostBinding('class.someClass') someField: boolean = false;
ngOnInit() {
this.someField = true; // set class `someClass` on `<body>`
//this.cdRef.detectChanges();
}
}
This CSS is defined inside the component and the selector is only applied if the class someClass
is set on the host element (from outside):
:host(.someClass) {
background-color: red;
}
img = cv2.imread('2015-05-27-191152.jpg',0)
The above line of code reads your image in grayscale color model, because of the 0 appended at the end. And if you again try to convert an already gray image to gray image it will show that error.
So either use above style or try undermentioned code:
img = cv2.imread('2015-05-27-191152.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Old question which has an accepted answer already, but I like to think of these two isolation levels in terms of how they change the locking behavior in SQL Server. This might be helpful for those who are debugging deadlocks like I was.
READ COMMITTED (default)
Shared locks are taken in the SELECT and then released when the SELECT statement completes. This is how the system can guarantee that there are no dirty reads of uncommitted data. Other transactions can still change the underlying rows after your SELECT completes and before your transaction completes.
REPEATABLE READ
Shared locks are taken in the SELECT and then released only after the transaction completes. This is how the system can guarantee that the values you read will not change during the transaction (because they remain locked until the transaction finishes).
In your case, I would use YAML .
That is an elegant and professional standard for dealing with multiple parameters. The values are loaded from a separate file. You can see some info in this link:
https://keleshev.com/yaml-quick-introduction
But it is easier to Google it, as it is a standard, there are hundreds of info about it, you can find what best fits to your understanding. ;)
Best regards.
See what is available in Jetty for storing password (or hashes) in configuration files, and consider if the OBF encoding might be useful for you. Then see in the source how it is done.
http://www.eclipse.org/jetty/documentation/current/configuring-security-secure-passwords.html
You can use the bindParam
or bindValue
methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name));
Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1
and change the fetch method into fetchAll
:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
Declare SupportMapFragment object globally
private SupportMapFragment mapFragment;
In onCreateView() method put below code
mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
In onDestroyView() put below code
@Override
public void onDestroyView() {
super.onDestroyView();
if (mapFragment != null)
getFragmentManager().beginTransaction().remove(mapFragment).commit();
}
In your xml file put below code
<fragment
android:id="@+id/map"
android:name="com.abc.Driver.fragment.FragmentHome"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Above code solved my problem and it's working fine
The following command installs ruby gem for ubuntu:
apt-get install libgemplugin-ruby
I did it after ruby was installed.
Try this CSS:
h1 {
left: 0;
line-height: 200px;
margin-top: -100px;
position: absolute;
text-align: center;
top: 50%;
width: 100%;
}
jsFiddle: http://jsfiddle.net/wprw3/
Maybe SO_REUSEADDR helps here? http://www.unixguide.net/network/socketfaq/4.5.shtml
Choose some columns to coerce to factors:
cols <- c("A", "C", "D", "H")
Use lapply()
to coerce and replace the chosen columns:
data[cols] <- lapply(data[cols], factor) ## as.factor() could also be used
Check the result:
sapply(data, class)
# A B C D E F G
# "factor" "integer" "factor" "factor" "integer" "integer" "integer"
# H I J
# "factor" "integer" "integer"
A bit late, but I couldn't find the way I implemented it, this version needs closure, php>=5.3, but could be altered not to:
$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';
$order = array('name', 'dob', 'address');
$keys= array_flip($order);
uksort($customer, function($a, $b)use($keys){
return $keys[$a] - $keys[$b];
});
print_r($customer);
Of course 'dontSortMe' needs to be sorted out, and may appear first in the example
Keep the java script code inside the body tag
<body>
<script type="text/javascript">
</script>
</body>
A simple jquery solution for those who don't need a pure css solution:
$(".letter").hover(function() {_x000D_
$(this).closest("#word").toggleClass("hovered")_x000D_
});
_x000D_
.hovered {_x000D_
background-color: lightblue;_x000D_
}_x000D_
_x000D_
.letter {_x000D_
margin: 20px;_x000D_
background: lightgray;_x000D_
}_x000D_
_x000D_
.letter:hover {_x000D_
background: grey;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="word">_x000D_
<div class="letter">T</div>_x000D_
<div class="letter">E</div>_x000D_
<div class="letter">S</div>_x000D_
<div class="letter">T</div>_x000D_
</div>
_x000D_
JavaScript:
<script type="text/javascript">
$(function() {
var url = window.location;
$('ul.nav a').filter(function() {
return this.href == url;
}).parent().parent().parent().addClass('active');
});
</script>
CSS:
.active{
color: #fff;
background-color: #080808;
}
HTML:
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="true"><i class="glyphicon glyphicon-user icon-white"></i> MY ACCOUNT <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li>
<?php echo anchor('myaccount', 'HOME', 'title="HOME"'); ?>
</li>
<li>
<?php echo anchor('myaccount/credithistory', 'CREDIT HISTORY', 'title="CREDIT HISTORY"'); ?>
</li>
</ul>
</li>
</ul>
items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
you can also get the line if there are other characters before token
items=re.findall("^.*token.*$",s,re.MULTILINE)
The above works like grep token on unix and keyword 'in' or .contains in python and C#
s='''
qwertyuiop
asdfghjkl
zxcvbnm
token qwerty
asdfghjklñ
'''
http://pythex.org/ matches the following 2 lines
....
....
token qwerty
Since .net45 you can use the LeaveOpen
constructor argument of StreamWriter
and still use the using
statement. Example:
using (var ms = new MemoryStream())
{
using (var sw = new StreamWriter(ms, Encoding.UTF8, 1024, true))
{
sw.WriteLine("data");
sw.WriteLine("data 2");
}
ms.Position = 0;
using (var sr = new StreamReader(ms))
{
Console.WriteLine(sr.ReadToEnd());
}
}
All of the answers so far involve completely replacing the default button behavior with something else. However, IMHO it is useful and important to understand that it's possible to change just the part you care about, by editing the existing, default template for a XAML element.
In the case of dealing with the hover effect on a WPF button, the change in appearance in a WPF Button
element is caused by a Trigger
in the default style for the Button
, which is based on the IsMouseOver
property and sets the Background
and BorderBrush
properties of the top-level Border
element in the control template. The Button
element's background is underneath the Border
element's background, so changing the Button.Background
property doesn't prevent the hover effect from being seen.
With some effort, you could override this behavior with your own setter, but because the element you need to affect is in the template and not directly accessible in your own XAML, that approach would be difficult and IMHO overly complex.
Another option would be to make use the graphic as the Content
for the Button
rather than the Background
. If you need additional content over the graphic, you can combine them with a Grid
as the top-level object in the content.
However, if you literally just want to disable the hover effect entirely (rather than just hiding it), you can use the Visual Studio XAML Designer:
<Trigger Property="IsMouseOver" Value="true">...</Trigger>
element. Of course, you can make any change to the template you want at that point.When you're done, the button style will look something like this:
<p:Style x:Key="FocusVisual">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</p:Style>
<SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
<SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
<SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
<SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
<SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
<SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
<SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
<SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
<SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
<p:Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
<Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
<Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
<Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
<ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsDefaulted" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
</Trigger>
<!--<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
</Trigger>-->
<Trigger Property="IsPressed" Value="true">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
<Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</p:Style>
(Note: you can omit the p:
XML namespace qualifications in the actual code…I provide them here only because the Stack Overflow XML code formatter gets confused by <Style/>
elements that don't have a fully-qualified name with XML namespace.)
If you want to apply the same style to other buttons, you can just right-click them and choose "Edit Template/Apply Resource" and select the style you just added for the first button. You can even make that style the default style for all buttons, using the normal techniques for applying a default style to elements in XAML.
I had a very similar issue with the same error message. "Changes not staged for commit", yet when I do a diff it shows differences. I finally figured out that a while back I had changed a directories case. ex. "PostgeSQL" to "postgresql". As I remember now sometimes git will leave a file or two behind in the old case directory. Then you will commit a new version to the new case.
Thus git doesn't know which one to rely on. So to resolve it, I had to go onto the github's website. Then you're able to view both cases. And you must delete all the files in the incorrect cased directory. Be sure that you have the correct version saved off or in the correct cased directory.
Once you have deleted all the files in the old case directory, that whole directory will disappear. Then do a commit.
At this point you should be able to do a Pull on your local computer and not see the conflicts any more. Thus being able to commit again. :)
I used this way to make my project faster:
RichTextBox rcbCatalyst = new RichTextBox()
{
Lines = arrayString
};
string text = rcbCatalyst.Text;
rcbCatalyst.Dispose();
return text;
RichTextBox.Text will automatically convert your array to a multiline string!
Since there are several answers here showing non-working code for Windows, here is a clarification:
Runtime.getRuntime().exec("cls");
This command does not work, for two reasons:
There is no executable named cls.exe
or cls.com
in a standard Windows installation that could be invoked via Runtime.exec
, as the well-known command cls
is builtin to Windows’ command line interpreter.
When launching a new process via Runtime.exec
, the standard output gets redirected to a pipe which the initiating Java process can read. But when the output of the cls
command gets redirected, it doesn’t clear the console.
To solve this problem, we have to invoke the command line interpreter (cmd
) and tell it to execute a command (/c cls
) which allows invoking builtin commands. Further we have to directly connect its output channel to the Java process’ output channel, which works starting with Java 7, using inheritIO()
:
import java.io.IOException;
public class CLS {
public static void main(String... arg) throws IOException, InterruptedException {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
}
Now when the Java process is connected to a console, i.e. has been started from a command line without output redirection, it will clear the console.
I fond that executing click()
event on a
element inside a for loop
for multiple files download works only for limited number of files (10 files in my case). The only reason that would explain this behavior that made sense to me, was speed/intervals of downloads executed by click()
events.
I figure out that, if I slow down execution of click()
event, then I will be able to downloads all files.
This is solution that worked for me.
var urls = [
'http://example.com/file1',
'http://example.com/file2',
'http://example.com/file3'
]
var interval = setInterval(download, 300, urls);
function download(urls) {
var url = urls.pop();
var a = document.createElement("a");
a.setAttribute('href', url);
a.setAttribute('download', '');
a.setAttribute('target', '_blank');
a.click();
if (urls.length == 0) {
clearInterval(interval);
}
}
I execute download event click()
every 300ms. When there is no more files to download urls.length == 0
then, I execute clearInterval
on interval
function to stop downloads.
Modified shA.t's query for more clarity:
-- t1 left join t2
SELECT t1.value, t2.value
FROM t1 LEFT JOIN t2 ON t1.value = t2.value
UNION ALL -- include duplicates
-- t1 right exclude join t2 (records found only in t2)
SELECT t1.value, t2.value
FROM t1 RIGHT JOIN t2 ON t1.value = t2.value
WHERE t1.value IS NULL
I had a wrong ssh private key for Bitbucket along with the right one in ssh agent.
Deleted all keys first
ssh-add -D
Then added just the right key.
ssh-add ~/.ssh/id_rsa
Replace with:
$('#something').click(function() {
location.reload();
});
There are some great answers already, but none of them address a complete list of what the __future__
statement currently supports.
Put simply, the __future__
statement forces Python interpreters to use newer features of the language.
The features that it currently supports are the following:
nested_scopes
Prior to Python 2.1, the following code would raise a NameError:
def f():
...
def g(value):
...
return g(value-1) + 1
...
The from __future__ import nested_scopes
directive will allow for this feature to be enabled.
generators
Introduced generator functions such as the one below to save state between successive function calls:
def fib():
a, b = 0, 1
while 1:
yield b
a, b = b, a+b
division
Classic division is used in Python 2.x versions. Meaning that some division statements return a reasonable approximation of division ("true division") and others return the floor ("floor division"). Starting in Python 3.0, true division is specified by x/y
, whereas floor division is specified by x//y
.
The from __future__ import division
directive forces the use of Python 3.0 style division.
absolute_import
Allows for parenthesis to enclose multiple import
statements. For example:
from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text,
LEFT, DISABLED, NORMAL, RIDGE, END)
Instead of:
from Tkinter import Tk, Frame, Button, Entry, Canvas, Text, \
LEFT, DISABLED, NORMAL, RIDGE, END
Or:
from Tkinter import Tk, Frame, Button, Entry, Canvas, Text
from Tkinter import LEFT, DISABLED, NORMAL, RIDGE, END
with_statement
Adds the statement with
as a keyword in Python to eliminate the need for try/finally
statements. Common uses of this are when doing file I/O such as:
with open('workfile', 'r') as f:
read_data = f.read()
print_function
:
Forces the use of Python 3 parenthesis-style print()
function call instead of the print MESSAGE
style statement.
unicode_literals
Introduces the literal syntax for the bytes
object. Meaning that statements such as bytes('Hello world', 'ascii')
can be simply expressed as b'Hello world'
.
generator_stop
Replaces the use of the StopIteration
exception used inside generator functions with the RuntimeError
exception.
One other use not mentioned above is that the __future__
statement also requires the use of Python 2.1+ interpreters since using an older version will throw a runtime exception.
proposed solution edit works if you replace the row
Set rDst = ThisWorkbook.Sheets("SomeSheet").Cells("YourCell").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
with
Set rDst = ThisWorkbook.Sheets("SomeSheet").Range("YourRange").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
IN db2warehouse I found that "owner" doesn't exist, so I describe table syscat.systables and try using CREATOR instead and it works.
db2 "select NAME from sysibm.systables where CREATOR = '[SCHEMANAME]'and type = 'T'"
In my case the only solution was to add the reference to the System.Configuration
in my Test project as well.
Just use a normal Javascript expression, no {}
or anything necessary:
@click="addToCount(item.contactID)"
if you also need the event object:
@click="addToCount(item.contactID, $event)"
For those interested, here's an alternative to invoking Array.join:
var arrayOfStrings = ['foo', 'bar'];
var result = String.concat.apply(null, arrayOfStrings);
console.log(result);
The output, as expected, is the string 'foobar'. In Firefox, this approach outperforms Array.join but is outperformed by + concatenation. Since String.concat requires each segment to be specified as a separate argument, the caller is limited by any argument count limit imposed by the executing JavaScript engine. Take a look at the documentation of Function.prototype.apply() for more information.
Javascript is single-threaded, so by nature there should not be a sleep function because sleeping will block the thread. setTimeout
is a way to get around this by posting an event to the queue to be executed later without blocking the thread. But if you want a true sleep function, you can write something like this:
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
}
}
Note: The above code is NOT recommended.
The error message could result due to the following reason:
Please follow the steps mentioned below to resolve the issue:
Method 1:
Method 2: 1. Run System File Checker. Refer to the link mentioned below for additional information: http://support.microsoft.com/kb/929833
Version 1:
// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();
Version 2:
$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();
In case of answered question you can use them:
$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();
upper-case(string) and lower-case(string)
When you want to create json format it had to be in this format for it to read:
[
{
"":"",
"":[
{
"":"",
"":""
}
]
}
]
There are several different methods you have to use for different browsers. Libraries like jQuery give you a cross-browser interface that handles it all for you, though.
To communicate a child component with another child component I've made a method in parent which calls a method in a child with:
this.$refs.childMethod()
And from the another child I've called the root method:
this.$root.theRootMethod()
It worked for me.
Assuming self
is a UIViewController
:
func displayAlert() {
let alert = UIAlertController(title: "Test",
message: "I am a modal alert",
preferredStyle: .alert)
let defaultButton = UIAlertAction(title: "OK",
style: .default) {(_) in
// your defaultButton action goes here
}
alert.addAction(defaultButton)
present(alert, animated: true) {
// completion goes here
}
}
You can specify a default value for the optional argument with something that would never passed to the function and check it with the is
operator:
class _NO_DEFAULT:
def __repr__(self):return "<no default>"
_NO_DEFAULT = _NO_DEFAULT()
def func(optional= _NO_DEFAULT):
if optional is _NO_DEFAULT:
print("the optional argument was not passed")
else:
print("the optional argument was:",optional)
then as long as you do not do func(_NO_DEFAULT)
you can be accurately detect whether the argument was passed or not, and unlike the accepted answer you don't have to worry about side effects of ** notation:
# these two work the same as using **
func()
func(optional=1)
# the optional argument can be positional or keyword unlike using **
func(1)
#this correctly raises an error where as it would need to be explicitly checked when using **
func(invalid_arg=7)
You should use a form of Math.Round
. Be aware that Math.Round
defaults to banker's rounding (rounding to the nearest even number) unless you specify a MidpointRounding
value. If you don't want to use banker's rounding, you should use Math.Round(decimal d, int decimals, MidpointRounding mode)
, like so:
Math.Round(pay, 2, MidpointRounding.AwayFromZero); // .005 rounds up to 0.01
Math.Round(pay, 2, MidpointRounding.ToEven); // .005 rounds to nearest even (0.00)
Math.Round(pay, 2); // Defaults to MidpointRounding.ToEven
I struggled with a similar problem for hours. It then turned out that jQuery was included twice, once by the program that I was adding a jQuery function to and once by our in-house debugger.
Or if you're using dotnet Core,
add to your .csproj file
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
</ItemGroup>
And
dotnet restore
My problem was in the config file of the domain:
the public folder of my project was created in /home/vagrant/Code/demo/public
the config file of the domain (for me /etc/nginx/sites-available/demo.app) had configured: "/home/vagrant/Code/Laravel/public" instead of "/home/vagrant/Code/demo/public".
Now it is working perfect.
Maybe you need extend()
i=[1,3,5,7]
j=[]
j.extend(i)
The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.
I think ADTC's solution is better, but mine's also works.
Here is the other solution I found
select p.name
from person p
where instr(p.name,chr(8211)) > 0; --contains the character chr(8211)
--at least 1 time
Thank you.
This is all you need.
rsync -e ssh file host:/directory/.
You can make Liquinaut's answer responsive to window size changes by adding a callback that sets the height back to auto.
$("#first").animate({height: $("#first").get(0).scrollHeight}, 1000, function() {$("#first").css({height: "auto"});});
The environment variable to set is MAVEN_OPTS
, for example MAVEN_OPTS=-Xmx1024m
. The maxmem
configuration in the pom only applies when you set the compiler plugin to fork javac
into a new JVM. Otherwise the plugin runs inside the same VM as Maven and thus within the memory passed on the command line via the MAVEN_OPTS
.
To set MAVEN_OPTS under Windows 7:
-Xmx1024m
(or more)Open a new command window and run mvn
.
Here is a lattice version:
library(lattice)
eq<-function(x) {x*x}
X<-1:1000
xyplot(eq(X)~X,type="l")
I ran into a similar problem recently. The solution for me was to re-create the colletion. Let me try to demonstrate:
var $element = $(selector);
$element.append(content);
// This Doesn't work, because $element still contains old structure:
$element.fooBar();
// This should work: the collection is re-created with the new content:
$(selector).fooBar();
Hope this helps!
Have you tried this?:
$string = '';
while($row = mysql_fetch_array($result))
{
//this will combine all the results into one string
$string .= '<img src="'.$row['name'].'" />
<div>'.$row['name'].'</div>
<div>'.$row['title'].'</div>
<div>'.$row['description'].'</div>
<div>'.$row['link'].'</div><br />';
//or this will add the individual result in an array
/*
$yourHtml[] = $row;
*/
}
then you echo the $tring to the place you want it to be
<div id="place_here">
<?php echo $string; ?>
<?php
//or
/*
echo '<img src="'.$yourHtml[0]['name'].'" />;//change the index, or you just foreach loop it
*/
?>
</div>
It's possible to "natively" select by value:
dropdownlist.select(1);
In my case the issue revealed to be chrome blocking the CORS request from localhost:4200 to facebook api website. Running Chrome with this setting: "YOUR_PATH_TO_CHROME\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chrome worked like a charm while developing. Even with no localhost added to facebook app's settings.
Samsung Note 8 User here - all i had to do was
adb devices
in the adb prompt.chrome://inspect/#devices
and the device shows up.After that i got a message on my phone and chrome recognized the phone.
A simple fix for this is to install the Google Cast extension. If you don't have a Chromecast, or don't want to use the extension, no problem; just don't use the extension.
You need to use Power Manager to acquire a wake lock in your application.
Most probably you are interested in a FULL_WAKE_LOCK:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
wl.acquire();
....
wl.release();
A solution that I like, because it keeps rspec output separate from actual rails log output, is to do the following:
$ tail -f $RAILS_APP_DIR/logs/test.log
or tail -f $RAILS_APP_DIR\logs\test.log
for Window usersIf you are running a multi-pane terminal like iTerm, this becomes even more fun and you have rspec
and the test.log
output side by side.
Here is an implementation based on the accepted answer:
/**_x000D_
* Returns the name of an object's type._x000D_
*_x000D_
* If the input is undefined, returns "Undefined"._x000D_
* If the input is null, returns "Null"._x000D_
* If the input is a boolean, returns "Boolean"._x000D_
* If the input is a number, returns "Number"._x000D_
* If the input is a string, returns "String"._x000D_
* If the input is a named function or a class constructor, returns "Function"._x000D_
* If the input is an anonymous function, returns "AnonymousFunction"._x000D_
* If the input is an arrow function, returns "ArrowFunction"._x000D_
* If the input is a class instance, returns "Object"._x000D_
*_x000D_
* @param {Object} object an object_x000D_
* @return {String} the name of the object's class_x000D_
* @see <a href="https://stackoverflow.com/a/332429/14731">https://stackoverflow.com/a/332429/14731</a>_x000D_
* @see getFunctionName_x000D_
* @see getObjectClass _x000D_
*/_x000D_
function getTypeName(object)_x000D_
{_x000D_
const objectToString = Object.prototype.toString.call(object).slice(8, -1);_x000D_
if (objectToString === "Function")_x000D_
{_x000D_
const instanceToString = object.toString();_x000D_
if (instanceToString.indexOf(" => ") != -1)_x000D_
return "ArrowFunction";_x000D_
const getFunctionName = /^function ([^(]+)\(/;_x000D_
const match = instanceToString.match(getFunctionName);_x000D_
if (match === null)_x000D_
return "AnonymousFunction";_x000D_
return "Function";_x000D_
}_x000D_
// Built-in types (e.g. String) or class instances_x000D_
return objectToString;_x000D_
};_x000D_
_x000D_
/**_x000D_
* Returns the name of a function._x000D_
*_x000D_
* If the input is an anonymous function, returns ""._x000D_
* If the input is an arrow function, returns "=>"._x000D_
*_x000D_
* @param {Function} fn a function_x000D_
* @return {String} the name of the function_x000D_
* @throws {TypeError} if {@code fn} is not a function_x000D_
* @see getTypeName_x000D_
*/_x000D_
function getFunctionName(fn)_x000D_
{_x000D_
try_x000D_
{_x000D_
const instanceToString = fn.toString();_x000D_
if (instanceToString.indexOf(" => ") != -1)_x000D_
return "=>";_x000D_
const getFunctionName = /^function ([^(]+)\(/;_x000D_
const match = instanceToString.match(getFunctionName);_x000D_
if (match === null)_x000D_
{_x000D_
const objectToString = Object.prototype.toString.call(fn).slice(8, -1);_x000D_
if (objectToString === "Function")_x000D_
return "";_x000D_
throw TypeError("object must be a Function.\n" +_x000D_
"Actual: " + getTypeName(fn));_x000D_
}_x000D_
return match[1];_x000D_
}_x000D_
catch (e)_x000D_
{_x000D_
throw TypeError("object must be a Function.\n" +_x000D_
"Actual: " + getTypeName(fn));_x000D_
}_x000D_
};_x000D_
_x000D_
/**_x000D_
* @param {Object} object an object_x000D_
* @return {String} the name of the object's class_x000D_
* @throws {TypeError} if {@code object} is not an Object_x000D_
* @see getTypeName_x000D_
*/_x000D_
function getObjectClass(object)_x000D_
{_x000D_
const getFunctionName = /^function ([^(]+)\(/;_x000D_
const result = object.constructor.toString().match(getFunctionName)[1];_x000D_
if (result === "Function")_x000D_
{_x000D_
throw TypeError("object must be an Object.\n" +_x000D_
"Actual: " + getTypeName(object));_x000D_
}_x000D_
return result;_x000D_
};_x000D_
_x000D_
_x000D_
function UserFunction()_x000D_
{_x000D_
}_x000D_
_x000D_
function UserClass()_x000D_
{_x000D_
}_x000D_
_x000D_
let anonymousFunction = function()_x000D_
{_x000D_
};_x000D_
_x000D_
let arrowFunction = i => i + 1;_x000D_
_x000D_
console.log("getTypeName(undefined): " + getTypeName(undefined));_x000D_
console.log("getTypeName(null): " + getTypeName(null));_x000D_
console.log("getTypeName(true): " + getTypeName(true));_x000D_
console.log("getTypeName(5): " + getTypeName(5));_x000D_
console.log("getTypeName(\"text\"): " + getTypeName("text"));_x000D_
console.log("getTypeName(userFunction): " + getTypeName(UserFunction));_x000D_
console.log("getFunctionName(userFunction): " + getFunctionName(UserFunction));_x000D_
console.log("getTypeName(anonymousFunction): " + getTypeName(anonymousFunction));_x000D_
console.log("getFunctionName(anonymousFunction): " + getFunctionName(anonymousFunction));_x000D_
console.log("getTypeName(arrowFunction): " + getTypeName(arrowFunction));_x000D_
console.log("getFunctionName(arrowFunction): " + getFunctionName(arrowFunction));_x000D_
//console.log("getFunctionName(userClass): " + getFunctionName(new UserClass()));_x000D_
console.log("getTypeName(userClass): " + getTypeName(new UserClass()));_x000D_
console.log("getObjectClass(userClass): " + getObjectClass(new UserClass()));_x000D_
//console.log("getObjectClass(userFunction): " + getObjectClass(UserFunction));_x000D_
//console.log("getObjectClass(userFunction): " + getObjectClass(anonymousFunction));_x000D_
//console.log("getObjectClass(arrowFunction): " + getObjectClass(arrowFunction));_x000D_
console.log("getTypeName(nativeObject): " + getTypeName(navigator.mediaDevices.getUserMedia));_x000D_
console.log("getFunctionName(nativeObject): " + getFunctionName(navigator.mediaDevices.getUserMedia));
_x000D_
We only use the constructor property when we have no other choice.
If you trying to fit the content according to the forms than the following will help. It helps me while I was trying to fit the content on the form to fit when ever the forms were resized.
this.contents.Size = new Size(this.ClientRectangle.Width, this.ClientRectangle.Height);
See also this previous answer which recommends the not
keyword
How to check if a list is empty in Python?
It generalizes to more than just lists:
>>> a = ""
>>> not a
True
>>> a = []
>>> not a
True
>>> a = 0
>>> not a
True
>>> a = 0.0
>>> not a
True
>>> a = numpy.array([])
>>> not a
True
Notably, it will not work for "0" as a string because the string does in fact contain something - a character containing "0". For that you have to convert it to an int:
>>> a = "0"
>>> not a
False
>>> a = '0'
>>> not int(a)
True
You can compare files from the explorer either from the working files section or the folder section. You can also trigger the global compare action from the command palette.
Even after @Mickey Perlstein's answer and his 3 hours of detective work, it still took me a few more minutes to apply this to my own mess. In case anyone else is like me and needs a little more help, here's what was going on in my situation.
Initial GeoJsonResponse class:
from pyexample.responses import Response
class GeoJsonResponse(Response):
def __init__(self, geo_json_data):
Looks fine. No problems until you try to debug the thing, which is when you get a bunch of seemingly vague error messages like this:
from pyexample.responses import GeoJsonResponse ..\pyexample\responses\GeoJsonResponse.py:12: in (module) class GeoJsonResponse(Response):
E TypeError: module() takes at most 2 arguments (3 given)
=================================== ERRORS ====================================
___________________ ERROR collecting tests/test_geojson.py ____________________
test_geojson.py:2: in (module) from pyexample.responses import GeoJsonResponse ..\pyexample\responses \GeoJsonResponse.py:12: in (module)
class GeoJsonResponse(Response): E TypeError: module() takes at most 2 arguments (3 given)
ERROR: not found: \PyExample\tests\test_geojson.py::TestGeoJson::test_api_response
C:\Python37\lib\site-packages\aenum__init__.py:163
(no name 'PyExample\ tests\test_geojson.py::TestGeoJson::test_api_response' in any of [])
The errors were doing their best to point me in the right direction, and @Mickey Perlstein's answer was dead on, it just took me a minute to put it all together in my own context:
I was importing the module:
from pyexample.responses import Response
when I should have been importing the class:
from pyexample.responses.Response import Response
Hope this helps someone. (In my defense, it's still pretty early.)
To find all files modified in the last 24 hours use the one below. The -1 here means changed 1 day or less ago.
find . -mtime -1 -ls
If this is happening in nodejs, it is due to the older version of nodejs. Update node by using,
1) Clear NPM's cache:
sudo npm cache clean -f
2) Install a little helper called 'n'
sudo npm install -g n
3) Install latest stable NodeJS version
sudo n stable
Update nodejs instructions taken from, https://stackoverflow.com/a/19584407/698072
You can pass program arguments on the command line and get them in your Java app like this:
public static void main(String[] args) {
String pathToXml = args[0];
....
}
Alternatively you pass a system property by changing the command line to:
java -Dpath-to-xml=enwiki-20111007-pages-articles.xml -jar wiki2txt
and your main class to:
public static void main(String[] args) {
String pathToXml = System.getProperty("path-to-xml");
....
}
Since AmazonDynamoDBClient(credentials) is deprecated i use this.
init {
val cp= AWSStaticCredentialsProvider(BasicAWSCredentials(ACCESS_KEY, SECRET_KEY))
val client = AmazonDynamoDBClientBuilder.standard().withCredentials(cp).withRegion(Regions.US_EAST_1).build()
dynamoDB = DynamoDB(client)
}
I saw that everybody's posting their takes on the problem despite the fact that few top answers already include all the necessary info to tailor for the specific use case.
And since I want to be hip as well - here's my unnecessary and a bit cumbersome solution, which is:
a) Readable (I hope!)
b) Easily customizable
c) Doesn't print any zeroes
drum roll
function durationToDDHHMMSSMS(durms) {
if (!durms) return "??";
var HHMMSSMS = new Date(durms).toISOString().substr(11, 12);
if (!HHMMSSMS) return "??";
var HHMMSS = HHMMSSMS.split(".")[0];
if (!HHMMSS) return "??";
var MS = parseInt(HHMMSSMS.split(".")[1],10);
var split = HHMMSS.split(":");
var SS = parseInt(split[2],10);
var MM = parseInt(split[1],10);
var HH = parseInt(split[0],10);
var DD = Math.floor(durms/(1000*60*60*24));
var string = "";
if (DD) string += ` ${DD}d`;
if (HH) string += ` ${HH}h`;
if (MM) string += ` ${MM}m`;
if (SS) string += ` ${SS}s`;
if (MS) string += ` ${MS}ms`;
return string;
},
Note that this code uses ES6 template strings, I'm sure that such a smarty-pants as you are will have no difficulties replacing them with regular strings if required.
Projection: what ever typed in select clause i.e, 'column list' or '*' or 'expressions' that becomes under projection.
*selection:*what type of conditions we are applying on that columns i.e, getting the records that comes under selection.
For example:
SELECT empno,ename,dno,job from Emp
WHERE job='CLERK';
in the above query the columns "empno,ename,dno,job" those comes under projection, "where job='clerk'" comes under selection
A practical example when name() and toString() make sense to be different is a pattern where single-valued enum is used to define a singleton. It looks surprisingly at first but makes a lot of sense:
enum SingletonComponent {
INSTANCE(/*..configuration...*/);
/* ...behavior... */
@Override
String toString() {
return "SingletonComponent"; // better than default "INSTANCE"
}
}
In such case:
SingletonComponent myComponent = SingletonComponent.INSTANCE;
assertThat(myComponent.name()).isEqualTo("INSTANCE"); // blah
assertThat(myComponent.toString()).isEqualTo("SingletonComponent"); // better
Traversal over the large map entrySet()
is much better than the keySet()
. Check this tutorial how they optimise the traversal over the large object with the help of entrySet(
) and how it helps for performance tuning.
I think the simplest way to accomplish the layout with bootstrap is like this:
<section>
<div class="container">
<div class="row">
<div align="center">
<div style="max-width: 200px; background-color: blueviolet;">
<div>
<h1 style="color: white;">Content goes here</h1>
</div>
</div>
</div>
</div>
</div>
all I did was to add layers of divs that allowed me to center the div, but since I am not using percentages, you need to specify the max-width of the div to be center.
You can use this same method to center more than one column, you just need to add more div layers:
<div class="container">
<div class="row">
<div align="center">
<div style="max-width: 400px; background-color: blueviolet;">
<div class="col-md-12 col-sm-12 col-xs-12" style="background-color: blueviolet;">
<div class="col-md-8 col-sm-8 col-xs-12" style="background-color: darkcyan;">
<h1 style="color: white;">Some content</h1>
</div>
<div class="col-md-4 col-sm-4 col-xs-12" style="background-color: blue;">
<p style="color: white;">More content</p>
</div>
</div>
</div>
</div>
</div>
</div>
Note: that I added a div with column 12 for md, sm and xs, if you don't do this the first div with background color (in this case "blueviolet") will collapse, you will be able to see the child divs, but not the background color.
Uninitialized non-static members will contain random data. Actually, they will just have the value of the memory location they are assigned to.
Of course for object parameters (like string
) the object's constructor could do a default initialization.
In your example:
int *ptr; // will point to a random memory location
string name; // empty string (due to string's default costructor)
string *pname; // will point to a random memory location
string &rname; // it would't compile
const string &crname; // it would't compile
int age; // random value
In my case, this was caused by custom manifest entries added by the maven-jar-plugin.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestEntries>
<git>${buildNumber}</git>
<build-time>${timestamp}</build-time>
</manifestEntries>
</archive>
</configuration>
</plugin>
Removing the following entries fixed the problem
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
I couldn't find any other full solutions so I thought I would post mine. This may be a bit of a hack, but it resolved the issue to the above problem:
public void login(HttpServletRequest request, String userName, String password)
{
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userName, password);
// Authenticate the user
Authentication authentication = authenticationManager.authenticate(authRequest);
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
// Create a new session and add the security context.
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
}
As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_user_connections
maximum range: 4,294,967,295 (e.g. 2**32 - 1)
You'd probably run out of memory, file handles, and network sockets, on your server long before you got anywhere close to that limit.
I installed WAMPServer 2.5 (32-bit) and also encountered an oci_connect error. I also had Oracle 11g client (32-bit) installed. The common fix I read in other posts was to alter the php.ini file in your C:\wamp\bin\php\php5.5.12 directory, however this never worked for me. Maybe I misunderstood, but I found that if you alter the php.ini file in the C:\wamp\bin\apache\apache2.4.9 directory instead, you will get the results you want. The only thing I altered in the apache php.ini file was remove the semicolon to extension=php_oci8_11g.dll
in order to enable it. I then restarted all the services and it now works! I hope this works for you.
Give this style to the <p>
tag.
p {
word-break: break-all;
white-space: normal;
}
You can do it with a LINQ like solution instead of a regular expression:
string input = "123- abcd33";
string chars = new String(input.Where(c => c != '-' && (c < '0' || c > '9')).ToArray());
A quick performance test shows that this is about five times faster than using a regular expression.
here is the working fiddle which works fine in IE8 using jquery MAP function
http://jsfiddle.net/533135/Cj4j7/
json.HOMES = $.map(json.HOMES, function(val, key) {
if (Number(val.price) <= 1000
&& Number(val.sqft) >= 500
&& Number(val.num_of_beds) >=2
&& Number(val.num_of_baths ) >= 2.5)
return val;
});
I know this question is old, but I stumbled upon it looking for a pythonic way to get current domain.
def myview(request):
domain = request.build_absolute_uri('/')[:-1]
# that will build the complete domain: http://foobar.com
UTF-8 is going to be the most space efficient unless a majority of the characters are from the CJK (Chinese, Japanese, and Korean) character space.
UTF-32 is best for random access by character offset into a byte-array.
So, Process you should follow to undo scaffolding in rails 4. Run Command as below:
rails d scaffold FooBar
rake db:rollback
if you_had_run_rake db:migrate
after creating above scaffold?That's it!
Cheers!
What could be easier than something like this:
import tempfile
for i in range(400):
with tempfile.TemporaryFile() as tf:
for j in range(1000):
tf.write('Line {} of file {}'.format(j,i))
That creates 400 temp files and writes 1000 lines to each temp file. It executes in less than 1/2 second on my unremarkable machine. Each temp file of the total is created and deleted as the context manager opens and closes in this case. It is fast, secure, and cross platform.
Using tempfile is a lot better than trying to reinvent it.
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollingFinished(scrollView: scrollView)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate {
//didEndDecelerating will be called for sure
return
}
scrollingFinished(scrollView: scrollView)
}
func scrollingFinished(scrollView: UIScrollView) {
// Your code
}
Replacing the border-color with outline-color should work.
What really made it all click for me was this presentation by Domenic Denicola.
In a github gist, he gave the description I like most, it's very concise:
The point of promises is to give us back functional composition and error bubbling in the async world.
In other word, promises are a way that lets us write asynchronous code that is almost as easy to write as if it was synchronous.
Consider this example, with promises:
getTweetsFor("domenic") // promise-returning async function
.then(function (tweets) {
var shortUrls = parseTweetsForUrls(tweets);
var mostRecentShortUrl = shortUrls[0];
return expandUrlUsingTwitterApi(mostRecentShortUrl); // promise-returning async function
})
.then(doHttpRequest) // promise-returning async function
.then(
function (responseBody) {
console.log("Most recent link text:", responseBody);
},
function (error) {
console.error("Error with the twitterverse:", error);
}
);
It works as if you were writing this synchronous code:
try {
var tweets = getTweetsFor("domenic"); // blocking
var shortUrls = parseTweetsForUrls(tweets);
var mostRecentShortUrl = shortUrls[0];
var responseBody = doHttpRequest(expandUrlUsingTwitterApi(mostRecentShortUrl)); // blocking x 2
console.log("Most recent link text:", responseBody);
} catch (error) {
console.error("Error with the twitterverse: ", error);
}
(If this still sounds complicated, watch that presentation!)
Regarding Deferred, it's a way to .resolve()
or .reject()
promises. In the Promises/B spec, it is called .defer()
. In jQuery, it's $.Deferred()
.
Please note that, as far as I know, the Promise implementation in jQuery is broken (see that gist), at least as of jQuery 1.8.2.
It supposedly implements Promises/A thenables, but you don't get the correct error handling you should, in the sense that the whole "async try/catch" functionality won't work.
Which is a pity, because having a "try/catch" with async code is utterly cool.
If you are going to use Promises (you should try them out with your own code!), use Kris Kowal's Q. The jQuery version is just some callback aggregator for writing cleaner jQuery code, but misses the point.
Regarding Future, I have no idea, I haven't seen that in any API.
Edit: Domenic Denicola's youtube talk on Promises from @Farm's comment below.
A quote from Michael Jackson (yes, Michael Jackson) from the video:
I want you to burn this phrase in your mind: A promise is an asynchronous value.
This is an excellent description: a promise is like a variable from the future - a first-class reference to something that, at some point, will exist (or happen).
Try:
mmatrix = np.zeros((nrows, ncols))
Since the shape parameter has to be an int or sequence of ints
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
Otherwise you are passing ncols
to np.zeros
as the dtype.
You probably want to add one day rather than 24 hours. Not all days have 24 hours due to (among other circumstances) daylight saving time:
strtotime('+1 day', $timestamp);
SHOW CREATE TABLE <tablename>;
Less parseable but more readable than SHOW TABLE STATUS
.
df.T.iloc[-1]
df.T.tail(1)
pd.Series(df.values[:, -1], name=df.columns[-1])
A simple example of escaping quotes in the shell:
$ echo 'abc'\''abc'
abc'abc
$ echo "abc"\""abc"
abc"abc
It's done by finishing an already-opened one ('
), placing the escaped one (\'
), and then opening another one ('
).
Alternatively:
$ echo 'abc'"'"'abc'
abc'abc
$ echo "abc"'"'"abc"
abc"abc
It's done by finishing already opened one ('
), placing a quote in another quote ("'"
), and then opening another one ('
).
More examples: Escaping single-quotes within single-quoted strings
Shouldn't you also be using the jspdf.plugin.from_html.js library? Besides the main library (jspdf.js), you must use other libraries for "special operations" (like jspdf.plugin.addimage.js for using images). Check https://github.com/MrRio/jsPDF.
You should set the src
attribute after the onload
event, f.ex:
el.onload = function() { //...
el.src = script;
You should also append the script to the DOM before attaching the onload
event:
$body.append(el);
el.onload = function() { //...
el.src = script;
Remember that you need to check readystate
for IE support. If you are using jQuery, you can also try the getScript()
method: http://api.jquery.com/jQuery.getScript/
This version builds on Robert Elliot's, but I'm not 100% sure of its efficacy.
// There are a few dependencies added by one of the Scala plugins that this cannot reach.
task downloadDependencies {
description "Pre-downloads *most* dependencies"
doLast {
configurations.getAsMap().each { name, config ->
println "Retrieving dependencies for $name"
try {
config.files
} catch (e) {
project.logger.info e.message // some cannot be resolved, silentlyish skip them
}
}
}
}
I tried putting it into configuration instead of action (by removing doLast) and it broke zinc. I worked around it, but the end result was the same with or without. So, I left it as an explicit state. It seems to work enough to reduce the dependencies that have to be downloaded later, but not eliminate them in my case. I think one of the Scala plugins adds dependencies later.
This is my customized factory providing a customized names for thread dump analyzers. Usually I just give tf=null
to reuse JVM default thread factory. This website has more advanced thread factory.
public class SimpleThreadFactory implements ThreadFactory {
private ThreadFactory tf;
private String nameSuffix;
public SimpleThreadFactory (ThreadFactory tf, String nameSuffix) {
this.tf = tf!=null ? tf : Executors.defaultThreadFactory();
this.nameSuffix = nameSuffix;
}
@Override public Thread newThread(Runnable task) {
// default "pool-1-thread-1" to "pool-1-thread-1-myapp-MagicTask"
Thread thread=tf.newThread(task);
thread.setName(thread.getName()+"-"+nameSuffix);
return thread;
}
}
- - - - -
ExecutorService es = Executors.newFixedThreadPool(4, new SimpleThreadFactory(null, "myapp-MagicTask") );
For your convenience this is a thread dump loop for debug purpose.
ThreadMXBean mxBean=ManagementFactory.getThreadMXBean();
long[] tids = mxBean.getAllThreadIds();
System.out.println("------------");
System.out.println("ThreadCount="+tids.length);
for(long tid : tids) {
ThreadInfo mxInfo=mxBean.getThreadInfo(tid);
if (mxInfo==null) {
System.out.printf("%d %s\n", tid, "Thread not found");
} else {
System.out.printf("%d %s, state=%s, suspended=%d, lockowner=%d %s\n"
, mxInfo.getThreadId(), mxInfo.getThreadName()
, mxInfo.getThreadState().toString()
, mxInfo.isSuspended()?1:0
, mxInfo.getLockOwnerId(), mxInfo.getLockOwnerName()
);
}
}
Declare in your Model with
[DataType(DataType.MultilineText)]
public string urString { get; set; }
Then in .cshtml can make use of editor as below. you can make use of @cols and @rows for TextArea size
@Html.EditorFor(model => model.urString, new { htmlAttributes = new { @class = "",@cols = 35, @rows = 3 } })
Thanks !
Platform.runLater works to prevent execution until initialization is complete. In this case, i want to refresh a list view every time I resize the window width.
Platform.runLater(() -> {
((Stage) listView.getScene().getWindow()).widthProperty().addListener((obs, oldVal, newVal) -> {
listView.refresh();
});
});
in your case
Platform.runLater(()->{
((Stage)myPane.getScene().getWindow()).setOn*whatIwant*(...);
});
Loop like
foreach (GridViewRow row in grid.Rows)
{
if (((CheckBox)row.FindControl("chkboxid")).Checked)
{
//read the label
}
}
Same think can be done using lambda function. Here I am reading the data from a xlsx file.
import pandas as pd
df = pd.read_excel("data.xlsx", sheet_name = 4)
print df
Output:
cluster Unnamed: 1 date budget actual
0 a 2014-01-01 00:00:00 11000 10000
1 a 2014-02-01 00:00:00 1200 1000
2 a 2014-03-01 00:00:00 200 100
3 b 2014-04-01 00:00:00 200 300
4 b 2014-05-01 00:00:00 400 450
5 c 2014-06-01 00:00:00 700 1000
6 c 2014-07-01 00:00:00 1200 1000
7 c 2014-08-01 00:00:00 200 100
8 c 2014-09-01 00:00:00 200 300
Sum two columns into 3rd new one.
df['variance'] = df.apply(lambda x: x['budget'] + x['actual'], axis=1)
print df
Output:
cluster Unnamed: 1 date budget actual variance
0 a 2014-01-01 00:00:00 11000 10000 21000
1 a 2014-02-01 00:00:00 1200 1000 2200
2 a 2014-03-01 00:00:00 200 100 300
3 b 2014-04-01 00:00:00 200 300 500
4 b 2014-05-01 00:00:00 400 450 850
5 c 2014-06-01 00:00:00 700 1000 1700
6 c 2014-07-01 00:00:00 1200 1000 2200
7 c 2014-08-01 00:00:00 200 100 300
8 c 2014-09-01 00:00:00 200 300 500
Same issue occurred for me, but before getting this error, my app was running. So I just did undo 2/3 times. And did changes again. And build app.app ran successfully.
Under [branch "master"]
, try adding the following to the repo's Git config file (.git/config
):
[branch "master"]
remote = origin
merge = refs/heads/master
This tells Git 2 things:
git pull
on the master branch, with no remote and branch specified, use the default remote (origin) and merge in the changes from the remote master branch.I'm not sure why this setup would've been removed from your configuration, though. You may have to follow the suggestions that other people have posted, too, but this may work (or help at least).
If you don't want to edit the config file by hand, you can use the command-line tool instead:
$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master
If you are using a third party library called apache commons-lang, the following solution can be useful:
Use StringUtils
class of apache commons-lang :
int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"
As StringUtils.leftPad()
is faster than String.format()
You want to check whether Examples exists in Range("A1").Value If it fails then to check Example right? I think mycode will work perfect. Please check.
Sub test()
Dim string1 As String, string2 As String
string1 = "Examples"
string2 = "Example"
If InStr(1, Range("A1").Value, string1) > 0 Then
x = 1
ElseIf InStr(1, Range("A1").Value, string2) > 0 Then
x = 2
End If
End Sub
Try this, it is updating the current location, and it works fine.
public void onLocationChanged(@NonNull Location location) {
//here we update the location on the map
LatLng myActualLocation = new LatLng(location.getLatitude(), location.getLongitude());
if (markerName!=null){ // marker name is declared as a gloval variable.
markerName.remove();
}
markerName = mMap.addMarker(new MarkerOptions().position(myActualLocation).title("Marker Miami").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
// mMap.addMarker(new MarkerOptions().position(myActualLocation).title("Marker Miami").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myActualLocation,18));
}
As strings are immutable another way to do this would be to turn the string into a list, which can then be indexed and modified without any slicing trickery. However, to get the list back to a string you'd have to use .join()
using an empty string.
>>> hash = '355879ACB6'
>>> hashlist = list(hash)
>>> hashlist.insert(4, '-')
>>> ''.join(hashlist)
'3558-79ACB6'
I am not sure how this compares as far as performance, but I do feel it's easier on the eyes than the other solutions. ;-)
Simple and Nice. You don't have to change your views. Bjax handles all your links. Check this out: Bjax
Usage:
<script src="bjax.min.js" type="text/javascript"></script>
<link href="bjax.min.css" rel="stylesheet" type="text/css" />
Finally, include this in the HEAD of your html:
$('a').bjax();
For more settings, checkout demo here: Bjax Demo
I found good solution for any format of request body.
I tested for application/x-www-form-urlencoded
and application/json
both worked very well. Problem of ContentCachingRequestWrapper
that is designed only for x-www-form-urlencoded
request body, but not work with e.g. json. I found solution for json link. It had trouble that it didn't support x-www-form-urlencoded
.
I joined both in my code:
import org.apache.commons.io.IOUtils;
import org.springframework.web.util.ContentCachingRequestWrapper;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class MyContentCachingRequestWrapper extends ContentCachingRequestWrapper {
private byte[] body;
public MyContentCachingRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
super.getParameterMap(); // init cache in ContentCachingRequestWrapper
body = super.getContentAsByteArray(); // first option for application/x-www-form-urlencoded
if (body.length == 0) {
try {
body = IOUtils.toByteArray(super.getInputStream()); // second option for other body formats
} catch (IOException ex) {
body = new byte[0];
}
}
}
public byte[] getBody() {
return body;
}
@Override
public ServletInputStream getInputStream() {
return new RequestCachingInputStream(body);
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream(), getCharacterEncoding()));
}
private static class RequestCachingInputStream extends ServletInputStream {
private final ByteArrayInputStream inputStream;
public RequestCachingInputStream(byte[] bytes) {
inputStream = new ByteArrayInputStream(bytes);
}
@Override
public int read() throws IOException {
return inputStream.read();
}
@Override
public boolean isFinished() {
return inputStream.available() == 0;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readlistener) {
}
}
}
You can't do it with pure HTML, but this jQuery plugin will let you: https://github.com/bradjasper/jQuery-Placeholder-Newlines
Okay I found the correct answer to this issue here
Here are the steps:
Now in the top row of your filtered data (just below the header) enter the following code:
=MAX($"Your Column Letter"$1:"Your Column Letter"$"The current row for the filter - 1") + 1
Ex:
=MAX($A$1:A26)+1
Which would be applied starting at cell A27.
Hold Ctrl and press enter.
Note this only works in a range, not in a table!
I use Spring Boot, my solution to the problem was
"src/main/resources/myfile.extension"
Hope it helps someone.
Create a .c file containing just the line:
_MSC_VER
or
CompilerVersion=_MSC_VER
then pre-process with
cl /nologo /EP <filename>.c
It is easy to parse the output.
You may use EmptyDataText
as shown below:
<asp:GridView ID="_gridView" RunAt="server" AutoGenerateColumns="false"
EmptyDataText="No entries found.">
It does not show headers, it renders your message "No entries found." instead.
NOTE if you are using python 3.x:
request.FILES
is a multivalue dictionary like object that keeps the files uploaded through an upload file button. Say in your html code the name of the button (type="file") is "myfile" so "myfile" will be the key in this dictionary. If you uploaded one file, then the value for this key will be only one and if you uploaded multiple files, then you will have multiple values for that specific key. If you use request.FILES['myfile']
you will get the first or last value (I cannot say for sure). This is fine if you only uploaded one file, but if you want to get all files you should do this:
list=[] #myfile is the key of a multi value dictionary, values are the uploaded files
for f in request.FILES.getlist('myfile'): #myfile is the name of your html file button
filename = f.name
list.append(filename)
of course one can squeeze the whole thing in one line, but this is easy to understand
use code like this:
new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709")
instead of "9D2B0228-4D0D-4C23-8B49-01A698857709" you can set your string value
Here is the example:
SQL> set define off;
SQL> select * from dual where dummy='&var';
no rows selected
SQL> set define on
SQL> /
Enter value for var: X
old 1: select * from dual where dummy='&var'
new 1: select * from dual where dummy='X'
D
-
X
With set define off
, it took a row with &var
value, prompted a user to enter a value for it and replaced &var
with the entered value (in this case, X
).
Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.
This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
strXls, True, "temp!"
You should never use the unidirectional @OneToMany
annotation because:
Now, in your first example, both sides are owning the association, and this is bad.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
Swift 5
you need to use UINib method to register cell in viewDidLoad
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
//register table view cell
tableView.register(UINib.init(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomTableViewCell")
}
From the TypeScript site: https://github.com/Microsoft/TypeScript/issues/6471
The recommended practice is to write the props type as {children?: any}
That worked for me. The child node can be many different things, so explicit typing can miss cases.
There's a longer discussion on the followup issue here: https://github.com/Microsoft/TypeScript/issues/13618, but the any approach still works.
try {
JSONObject jsonObject = new JSONObject(response.body().string());
System.out.println(jsonObject);
} catch (JSONException | IOException e ) {
e.printStackTrace();
}
No. When your input type is submit, you should have an onsubmit
event declared in the markup and then do the changes you want. Meaning, have an onsubmit
defined in your form tag.
Otherwise change the input type to a button and then define an onclick
event for that button.
You can use this query:
SELECT
ROUTINE_CATALOG AS DatabaseName ,
ROUTINE_SCHEMA AS SchemaName,
SPECIFIC_NAME AS SPName ,
ROUTINE_DEFINITION AS SPBody ,
CREATED AS CreatedDate,
LAST_ALTERED AS LastModificationDate
FROM INFORMATION_SCHEMA.ROUTINES
WHERE
(ROUTINE_DEFINITION LIKE '%%')
AND
(ROUTINE_TYPE='PROCEDURE')
AND
(SPECIFIC_NAME LIKE '%AssessmentToolDegreeDel')
As you can see, you can do search inside the body of Stored Procedure also.
If you are trying to cache the tiles that Google serves, that may be a violation of Google's Terms of Service (unless, under certain circumstances, if you've purchased their enterprise Maps API Premier). That's why gmapcatcher has it crossed off their list. See http://code.google.com/p/gmapcatcher/issues/detail?id=210.
At the gmapcatcher URL above, you will also find a shell script that can download tiles (or so its author says).
There are also other projects that try to make Google Maps available offline:
http://code.google.com/p/ogmaps/
http://code.google.com/p/gmapoffline/
Lastly, if Google Earth can meet your needs, then you can use that. Offline usage of Google Earth requires a Google Earth Enterprise license according to http://www.google.com/permissions/geoguidelines.html.
Note that the preceding page also says: "You may not scrape or otherwise export Content from Google Maps or Earth or save it for offline use." So if you try to cache tiles, that will almost certainly be considered (by Google, anyway) a violation of the Terms of Service.
!
is non-null assertion operator (post-fix expression) - it just saying to type checker that you're sure that a
is not null
or undefined
.
the operation
a!
produces a value of the type ofa
withnull
andundefined
excluded
Optional chaining finally made it to typescript (3.7)
The optional chaining operator
?.
permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The?.
operator functions similarly to the.
chaining operator, except that instead of causing an error if a reference is nullish (null
orundefined
), the expression short-circuits with a return value ofundefined
. When used with function calls, it returnsundefined
if the given function does not exist.
Syntax:
obj?.prop // Accessing object's property
obj?.[expr] // Optional chaining with expressions
arr?.[index] // Array item access with optional chaining
func?.(args) // Optional chaining with function calls
Pay attention:
Optional chaining is not valid on the left-hand side of an assignment
const object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment
Open up a command prompt then type...
netstat -a
i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; --- i got the following error..`syntax error at or near “-”
The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.
# GRANT SELECT ON table_name TO "walters-ro";
That solved the problem.
You can create a custom alertDialog and use a xml layout. in the layout, you can set the background color and textcolor.
Something like this:
Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
LayoutInflater inflater = (LayoutInflater)ActivityName.this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_layout,(ViewGroup)findViewById(R.id.layout_root));
dialog.setContentView(view);
TL;DR: Tell Chrome that this is a new password input and it won't provide old ones as autocomplete suggestions:
<input type="password" name="password" autocomplete="new-password">
autocomplete="off"
doesn't work due to a design decision - lots of research shows that users have much longer and harder to hack passwords if they can store them in a browser or password manager.
The specification for autocomplete
has changed, and now supports various values to make login forms easy to auto complete:
<!-- Auto fills with the username for the site, even though it's email format -->
<input type="email" name="email" autocomplete="username">
<!-- current-password will populate for the matched username input -->
<input type="password" autocomplete="current-password" />
If you don't provide these Chrome still tries to guess, and when it does it ignores autocomplete="off"
.
The solution is that autocomplete
values also exist for password reset forms:
<label>Enter your old password:
<input type="password" autocomplete="current-password" name="pass-old" />
</label>
<label>Enter your new password:
<input type="password" autocomplete="new-password" name="pass-new" />
</label>
<label>Please repeat it to be sure:
<input type="password" autocomplete="new-password" name="pass-repeat" />
</label>
You can use this autocomplete="new-password"
flag to tell Chrome not to guess the password, even if it has one stored for this site.
Chrome can also manage passwords for sites directly using the credentials API, which is a standard and will probably have universal support eventually.
I have tried this with and without the WRITE_INTERNAL_STORAGE permission.
There is no WRITE_INTERNAL_STORAGE
permission in Android.
How do I create this file for writing?
You don't, except perhaps on a rooted device, if your app is running with superuser privileges. You are trying to write to the root of internal storage, which apps do not have access to.
Please use the version of the FileOutputStream
constructor that takes a File
object. Create that File
object based off of some location that you can write to, such as:
getFilesDir()
(called on your Activity
or other Context
)getExternalFilesDir()
(called on your Activity
or other Context
)The latter will require WRITE_EXTERNAL_STORAGE
as a permission.
Is there an easier way than writing it to a file then reading from it again?
You can temporarily put it in a static data member.
because many people don't have SD card slots
"SD card slots" are irrelevant, by and large. 99% of Android device users will have external storage -- the exception will be 4+ year old devices where the user removed their SD card. Devices manufactured since mid-2010 have external storage as part of on-board flash, not as removable media.
If you came here looking for an answer to this question but not exactly the way the OP meant, ie how do you get multi-line CMD to work in a single line, I have a sort of dangerous answer for you.
Trying to use this with things that actually use piping, like say findstr
is quite problematic. The same goes for dealing with else
s. But if you just want a multi-line conditional command to execute directly from CMD and not via a batch file, this should do work well.
Let's say you have something like this in a batch that you want to run directly in command prompt:
@echo off
for /r %%T IN (*.*) DO (
if /i "%%~xT"==".sln" (
echo "%%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file
echo Dumping SLN file contents
type "%%~T"
)
)
Now, you could use the line-continuation carat (^
) and manually type it out like this, but warning, it's tedious and if you mess up you can learn the joy of typing it all out again.
Well, it won't work with just ^
thanks to escaping mechanisms inside of parentheses shrug At least not as-written. You actually would need to double up the carats like so:
@echo off ^
More? for /r %T IN (*.sln) DO (^^
More? if /i "%~xT"==".sln" (^^
More? echo "%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file^^
More? echo Dumping SLN file contents^^
More? type "%~T"))
Instead, you can be a dirty sneaky scripter from the wrong side of the tracks that don't need no carats by swapping them out for a single pipe (|
) per continuation of a loop/expression:
@echo off
for /r %T IN (*.sln) DO if /i "%~xT"==".sln" echo "%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file | echo Dumping SLN file contents | type "%~T"
I find solution that instead of using ListBox I used ListView.It allows to change list items BackColor.
private void listView1_Refresh()
{
for (int i = 0; i < listView1.Items.Count; i++)
{
listView1.Items[i].BackColor = Color.Red;
for (int j = 0; j < existingStudents.Count; j++)
{
if (listView1.Items[i].ToString().Contains(existingStudents[j]))
{
listView1.Items[i].BackColor = Color.Green;
}
}
}
}
When you are using Google Chrome you can use/abuse the Google Filesystem API
for this. Here you can create a file with a specified name and write the content of a blob to it. Then you can return the result to the user.
I have not found a good way for Firefox yet; probably a small piece of Flash like downloadify
is required to name a blob.
IE10 has a msSaveBlob()
function in the BlobBuilder
.
Maybe this is more for downloading a blob, but it is related.
The default installation of the multi-architecture (x86, x64) version of SQLite from NuGet exhibits the behavior that you described. If you would like to load the correct version for actual architecture that the .NET runtime chose to run your application on your machine, then you can give the DLL loader a hint about where to locate the correct library as follows:
Add a declaration for the kernel32.dll function call to SetDLLDirectory() before your Program.Main():
[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
[return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
static extern bool SetDllDirectory(string lpPathName);
Then use your own method for determining the correct subdirectory to find the architecture specific version of 'SQLite.Interop.dll'. I use the following code:
[STAThread]
static void Main()
{
int wsize = IntPtr.Size;
string libdir = (wsize == 4)?"x86":"x64";
string appPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
SetDllDirectory(System.IO.Path.Combine(appPath, libdir));
You can update the existing package-lock.json file instead of creating a new one. Just change the version number to a different one.
{ "name": "theme","version": "1.0.1", "description": "theme description"}
First Create an Application on Instagram and get Client Id for your application
http://instagram.com/developer/
Now just copy paste following Url into browser window by replacing your Username and your Client Id https://api.instagram.com/v1/users/search?q=[Your-username]&client_id=[Your-Client-Id]
you will get a Json Result containing General Information about your account along with your Numeric user Id
You are trying to assign to literal integer values. 1
, 2
, etc. are not valid names; they are only valid integers:
>>> 1
1
>>> 1 = 'something'
File "<stdin>", line 1
SyntaxError: can't assign to literal
You probably want to use a list or dictionary instead:
names = []
for i in range(1, 6):
name = input("Please enter name {}:".format(i))
names.append(name)
Using a list makes it much easier to pick a random value too:
winner = random.choice(names)
print('Well done {}. You are the winner!'.format(winner))
I think the most efficient way is to wrap the touchableOpacity with a view and add the prop pointerEvents with a style condition.
<View style={this.state.disabled && commonStyles.buttonDisabled}
pointerEvents={this.state.disabled ? "none" : "auto"}>
<TouchableOpacity
style={styles.connectButton}>
<Text style={styles.connectButtonText}">CONNECT </Text>
</TouchableOpacity>
</View>
CSS:
buttonDisabled: {
opacity: 0.7
}
First download the JavaMail API and make sure the relevant jar files are in your classpath.
Here's a full working example using GMail.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Main {
private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "********"; // GMail password
private static String RECIPIENT = "[email protected]";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
Naturally, you'll want to do more in the catch
blocks than print the stack trace as I did in the example code above. (Remove the catch
blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.)
Thanks to @jodonnel and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.
Old Q, but for posterity...it also also happens (.NET Core 2.1) if you have a self-referencing navigation property ("Parent" or "Children" of the same type) but the Id property name isn't what EF expects. That is, I had an "Id" property on my class called WorkflowBase
, and it had an array of related child steps, which were also of type WorkflowBase
, and it kept trying to associate them with a non-existent "WorkflowBaseId" (the name i suppose it prefers as a natural/conventional default). I had to explicitly configure it using HasMany()
, WithOne()
, and HasConstraintName()
to tell it how to traverse. But I spent a few hours thinking the problem was in 'locally' mapping the object's primary key, which i attempted to fix a bunch of different ways but which was probably always working.
You can update progress bar only from ProgressChanged
or RunWorkerCompleted
event handlers as these are synchronized with the UI thread.
The basic idea is. Thread.Sleep
just simulates some work here. Replace it with your real routing call.
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.WorkerReportsProgress = true;
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
First, keep in mind that, in its precise definition, a module is an object in the memory of a Python interpreter, often created by reading one or more files from disk. While we may informally call a disk file such as a/b/c.py
a "module," it doesn't actually become one until it's combined with information from several other sources (such as sys.path
) to create the module object.
(Note, for example, that two modules with different names can be loaded from the same file, depending on sys.path
and other settings. This is exactly what happens with python -m my.module
followed by an import my.module
in the interpreter; there will be two module objects, __main__
and my.module
, both created from the same file on disk, my/module.py
.)
A package is a module that may have submodules (including subpackages). Not all modules can do this. As an example, create a small module hierarchy:
$ mkdir -p a/b
$ touch a/b/c.py
Ensure that there are no other files under a
. Start a Python 3.4 or later interpreter (e.g., with python3 -i
) and examine the results of the following statements:
import a
a ? <module 'a' (namespace)>
a.b ? AttributeError: module 'a' has no attribute 'b'
import a.b.c
a.b ? <module 'a.b' (namespace)>
a.b.c ? <module 'a.b.c' from '/home/cjs/a/b/c.py'>
Modules a
and a.b
are packages (in fact, a certain kind of package called a "namespace package," though we wont' worry about that here). However, module a.b.c
is not a package. We can demonstrate this by adding another file, a/b.py
to the directory structure above and starting a fresh interpreter:
import a.b.c
? ImportError: No module named 'a.b.c'; 'a.b' is not a package
import a.b
a ? <module 'a' (namespace)>
a.__path__ ? _NamespacePath(['/.../a'])
a.b ? <module 'a.b' from '/home/cjs/tmp/a/b.py'>
a.b.__path__ ? AttributeError: 'module' object has no attribute '__path__'
Python ensures that all parent modules are loaded before a child module is loaded. Above it finds that a/
is a directory, and so creates a namespace package a
, and that a/b.py
is a Python source file which it loads and uses to create a (non-package) module a.b
. At this point you cannot have a module a.b.c
because a.b
is not a package, and thus cannot have submodules.
You can also see here that the package module a
has a __path__
attribute (packages must have this) but the non-package module a.b
does not.
You could use
->appends(request()->query())
Example in the Controller:
$users = User::search()->order()->with('type:id,name')
->paginate(30)
->appends(request()->query());
return view('users.index', compact('users'));
Example in the View:
{{ $users->appends(request()->query())->links() }}
You can create lib folder inside app you press right click and select directory you named as libs its will be worked
window.location
sets the URL of your current window. To open a new window, you need to use window.open
. This should work:
function ToKey(){
var key = document.tokey.key.value.toLowerCase();
if (key == "smk") {
window.open('http://www.smkproduction.eu5.org', '_blank');
} else {
alert("Kodi nuk është valid!");
}
}
Generally when I deal with stripping \r or \n, I'll look for both by doing something like
lines.gsub(/\r\n?/, "\n");
I've found that depending on how the data was saved (the OS used, editor used, Jupiter's relation to Io at the time) there may or may not be the newline after the carriage return. It does seem weird that you see both characters in hex mode. Hope this helps.
Here is an even simplier way, by writing directly to php error output
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_STDERR, fopen('php://stderr', 'w'));
This is about generating data, and so is more properly done from the model. Imagine if you ever wanted to change the way data is displayed in the drop-down box, say add a surname or something. You'd have to find every drop-down box and change the arrayHelper
. I use a function in my models to return the data for a dropdown, so I don't have to repeat code in views. It also has the advantage that I can specify filter here and have them apply to every dropdown created from this model;
/* Model Standard.php */
public function getDropdown(){
return ArrayHelper::map(self::find()->all(), 's_id', 'name'));
}
You can use this in your view file like this;
echo $form->field($model, 'attribute')
->dropDownList(
$model->dropDown
);
If each file only has one sequence of aminoacids, I wouldn't use regular expressions at all. Just something like this:
def read_amino_acid_sequence(path):
with open(path) as sequence_file:
title = sequence_file.readline() # read 1st line
aminoacid_sequence = sequence_file.read() # read the rest
# some cleanup, if necessary
title = title.strip() # remove trailing white spaces and newline
aminoacid_sequence = aminoacid_sequence.replace(" ","").replace("\n","")
return title, aminoacid_sequence
As of 2016 you can also use the tidyverse
.
library(tidyverse)
samp %>% remove_rownames %>% column_to_rownames(var="names")
Another thing that I've found is that you must change your password at least once. And try to use a secure level password (do not use the same user as password, 123456, etc.)
As others have said, this isn't something you'd want to be doing in CSS. You can fudge it with absolute positioning and strange margins, but it's just not a robust solution. The best option in your case would be to turn to javascript. In jQuery, this is a very simple task:
$('#secondDiv').insertBefore('#firstDiv');
or more generically:
$('.swapMe').each(function(i, el) {
$(el).insertBefore($(el).prev());
});
The new :is()
CSS pseudo-class can do it in one selector:
:is(h1, h2, h3, h4, h5, h6) {
color: red;
}
This worked for me:
exclude: [/bower_components/, /node_modules/]
module.loaders
A array of automatically applied loaders.
Each item can have these properties:
test: A condition that must be met
exclude: A condition that must not be met
include: A condition that must be met
loader: A string of "!" separated loaders
loaders: A array of loaders as string
A condition can be a RegExp, an absolute path start, or an array of one of these combined with "and".
See http://webpack.github.io/docs/configuration.html#module-loaders
Just thought I'd update in-case anyone stumbles across this page in the future. As of 1.5.3, mongo now supports a real $or operator: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24or
Your query of "(expires >= Now()) OR (expires IS NULL)" can now be rendered as:
{$or: [{expires: {$gte: new Date()}}, {expires: null}]}
Ok, it seems that some versions of PHP have a limitation of length of GET params:
Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.
To add support for long parameters with suhosin, add
suhosin.get.max_value_length = <limit>
inphp.ini
Source: http://www.php.net/manual/en/reserved.variables.get.php#101469
$ git push origin develop:master
or, more generally
$ git push <remote> <local branch name>:<remote branch to push into>
The easiest thing to do is putting a div
with the following CSS in the body:
#hideAll
{
position: fixed;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
background-color: white;
z-index: 99; /* Higher than anything else in the document */
}
(Note that position: fixed
won't work in IE6 - I know of no sure-fire way of doing this in that browser)
Add the DIV like so (directly after the opening body
tag):
<div style="display: none" id="hideAll"> </div>
show the DIV directly after :
<script type="text/javascript">
document.getElementById("hideAll").style.display = "block";
</script>
and hide it onload
:
window.onload = function()
{ document.getElementById("hideAll").style.display = "none"; }
or using jQuery
$(window).load(function() { document.getElementById("hideAll").style.display = "none"; });
this approach has the advantage that it will also work for clients who have JavaScript turned off. It shouldn't cause any flickering or other side-effects, but not having tested it, I can't entirely guarantee it for every browser out there.
Use sudo -i to switch to $root, then execute npm install -g xxxx
No matter what $action is, it will always either not be "add" OR not be "delete", which is why the if condition always passes. What you want is to use && instead of ||:
(!isset($action)) || ($action !="add" && $action !="delete"))
Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.
Yup, this is in fact what's happening. See also the Javadoc:
Returns: the year represented by this date, minus 1900.
The getYear method is deprecated for this reason. So, don't use it.
Note also that getMonth returns a number between 0 and 11. Therefore, this.sale.getSaleDate().getMonth()
returns 1 for February, instead of 2. While java.util.Calendar
doesn't add 1900 to all years, it does suffer from the off-by-one-month problem.
You're much better off using JodaTime.
I'm posting this answer because the one with the most votes led me astray. To redirect from a servlet, you simply do this:
response.sendRedirect("simpleList.do")
In this particular question, I think @M-D is correctly explaining why the asker is having his problem, but since this is the first result on google when you search for "Redirect from Servlet" I think it's important to have an answer that helps most people, not just the original asker.
You could also flip your if test:
foreach ( int number in numbers )
{
if ( number >= 0 )
{
//process number
}
}
Decoding using convenience initialiser - Swift 5
extension UIImage {
convenience init?(base64String: String) {
guard let data = Data(base64Encoded: base64String) else { return nil }
self.init(data: data)
}
}
.user is the user settings, and I think .suo is the solution user options. You don't want these files under source control; they will be re-created for each user.
To do it the GUI way, you need to go edit your login. One of its properties is the default database used for that login. You can find the list of logins under the Logins node under the Security node. Then select your login and right-click and pick Properties. Change the default database and your life will be better!
Note that someone with sysadmin privs needs to be able to login to do this or to run the query from the previous post.
As Sahil Chhabra suggested you can use @JsonFormat
with proper shape
on your variable.
In case you would like to apply it on every BigDecimal
field you have in your Dto's
you can override default format for given class.
@Configuration
public class JacksonObjectMapperConfiguration {
@Autowired
public void customize(ObjectMapper objectMapper) {
objectMapper
.configOverride(BigDecimal.class).setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING));
}
}
map
doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using map
.
map
in Python 3 is equivalent to this:
def map(func, iterable):
for i in iterable:
yield func(i)
and the only difference in Python 2 is that it will build up a full list of results to return all at once instead of yield
ing.
Although Python convention usually prefers list comprehensions (or generator expressions) to achieve the same result as a call to map
, particularly if you're using a lambda expression as the first argument:
[func(i) for i in iterable]
As an example of what you asked for in the comments on the question - "turn a string into an array", by 'array' you probably want either a tuple or a list (both of them behave a little like arrays from other languages) -
>>> a = "hello, world"
>>> list(a)
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(a)
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')
A use of map
here would be if you start with a list of strings instead of a single string - map
can listify all of them individually:
>>> a = ["foo", "bar", "baz"]
>>> list(map(list, a))
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]
Note that map(list, a)
is equivalent in Python 2, but in Python 3 you need the list
call if you want to do anything other than feed it into a for
loop (or a processing function such as sum
that only needs an iterable, and not a sequence). But also note again that a list comprehension is usually preferred:
>>> [list(b) for b in a]
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]
I had this concern when working on a Rails application with Docker.
My most preferred approach is to generally not use quotes. This includes not using quotes for:
${RAILS_ENV}
postgres-log:/var/log/postgresql
I, however, use double-quotes for integer
values that need to be converted to strings like:
version: "3.8"
"8080:8080"
However, for special cases like booleans
, floats
, integers
, and other cases, where using double-quotes for the entry values could be interpreted as strings
, please do not use double-quotes.
Here's a sample docker-compose.yml
file to explain this concept:
version: "3"
services:
traefik:
image: traefik:v2.2.1
command:
- --api.insecure=true # Don't do that in production
- --providers.docker=true
- --providers.docker.exposedbydefault=false
- --entrypoints.web.address=:80
ports:
- "80:80"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
That's all.
I hope this helps
Lots of the answers here don't honor changes of the table or are way too complicated. Using a subclass of UITableView
that will properly set intrinsicContentSize
is a far easier solution when using autolayout. No height constraints etc. needed.
class UIDynamicTableView: UITableView
{
override var intrinsicContentSize: CGSize {
self.layoutIfNeeded()
return CGSize(width: UIViewNoIntrinsicMetric, height: self.contentSize.height)
}
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
}
}
Set the class of your TableView to UIDynamicTableView
in the interface builder and watch the magic as this TableView will change it's size after a call to reloadData()
.
You have a couple options, you could setTimeout()
or setInterval()
. Here's a great article that elaborates on how to use them.
The magic is that they're built in to JavaScript, you can use them with any library.
Among other already mentioned tools you can use also readelf
(manual). It is similar to objdump
but goes more into detail. See this for the difference explanation.
$ readelf -sW /lib/liblzma.so.5 |head -n10
Symbol table '.dynsym' contains 128 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FUNC GLOBAL DEFAULT UND pthread_mutex_unlock@GLIBC_2.0 (4)
2: 00000000 0 FUNC GLOBAL DEFAULT UND pthread_mutex_destroy@GLIBC_2.0 (4)
3: 00000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable
4: 00000000 0 FUNC GLOBAL DEFAULT UND memmove@GLIBC_2.0 (5)
5: 00000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.0 (5)
6: 00000000 0 FUNC GLOBAL DEFAULT UND memcpy@GLIBC_2.0 (5)
i think you have only defined the function. you are not triggering it anywhere.
please do
window.onload = addList();
or trigger it on some other event
after its definition
see this fiddle
If you wish to have "Save as" dialog, just pass image into php script, which adds appropriate headers
Example "all-in-one" script script.php
<?php if(isset($_GET['image'])):
$image = $_GET['image'];
if(preg_match('#^data:image/(.*);base64,(.*)$#s', $image, $match)){
$base64 = $match[2];
$imageBody = base64_decode($base64);
$imageFormat = $match[1];
header('Content-type: application/octet-stream');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); // required for certain browsers
header("Content-Disposition: attachment; filename=\"file.".$imageFormat."\";" ); //png is default for toDataURL
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".strlen($imageBody));
echo $imageBody;
}
exit();
endif;?>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js?ver=1.7.2'></script>
<canvas id="canvas" width="300" height="150"></canvas>
<button id="btn">Save</button>
<script>
$(document).ready(function(){
var canvas = document.getElementById('canvas');
var oCtx = canvas.getContext("2d");
oCtx.beginPath();
oCtx.moveTo(0,0);
oCtx.lineTo(300,150);
oCtx.stroke();
$('#btn').on('click', function(){
// opens dialog but location doesnt change due to SaveAs Dialog
document.location.href = '/script.php?image=' + canvas.toDataURL();
});
});
</script>
Use DISTINCT
if you just want to remove duplicates. Use GROUPY BY
if you want to apply aggregate operators (MAX
, SUM
, GROUP_CONCAT
, ..., or a HAVING
clause).
You shouldn't need a $watch. Just bind to resize event on window:
'use strict';
var app = angular.module('plunker', []);
app.directive('myDirective', ['$window', function ($window) {
return {
link: link,
restrict: 'E',
template: '<div>window size: {{width}}px</div>'
};
function link(scope, element, attrs){
scope.width = $window.innerWidth;
angular.element($window).bind('resize', function(){
scope.width = $window.innerWidth;
// manuall $digest required as resize event
// is outside of angular
scope.$digest();
});
}
}]);
And if you want to specify select's ID:
$("#nextPageLink").click(function(){
$('#myselect option:selected').next('option').attr('selected', 'selected');
$("#myselect").change();
});
If you click on item with id "nextPageLink", next option will be selected and onChange() event will be called. It may look like this:
$("#myselect").change(function(){
$('#myDivId').load(window.location.pathname,{myvalue:$("select#myselect").val()});
});
OnChange() event uses Ajax to load something into specified div.
window.location.pathname = actual address
OnChange() event is defined because it allowes you to change value not only using netx/prev button, but directly using standard selection. If value is changed, page does somethig automatically.
I created a Bash script that basically automates the manual installation described in the linked similar question. It requires the tar.gz
file as well as its SHA256 sum value. You can find out more info and download the script from my GitHub project page. It is provided under MIT license.
You can do multicolor outputs without any external programs.
@echo off
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
echo say the name of the colors, don't read
call :ColorText 0a "blue"
call :ColorText 0C "green"
call :ColorText 0b "red"
echo(
call :ColorText 19 "yellow"
call :ColorText 2F "black"
call :ColorText 4e "white"
goto :eof
:ColorText
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
goto :eof
It uses the color feature of the findstr command.
Findstr can be configured to output line numbers or filenames in a defined color.
So I first create a file with the text as filename, and the content is a single <backspace>
character (ASCII 8).
Then I search all non empty lines in the file and in nul, so the filename will be output in the correct color appended with a colon, but the colon is immediatly removed by the <backspace>
.
EDIT: One year later ... all characters are valid
@echo off
setlocal EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
rem Prepare a file "X" with only one dot
<nul > X set /p ".=."
call :color 1a "a"
call :color 1b "b"
call :color 1c "^!<>&| %%%%"*?"
exit /b
:color
set "param=^%~2" !
set "param=!param:"=\"!"
findstr /p /A:%1 "." "!param!\..\X" nul
<nul set /p ".=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
exit /b
This uses the rule for valid path/filenames.
If a \..\
is in the path the prefixed elemet will be removed completly and it's not necessary that this element contains only valid filename characters.
static void pushZerosToEnd(int arr[])
{ int n = arr.length;
int count = 0; // Count of non-zero elements
// Traverse the array. If element encountered is non-zero, then
// replace the element at index 'count' with this element
for (int i = 0; i < n; i++){
if (arr[i] != 0)`enter code here`
// arr[count++] = arr[i]; // here count is incremented
swapNumbers(arr,count++,i);
}
for (int j = 0; j < n; j++){
System.out.print(arr[j]+",");
}
}
public static void swapNumbers(int [] arr, int pos1, int pos2){
int temp = arr[pos2];
arr[pos2] = arr[pos1];
arr[pos1] = temp;
}
Hi every one this code is workin for me please try with this for sending mail to multiple recepients
private String recipient = "[email protected] ,[email protected] ";
String[] recipientList = recipient.split(",");
InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
int counter = 0;
for (String recipient : recipientList) {
recipientAddress[counter] = new InternetAddress(recipient.trim());
counter++;
}
message.setRecipients(Message.RecipientType.TO, recipientAddress);
The spec says seconds:
http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-4.2.2
expires_in
OPTIONAL. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
I agree with OP that it's careless for Google to not document this.
I had a form with 11 submit buttons on it, and it would always use the first submit button when the user pressed enter. I read elsewhere that it is not a good idea (bad practice) to have more than one submit button on a form, and the best way to do this is have the button you want as default, as the only submit button on the form. The other buttons should be made into "TYPE=BUTTON" and an onClick event added that calls your own submit routine in Javascript. Something like this :-
<SCRIPT Language="JavaScript">
function validform()
{
// do whatever you need to validate the form, and return true or false accordingly
}
function mjsubmit()
{
if (validform()) { document.form1.submit(); return true;}
return false;
}
</SCRIPT>
<INPUT TYPE=BUTTON NAME="button1" VALUE="button1" onClick="document.form1.submitvalue='button1'; return mjsubmit();">
<INPUT TYPE=BUTTON NAME="button2" VALUE="button2" onClick="document.form1.submitvalue='button2'; return mjsubmit();">
<INPUT TYPE=SUBMIT NAME="button3" VALUE="button3" onClick="document.form1.submitvalue='button3'; return validform();">
<INPUT TYPE=BUTTON NAME="button4" VALUE="button4" onClick="document.form1.submitvalue='button4'; return mjsubmit();">
Here, button3 is the default, and although you are programmatically submitting the form with the other buttons, the mjsubmit routine validates them. HTH.
With using pathlib module, indentation isn't needed.
import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))
As of python 3.6, f-strings is available.
pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")
It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
When location matches the last part of the directive’s value: it is better to use the root directive instead:
which would yield:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
root /home/www-data/mysite;
}
location = /404.html {
root /home/www-data/mysite/static/html;
}
}