All of the answers here are helpful, Thanks to everyone who offered help.
However as i see that that the safe area topic is a little bit confused which won’t appear to be well documented.
So i will summarize it here as mush as possible to make it easy to understand safeAreaInsets
, safeAreaLayoutGuide
and LayoutGuide
.
In iOS 7, Apple introduced the topLayoutGuide
and bottomLayoutGuide
properties in UIViewController
,
They allowed you to create constraints to keep your content from being hidden by UIKit bars like the status, navigation or tab bar
It was possible with these layout guides to specify constraints on content,
avoiding it to be hidden by top or bottom navigation elements (UIKit bars, status bar, nav or tab bar…).
So for example if you wanna make a tableView starts from the top screen you have done something like that:
self.tableView.contentInset = UIEdgeInsets(top: -self.topLayoutGuide.length, left: 0, bottom: 0, right: 0)
In iOS 11 Apple has deprecated these properties replacing them with a single safe area layout guide
Safe area according to Apple
Safe areas help you place your views within the visible portion of the overall interface. UIKit-defined view controllers may position special views on top of your content. For example, a navigation controller displays a navigation bar on top of the underlying view controller’s content. Even when such views are partially transparent, they still occlude the content that is underneath them. In tvOS, the safe area also includes the screen’s overscan insets, which represent the area covered by the screen’s bezel.
Below, a safe area highlighted in iPhone 8 and iPhone X-series:
The safeAreaLayoutGuide
is a property of UIView
To get the height of safeAreaLayoutGuide
:
extension UIView {
var safeAreaHeight: CGFloat {
if #available(iOS 11, *) {
return safeAreaLayoutGuide.layoutFrame.size.height
}
return bounds.height
}
}
That will return the height of the Arrow in your picture.
Now, what about getting the top "notch" and bottom home screen indicator heights?
Here we will use the safeAreaInsets
The safe area of a view reflects the area not covered by navigation bars, tab bars, toolbars, and other ancestors that obscure a view controller's view. (In tvOS, the safe area reflects the area not covered by the screen's bezel.) You obtain the safe area for a view by applying the insets in this property to the view's bounds rectangle. If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the edge insets in this property are 0.
The following will show the unsafe area and there distance from edges on iPhone 8 and one of iPhone X-Series.
Now, if navigation bar added
So, now how to get the unsafe area height? we will use the safeAreaInset
Here are to solutions however they differ in an important thing,
First One:
self.view.safeAreaInsets
That will return the EdgeInsets, you can now access the top and the bottom to know the insets,
Second One:
UIApplication.shared.windows.first{$0.isKeyWindow }?.safeAreaInsets
The first one you are taking the view insets, so if there a navigation bar it will be considered , however the second one you are accessing the window's safeAreaInsets so the navigation bar will not be considered
Just a note that the constant
keyword use for safe-area margins has been updated to env
for 11.2 beta+
https://webkit.org/blog/7929/designing-websites-for-iphone-x/
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
So, I had this code:
<div class="dropdown-select-wrapper" *ngIf="contentData">
<button mat-stroked-button [disableRipple]="true" class="mat-button" (click)="openSelect()" [ngClass]="{'only-icon': !contentData?.buttonText?.length}">
<i *ngIf="contentData.iconClassInfo" class="dropdown-icon {{contentData.iconClassInfo.name}}"></i>
<span class="button-text" *ngIf="contentData.buttonText">{{contentData.buttonText}}</span>
</button>
<mat-select class="small-dropdown-select" [formControl]="theFormControl" #buttonSelect (selectionChange)="onSelect(buttonSelect.selected)" (click)="$event.stopPropagation();">
<mat-option *ngFor="let option of options" [ngClass]="{'selected-option': buttonSelect.selected?.value === option[contentData.optionsStructure.valName]}" [disabled]="buttonSelect.selected?.value === option[contentData.optionsStructure.valName] && contentData.optionSelectedWillDisable" [value]="option[contentData.optionsStructure.valName]">
{{option[contentData.optionsStructure.keyName]}}
</mat-option>
</mat-select>
</div>
Here I was using standalone formControl, and I was getting the error we are talking about, which made no sense for me, since I wasn't working with formgroups or formarrays... it only disappeared when I added the *ngIf to the select it self, so is not being used before it actually exists. That's what solved the issue in my case.
<mat-select class="small-dropdown-select" [formControl]="theFormControl" #buttonSelect (selectionChange)="onSelect(buttonSelect.selected)" (click)="$event.stopPropagation();" *ngIf="theFormControl">
<mat-option *ngFor="let option of options" [ngClass]="{'selected-option': buttonSelect.selected?.value === option[contentData.optionsStructure.valName]}" [disabled]="buttonSelect.selected?.value === option[contentData.optionsStructure.valName] && contentData.optionSelectedWillDisable" [value]="option[contentData.optionsStructure.valName]">
{{option[contentData.optionsStructure.keyName]}}
</mat-option>
</mat-select>
Actions
ADD_PRODUCT : (context,product) => {
return Axios.post(uri, product).then((response) => {
if (response.status === 'success') {
context.commit('SET_PRODUCT',response.data.data)
}
return response.data
});
});
Component
this.$store.dispatch('ADD_PRODUCT',data).then((res) => {
if (res.status === 'success') {
// write your success actions here....
} else {
// write your error actions here...
}
})
It's so simple.
Just install Microsoft.EntityFrameworkCore.Tools
package from nuget:
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.5
You can also use this link to install the latest version: Nuget package link
.NET CLI command:
dotnet add package Microsoft.EntityFrameworkCore.Tools
As a newbie in React world, I came across a similar issues where I could not edit
the textarea and struggled
with binding. It's worth knowing about controlled
and uncontrolled
elements when it comes to react.
The value of the following uncontrolled textarea
cannot be changed because of value
<textarea type="text" value="some value"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following uncontrolled textarea
can be changed because of use of defaultValue
or no value attribute
<textarea type="text" defaultValue="sample"
onChange={(event) => this.handleOnChange(event)}></textarea>
<textarea type="text"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following controlled textarea
can be changed because of how
value is mapped to a state as well as the onChange
event listener
<textarea value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
Here is my solution using different syntax. I prefer the auto-bind
than manual binding however, if I were to not use {(event) => this.onXXXX(event)}
then that would cause the content of textarea
to be not editable OR the event.preventDefault()
does not work as expected. Still a lot to learn I suppose.
class Editor extends React.Component {
constructor(props) {
super(props)
this.state = {
textareaValue: ''
}
}
handleOnChange(event) {
this.setState({
textareaValue: event.target.value
})
}
handleOnSubmit(event) {
event.preventDefault();
this.setState({
textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
})
}
render() {
return <div>
<form onSubmit={(event) => this.handleOnSubmit(event)}>
<textarea rows={10} cols={30} value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
<br/>
<input type="submit" value="Save"/>
</form>
</div>
}
}
ReactDOM.render(<Editor />, document.getElementById("content"));
The versions of libraries are
"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4"
Use Test-Path:
if (!(Test-Path $exactadminfile) -and !(Test-Path $userfile)) {
Write-Warning "$userFile absent from both locations"
}
Placing the above code in your ForEach
loop should do what you want
I solved this problem like so:
1.) Set classpath in top-level build file as GUG mentioned:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.0-beta2'
}
allprojects {
repositories {
jcenter()
}
}
}
2.) In build file of specific module:
android {
useLibrary 'org.apache.http.legacy'
compileSdkVersion 'android-MNC'
buildToolsVersion '23.0.0 rc3'
}
Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application.....
with filename = GetFileName(Range("A1"))
Function GetFileName(rngNamedCell As Range) As String
Dim strSaveDirectory As String: strSaveDirectory = ""
Dim strFileName As String: strFileName = ""
Dim strTestPath As String: strTestPath = ""
Dim strFileBaseName As String: strFileBaseName = ""
Dim strFilePath As String: strFilePath = ""
Dim intFileCounterIndex As Integer: intFileCounterIndex = 1
' Get the users desktop directory.
strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
Debug.Print "Saving to: " & strSaveDirectory
' Base file name
strFileBaseName = Trim(rngNamedCell.Value)
Debug.Print "File Name will contain: " & strFileBaseName
' Loop until we find a free file number
Do
If intFileCounterIndex > 1 Then
' Build test path base on current counter exists.
strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
Else
' Build test path base just on base name to see if it exists.
strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
End If
If (Dir(strTestPath) = "") Then
' This file path does not currently exist. Use that.
strFileName = strTestPath
Else
' Increase the counter as we have not found a free file yet.
intFileCounterIndex = intFileCounterIndex + 1
End If
Loop Until strFileName <> ""
' Found useable filename
Debug.Print "Free file name: " & strFileName
GetFileName = strFileName
End Function
The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.
In Action
My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.
Sub Testing()
Dim filename As String: filename = GetFileName(Range("o1"))
ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.
How to resize root partition online :
1) [root@oel7 ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/root_vg-root 5.0G 4.5G 548M 90% /
2)
PV /dev/sda2 VG root_vg lvm2 [6.00 GiB / 0 free]
as here it shows that there is no space left on root_vg volume group, so first i need to extend VG
3)
[root@oel7 ~]# vgextend root_vg /dev/sdb5
Volume group "root_vg" successfully extended
4)
[root@oel7 ~]# pvscan
PV /dev/sda2 VG root_vg lvm2 [6.00 GiB / 0 free]
PV /dev/sdb5 VG root_vg lvm2 [2.00 GiB / 2.00 GiB free]
5) Now extend the logical volume
[root@oel7 ~]# lvextend -L +1G /dev/root_vg/root
Size of logical volume root_vg/root changed from 5.00 GiB (1280 extents) to 6.00 GiB (1536 extents).
Logical volume root successfully resized
3) [root@oel7 ~]# resize2fs /dev/root_vg/root
resize2fs 1.42.9 (28-Dec-2013)
resize2fs: Bad magic number in super-block while trying to open /dev/root_vg /root
Couldn't find valid filesystem superblock.
as root partition is not a ext* partiton so , you resize2fs will not work for you.
4) to check the filesystem type of a partition
[root@oel7 ~]# df -Th
Filesystem Type Size Used Avail Use% Mounted on
/dev/mapper/root_vg-root xfs 6.0G 4.5G 1.6G 75% /
devtmpfs devtmpfs 481M 0 481M 0% /dev
tmpfs tmpfs 491M 80K 491M 1% /dev/shm
tmpfs tmpfs 491M 7.1M 484M 2% /run
tmpfs tmpfs 491M 0 491M 0% /sys/fs /cgroup
/dev/mapper/data_vg-home xfs 3.5G 2.9G 620M 83% /home
/dev/sda1 xfs 497M 132M 365M 27% /boot
/dev/mapper/data_vg01-data_lv001 ext3 4.0G 2.4G 1.5G 62% /sybase
/dev/mapper/data_vg02-backup_lv01 ext3 4.0G 806M 3.0G 22% /backup
above command shows that root is an xfs filesystem , so we are sure that we need to use xfs_growfs command to resize the partition.
6) [root@oel7 ~]# xfs_growfs /dev/root_vg/root
meta-data=/dev/mapper/root_vg-root isize=256 agcount=4, agsize=327680 blks
= sectsz=512 attr=2, projid32bit=1
= crc=0 finobt=0
data = bsize=4096 blocks=1310720, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=0
log =internal bsize=4096 blocks=2560, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
realtime =none extsz=4096 blocks=0, rtextents=0
data blocks changed from 1310720 to 1572864
[root@oel7 ~]# df -Th
Filesystem Type Size Used Avail Use% Mounted on
/dev/mapper/root_vg-root xfs 6.0G 4.5G 1.6G 75% /
I was also getting this error, I deleted dlls from my debug folder and when I started a new instance for debug I got this error. For me the issue was due to the the build setting, Release was selected in the build type, I just changed it to debug and then application was working fine
I am working with ionic2 and system config is as below-
******************************************************
Your system information:
Cordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-beta.10
Ionic CLI Version: 2.1.8
Ionic App Lib Version: 2.1.4
ios-deploy version: Not installed
ios-sim version: 5.0.8
OS: OS X Yosemite
Node Version: v6.2.2
Xcode version: Xcode 7.2 Build version 7C68
******************************************************
For me this issue got resolved with this code-
for html iframe tag-
<div class="iframe_container">
<iframe class= "animated fadeInUp" id="iframe1" [src]='page' frameborder="0" >
<!-- <img src="img/video-icon.png"> -->
</iframe><br>
</div>
See css of the same as-
.iframe_container {
overflow: auto;
position: relative;
-webkit-overflow-scrolling: touch;
height: 75%;
}
iframe {
position:relative;
top: 2%;
left: 5%;
border: 0 !important;
width: 90%;
}
Position property play a vital role here in my case.
position:relative;
It may help you too!!!
How I redirect to an area is add it as a parameter
@Html.Action("Action", "Controller", new { area = "AreaName" })
for the href portion of a link I use
@Url.Action("Action", "Controller", new { area = "AreaName" })
While working with selected cells as shown by @tbur can be useful, it's also not the only option available.
You can use Range() like so:
If Worksheets("Sheet1").Range("A1").MergeCells Then
Do something
Else
Do something else
End If
Or:
If Worksheets("Sheet1").Range("A1:C1").MergeCells Then
Do something
Else
Do something else
End If
Alternately, you can use Cells():
If Worksheets("Sheet1").Cells(1, 1).MergeCells Then
Do something
Else
Do something else
End If
Please find below a way that works on all browsers. Basically I put the input on top the image. I make it huge using font-size so the user is always clicking the upload button.
.myFile {_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
float: left;_x000D_
clear: left;_x000D_
}_x000D_
.myFile input[type="file"] {_x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
opacity: 0;_x000D_
font-size: 100px;_x000D_
filter: alpha(opacity=0);_x000D_
cursor: pointer;_x000D_
}
_x000D_
<label class="myFile">_x000D_
<img src="http://wscont1.apps.microsoft.com/winstore/1x/c37a9d99-6698-4339-acf3-c01daa75fb65/Icon.13385.png" alt="" />_x000D_
<input type="file" />_x000D_
</label>
_x000D_
Object doesn't support this property or method.
Think of it like if anything after the dot is called on an object. It's like a chain.
An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot .
you get intelli-sense (that white dropdown) trying to help you pick the correct action.
(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)
Type this much anywhere in your code area
Dim a As Worksheets
a.
you get help from VBE, it's a little dropdown called Intelli-sense
It lists all available actions that particular object exposes to any user. You can't see the .Selection
member of the Worksheets()
class. That's what the error tells you exactly.
Object doesn't support this property or method.
If you look at the example on MSDN
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
It activates
the sheet first then calls the Selection...
it's not connected together because Selection
is not a member of Worksheets()
class. Simply, you can't prefix the Selection
What about
Sub DisplayColumnCount()
Dim iAreaCount As Integer
Dim i As Integer
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
If iAreaCount <= 1 Then
MsgBox "The selection contains " & Selection.Columns.Count & " columns."
Else
For i = 1 To iAreaCount
MsgBox "Area " & i & " of the selection contains " & _
Selection.Areas(i).Columns.Count & " columns."
Next i
End If
End Sub
from HERE
Another useful way is with Concat.
More information in the official documentation.
List<string> first = new List<string> { "One", "Two", "Three" };
List<string> second = new List<string>() { "Four", "Five" };
first.Concat(second);
The output will be.
One
Two
Three
Four
Five
And there is another similar answer.
I had the same issue, for me this fixed the issue:
right click on the project ->maven -> update project
Once you have Selected a group of sheets, you can use Selection
Consider:
Sub luxation()
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
Selection.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="C:\TestFolder\temp.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End Sub
EDIT#1:
Further testing has reveled that this technique depends on the group of cells selected on each worksheet. To get a comprehensive output, use something like:
Sub Macro1()
Sheets("Sheet1").Activate
ActiveSheet.UsedRange.Select
Sheets("Sheet2").Activate
ActiveSheet.UsedRange.Select
Sheets("Sheet3").Activate
ActiveSheet.UsedRange.Select
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\James\Desktop\pdfmaker.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End Sub
Try to change where Member class
public function users() {
return $this->hasOne('User');
}
return $this->belongsTo('User');
HTML
<form id="some_form">
<!-- some form elements -->
</form>
and jquery
$("#some_form").reset();
Idle Timeout is if no action has been asked from your web app, it the process will drop and release everything from memory
Recycle is a forced action on the application where your processed is closed and started again, for memory leaking purposes and system health
The negative impact of both is usually the use of your Session and Application state is lost if you mess with Recycle to a faster time.(logged in users etc will be logged out, if they where about to "check out" all would have been lost" that's why recycle is at such a large time out value, idle timeout doesn't matter because nobody is logged in anyway and figure 20 minutes an no action they are not still "shopping"
The positive would be get rid of the idle time out as your website will respond faster on its "first" response if its not a highly active site where a user would have to wait for it to load if you have 1 user every 20 minutes lets say. So a website that get his less then 1 time in 20 minutes actually you would want to increase this value as the website has to load up again from scratch for each user. but if you set this to 0 over a long time, any memory leaks in code could over a certain amount of time, entirely take over the server.
mysqlclient
sudo pip3 install mysqlclient
if you get error:
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-dbljg4tx/mysqlclient/
then:
1. sudo apt install libmysqlclient-dev python-mysqldb
2. sudo pip3 install mysqlclient
Modify settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'website',
'USER': 'root',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '3306',
'OPTION': {'init_command':"SET sql_mode='STRICT_TRANS_TABLE',"},
}
}
This appears to be a bug in the way jQuery ships. You can fix it manually with some dom manipulation on the Dialog Open
event:
$("#selector").dialog({
open: function() {
$(this).closest(".ui-dialog")
.find(".ui-dialog-titlebar-close")
.removeClass("ui-dialog-titlebar-close")
.html("<span class='ui-button-icon-primary ui-icon ui-icon-closethick'></span>");
}
});
Not too sure to add opacity via CSS is such a good idea.
Opacity has that funny way to be applied to all content and childs from where you set it, with unexpected results in mixed of colours.
It has no really purpose in that case , for a bg color, in my opinion.
If you'd like to lay it hover the bg image, then you may use multiple backgrounds.
this color transparent could be applyed via an extra png repeated (or not with background-position),
CSS gradient (radial-) linear-gradient with rgba colors (starting and ending with same color) can achieve this as well. They are treated as background-image and can be used as filter.
Idem for text, if you want them a bit transparent, use rgba (okay to put text-shadow together).
I think that today, we can drop funny behavior of CSS opacity.
Here is a mixed of rgba used for opacity if you are curious dabblet.com/gist/5685845
Add following line
GlobalConfiguration.Configure(WebApiConfig.Register);
in Application_Start()
function in Global.ascx.cs file.
hope you are doing well.
you can use my code to crop image.you just have to make a class and use this class into your XMl
and java
classes.
Crop image.
you can crop your selected image into circle and square into many of option.
hope fully it will works for you.because this is totally manageable for you and you can change it according to you.
enjoy your work :)
I prefer option 4, but it makes intuitive sense to me because I do far too much work in Grails, Groovy, and JavaFX. "Magic" connections between the view and the controller are common in all. It is important to name the method well:
In the view,add the onClick method to the button or other widget:
android:clickable="true"
android:onClick="onButtonClickCancel"
Then in the class, handle the method:
public void onButtonClickCancel(View view) {
Toast.makeText(this, "Cancel pressed", Toast.LENGTH_LONG).show();
}
Again, name the method clearly, something you should do anyway, and the maintenance becomes second-nature.
One big advantage is that you can write unit tests now for the method. Option 1 can do this, but 2 and 3 are more difficult.
In my case, I had created the map, but was missing the ReverseMap function. Adding it got rid of the error.
private static void RegisterServices(ContainerBuilder bldr)
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new CampMappingProfile());
});
...
}
public CampMappingProfile()
{
CreateMap<Talk, TalkModel>().ReverseMap();
...
}
Not sure if this hits the solution from a different angle to the accepted answer, but I found that one of my controllers in the Areas section was sitting in the wrong namespace. Correcting the namespace to:
Areas.{AreaName}.Controller
fixed the issue for me.
I suspect the key factor was to have all the controllers within a given area share the same namespace.
As said by Sparky in comments on many answers to this question, there is NOT any textarea
value for the type
attribute of the input
tag.
On other terms, the following markup is not valid :
<input type="textarea" />
And the browser replaces it by the default :
<input type="text" />
To define a multi-lines text input, use :
<textarea></textarea>
See the textarea element documentation for more details.
Any approach should give you roughly same number. It is always a good idea to allocate the heap using -X..m
-X..x
for all generations. You can then guarantee and also do ps to see what parameters were passed and hence being used.
For actual memory usages, you can roughly compare VIRT (allocated and shared) and RES (actual used) compare against the jstat values as well:
For Java 8, see jstat for these values actually mean. Assuming you run a simple class with no mmap or file processing.
$ jstat -gccapacity 32277
NGCMN NGCMX NGC S0C S1C EC OGCMN OGCMX OGC OC MCMN MCMX MC CCSMN CCSMX CCSC YGC FGC
215040.0 3433472.0 73728.0 512.0 512.0 67072.0 430080.0 6867968.0 392704.0 392704.0 0.0 1083392.0 39680.0 0.0 1048576.0 4864.0 7225 2
$ jstat -gcutil 32277
S0 S1 E O M CCS YGC YGCT FGC FGCT GCT
6.25 0.00 7.96 18.21 98.01 95.29 7228 30.859 2 0.173 31.032
Max:
NGCMX + S0C + S1C + EC + OGCMX + MCMX + CCSMX
3433472 + 512 + 512 + 67072 + 6867968 + 1083392 + 1048576 = 12 GB
(roughly close and below to VIRT memory)
Max(Min, Used):
215040 + 512 + 512 + 67072 + 430080 + 39680 + 4864 = ~ 1GB
(roughly close to RES memory)
"Don't quote me on this" but VIRT mem is roughly close to or more than Max memory allocated but as long as memory being used is free/available in physical memory, JVM does not throw memory exception. In fact, max memory is not even checked against physical memory on JVM startup even with swap off on OS. A better explanation of what Virtual memory really used by a Java process is discussed here.
See http://angular-ui.github.io/bootstrap/#/collapse
function CollapseDemoCtrl($scope) {
$scope.isCollapsed = false;
}
<div ng-controller="CollapseDemoCtrl">
<button class="btn" ng-click="isCollapsed = !isCollapsed">Toggle collapse</button>
<hr>
<div collapse="isCollapsed">
<div class="well well-large">Some content</div>
</div>
</div>
Inspired by [@JulieLerman 's DDD MSDN Mag Article 2013][1]
public class ShippingContext : BaseContext<ShippingContext>
{
public DbSet<Shipment> Shipments { get; set; }
public DbSet<Shipper> Shippers { get; set; }
public DbSet<OrderShippingDetail> Order { get; set; } //Orders table
public DbSet<ItemToBeShipped> ItemsToBeShipped { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Ignore<LineItem>();
modelBuilder.Ignore<Order>();
modelBuilder.Configurations.Add(new ShippingAddressMap());
}
}
public class BaseContext<TContext>
DbContext where TContext : DbContext
{
static BaseContext()
{
Database.SetInitializer<TContext>(null);
}
protected BaseContext() : base("DPSalesDatabase")
{}
}
"If you’re doing new development and you want to let Code First create or migrate your database based on your classes, you’ll need to create an “uber-model” using a DbContext that includes all of the classes and relationships needed to build a complete model that represents the database. However, this context must not inherit from BaseContext." JL
Here is the NodeJS REST api for two PDF render scripts. https://github.com/pumppi/pdf2images
Scripts are: pdf2svg and Imagemagicks convert
Fun problem: when I glanced at your bottle image I thought it was a can too. But, as a human, what I did to tell the difference is that I then noticed it was also a bottle...
So, to tell cans and bottles apart, how about simply scanning for bottles first? If you find one, mask out the label before looking for cans.
Not too hard to implement if you're already doing cans. The real downside is it doubles your processing time. (But thinking ahead to real-world applications, you're going to end up wanting to do bottles anyway ;-)
To learn what row was selected, add a ListSelectionListener
, as shown in How to Use Tables in the example SimpleTableSelectionDemo
. A JList
can be constructed directly from the linked list's toArray()
method, and you can add a suitable listener to it for details.
Simplest and best:
i = 0
while not there_is_reason_to_break(i):
# some code here
i += 1
It may be tempting to choose the closest analogy to the C code possible in Python:
from itertools import count
for i in count():
if thereIsAReasonToBreak(i):
break
But beware, modifying i
will not affect the flow of the loop as it would in C. Therefore, using a while
loop is actually a more appropriate choice for porting that C code to Python.
When the translate3d doesn't work, try to add perspective. It always works for me
transform: translate3d(0, 0, 0);
-webkit-transform: translate3d(0, 0, 0);
perspective: 1000;
-webkit-perspective: 1000;
http://blog.teamtreehouse.com/increase-your-sites-performance-with-hardware-accelerated-css
Here's a solution in pure PIL.
def blend_value(under, over, a):
return (over*a + under*(255-a)) / 255
def blend_rgba(under, over):
return tuple([blend_value(under[i], over[i], over[3]) for i in (0,1,2)] + [255])
white = (255, 255, 255, 255)
im = Image.open(object.logo.path)
p = im.load()
for y in range(im.size[1]):
for x in range(im.size[0]):
p[x,y] = blend_rgba(white, p[x,y])
im.save('/tmp/output.png')
Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:
<input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />
Then you just get the value in your ajax call:
var path = $("#GetIndexDataPath").val();
$.ajax({
type: "GET",
url: path,
data: { id = e.value},
dataType: "html",
success : function (data) {
$('div#theNewView').html(data);
}
});
}
I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.
This one is in my opinion the best one for online (offline however dreamweaver is best): http://www.maschek.hu/imagemap/imgmap
.services-list .fa {
transition: 0.5s;
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
color: blue;
}
/* For me, @media query is the easiest way for disabling hover on mobile devices */
@media only screen and (min-width: 981px) {
.services-list .fa:hover {
color: #faa152;
transition: 0.5s;
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
/* You can actiate hover on mobile with :active */
.services-list .fa:active {
color: #faa152;
transition: 0.5s;
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
.services-list .fa-car {
font-size:20px;
margin-right:15px;
}
.services-list .fa-user {
font-size:48px;
margin-right:15px;
}
.services-list .fa-mobile {
font-size:60px;
}
_x000D_
<head>
<title>Hover effects on mobile browsers</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="services-list">
<i class="fa fa-car"></i>
<i class="fa fa-user"></i>
<i class="fa fa-mobile"></i>
</div>
</body>
_x000D_
For example: https://jsfiddle.net/lesac4/jg9f4c5r/8/
As far as I am aware you have to use javascript to travel up the dom.
Something like this:
$("textarea:focus").parent().attr("border", "thin solid black");
you'll need the jQuery libraries loaded as well.
i just deleted folder 'Bin' from server and copy my bin to server, and my problem solved.
If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)
<select chosen="{width: '100%'}" ng-
model="modelName" class="form-control input-
sm"
ng-
options="persons.persons as
persons.persons for persons in
jsonData"
ng-
change="anyFunction(anyParam)"
required>
<option value=""> </option>
</select>
<style>
.chosen-container .chosen-drop {
border-bottom: 0;
border-top: 1px solid #aaa;
top: auto;
bottom: 40px;
}
.chosen-container.chosen-with-drop .chosen-single {
border-top-left-radius: 0px;
border-top-right-radius: 0px;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
background-image: none;
}
.chosen-container.chosen-with-drop .chosen-drop {
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
box-shadow: none;
margin-bottom: -16px;
}
</style>
This code is work for me
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
// add your action here that you want
return true;
}
else if (id==R.id.login)
{
// add your action here that you want
}
return super.onOptionsItemSelected(item);
}
I would like to suggest another framework: Apache Pivot http://pivot.apache.org/.
I tried it briefly and was impressed by what it can offer as an RIA (Rich Internet Application) framework ala Flash.
It renders UI using Java2D, thus minimizing the impact of (IMO, bloated) legacies of Swing and AWT.
Animations:
// slide to top of the page
$('.up').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
// slide page to anchor
$('.menutop b').click(function(){
//event.preventDefault();
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 600);
return false;
});
// Scroll to class, div
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#target-element").offset().top
}, 1000);
});
// div background animate
$(window).scroll(function () {
var x = $(this).scrollTop();
// freezze div background
$('.banner0').css('background-position', '0px ' + x +'px');
// from left to right
$('.banner0').css('background-position', x+'px ' +'0px');
// from right to left
$('.banner0').css('background-position', -x+'px ' +'0px');
// from bottom to top
$('#skills').css('background-position', '0px ' + -x + 'px');
// move background from top to bottom
$('.skills1').css('background-position', '0% ' + parseInt(-x / 1) + 'px' + ', 0% ' + parseInt(-x / 1) + 'px, center top');
// Show hide mtop menu
if ( x > 100 ) {
$( ".menu" ).addClass( 'menushow' );
$( ".menu" ).fadeIn("slow");
$( ".menu" ).animate({opacity: 0.75}, 500);
} else {
$( ".menu" ).removeClass( 'menushow' );
$( ".menu" ).animate({opacity: 1}, 500);
}
});
// progres bar animation simple
$('.bar1').each(function(i) {
var width = $(this).data('width');
$(this).animate({'width' : width + '%' }, 900, function(){
// Animation complete
});
});
1) Note that it is considered insecure to have the .htpasswd
file below the server root.
2) The docs say this about relative paths, so it looks you're out of luck:
File-path is the path to the user file. If it is not absolute (i.e., if it doesn't begin with a slash), it is treated as relative to the ServerRoot.
3) While the answers recommending the use of environment variables work perfectly fine, I would prefer to put a placeholder in the .htaccess
file, or have different versions in my codebase, and have the deployment process set it all up (i. e. replace placeholders or rename / move the appropriate file).
On Java projects, I use Maven to do this type of work, on, say, PHP projects, I like to have a build.sh and / or install.sh shell script that tunes the deployed files to their environment. This decouples your codebase from the specifics of its target environment (i. e. its environment variables and configuration parameters). In general, the application should adapt to the environment, if you do it the other way around, you might run into problems once the environment also has to cater for different applications, or for completely unrelated, system-specific requirements.
After invalidating my cache and restarting; and confirming my maven settings were okay, I was still seeing "Cannot resolve symbol" for a module that I definitely had set as a dependency. Turns out I had it set to the wrong scope.
You can check by right clicking on your module and selecting Open Module Settings. Click the dependency tab and verify that the scope for your un-resolvable dependency is set to Compile.
when you click div with addproduct class one event is fired for that particular element, not five. you're doing something wrong in you code if event is fired 5 times.
I tried this to fix access issues to an IIS website, which manifested as something like the following in the Event Logs ? Windows ? Application:
Log Name: Application Source: ASP.NET 4.0.30319.0 Date: 1/5/2012 4:12:33 PM Event ID: 1314 Task Category: Web Event Level: Information Keywords: Classic User: N/A Computer: SALTIIS01 Description: Event code: 4008 Event message: File authorization failed for the request. Event time: 1/5/2012 4:12:33 PM Event time (UTC): 1/6/2012 12:12:33 AM Event ID: 349fcb2ec3c24b16a862f6eb9b23dd6c Event sequence: 7 Event occurrence: 3 Event detail code: 0 Application information: Application domain: /LM/W3SVC/2/ROOT/Application/SNCDW-19-129702818025409890 Trust level: Full Application Virtual Path: /Application/SNCDW Application Path: D:\Sites\WCF\Application\SNCDW\ Machine name: SALTIIS01 Process information: Process ID: 1896 Process name: w3wp.exe Account name: iisservice Request information: Request URL: http://webservicestest/Application/SNCDW/PC.svc Request path: /Application/SNCDW/PC.svc User host address: 10.60.16.79 User: js3228 Is authenticated: True Authentication Type: Negotiate Thread account name: iisservice
In the end I had to give the Windows Everyone
group read access to that folder to get it to work properly.
This is possible with <textarea>
the only thing you need to do is use
Summernote WYSIWYG editor
it interprets HTML tags inside a textarea (namely <strong>
, <i>
, <u>
, <a>
)
You can use simple following code
String str= "This is a sample sentence.";
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
System.out.print(words[i]+" ");
I prefer to convert arrays to strings:
Assert.assertEquals(
Arrays.toString(values),
Arrays.toString(new int[] { 7, 8, 9, 3 }));
this way I can see clearly where wrong values are. This works effectively only for small sized arrays, but I rarely use arrays with more items than 7 in my unit tests.
This method works for primitive types and for other types when overload of toString
returns all essential information.
For what it's worth here are the step by step instructions for doing this in an Android device. Should be the same for iOS:
You should then be able to see the SSL files in Charles. If you want to intercept and change the values you can use the "Map Local" tool which is really awesome:
This problem has been studied in some depth by physicists. There is a good implementation in ROOT. Look at the TSpectrum classes (especially TSpectrum2 for your case) and the documentation for them.
References:
...and for those who don't have access to a subscription to NIM:
I had same issue with external libraries like ROS headers. I like to use following options in CMakeLists.txt for stricter compilation:
set(CMAKE_CXX_FLAGS "-std=c++0x -Wall -Wextra -Wstrict-aliasing -pedantic -Werror -Wunreachable-code ${CMAKE_CXX_FLAGS}")
However doing this causes all kind of pedantic errors in externally included libraries as well. The solution is to disable all pedantic warnings before you include external libraries and re-enable like this:
//save compiler switches
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
//Bad headers with problem goes here
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
//restore compiler switches
#pragma GCC diagnostic pop
MainCode
Uri raw_uri=Uri.parse("android.resource://<package_name>/+R.raw.<video_file_name>);
myVideoView=(VideoView)findViewbyID(R.idV.Video_view);
myVideoView.setVideoURI(raw_uri);
myVideoView.setMediaController(new MediaController(this));
myVideoView.start();
myVideoView.requestFocus();
XML
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<VideoView
android:id="+@/Video_View"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
While it can be annoying when used as an anti-piracy measure, I can see there might be some instances where it'd be legitimate, so:
function disableCopyPaste(elm) {
// Disable cut/copy/paste key events
elm.onkeydown = interceptKeys
// Disable right click events
elm.oncontextmenu = function() {
return false
}
}
function interceptKeys(evt) {
evt = evt||window.event // IE support
var c = evt.keyCode
var ctrlDown = evt.ctrlKey||evt.metaKey // Mac support
// Check for Alt+Gr (http://en.wikipedia.org/wiki/AltGr_key)
if (ctrlDown && evt.altKey) return true
// Check for ctrl+c, v and x
else if (ctrlDown && c==67) return false // c
else if (ctrlDown && c==86) return false // v
else if (ctrlDown && c==88) return false // x
// Otherwise allow
return true
}
I've used event.ctrlKey
rather than checking for the key code as on most browsers on Mac OS X Ctrl/Alt "down" and "up" events are never triggered, so the only way to detect is to use event.ctrlKey
in the e.g. c event after the Ctrl key is held down. I've also substituted ctrlKey
with metaKey
for macs.
Limitations of this method:
edit
->copy
menu item in e.g. Firefox can still allow copy/pasting.For non-printable keys such as arrow keys and shortcut keys such as Ctrl-z, Ctrl-x, Ctrl-c that may trigger some action in the browser (for instance, inside editable documents or elements), you may not get a keypress event in all browsers. For this reason you have to use keydown
instead, if you're interested in suppressing the browser's default action. If not, keyup
will do just as well.
Attaching a keydown
event to document
works in all the major browsers:
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.ctrlKey && evt.keyCode == 90) {
alert("Ctrl-Z");
}
};
For a complete reference, I strongly recommend Jan Wolter's article on JavaScript key handling.
$( "form" ).bind( "submit", function(e) {_x000D_
e.preventDefault();_x000D_
_x000D_
console.log( $(this).serializeObject() ); _x000D_
_x000D_
//console.log( $(this).serialize() );_x000D_
//console.log( $(this).serializeArray() );_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
$.fn.serializeObject = function() {_x000D_
var o = {};_x000D_
var a = this.serializeArray();_x000D_
_x000D_
$.each( a, function() {_x000D_
if ( o[this.name] !== undefined) _x000D_
{_x000D_
if ( ! o[this.name].push ) _x000D_
{_x000D_
o[this.name] = [o[this.name]];_x000D_
}_x000D_
o[this.name].push(this.value || '');_x000D_
}_x000D_
else _x000D_
{_x000D_
o[this.name] = this.value || '';_x000D_
}_x000D_
});_x000D_
_x000D_
return o;_x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
_x000D_
<input type="radio" name="foo" value="1" checked="checked" />_x000D_
<input type="radio" name="foo" value="0" />_x000D_
<input name="bar" value="xxx" />_x000D_
_x000D_
<select name="this">_x000D_
<option value="hi" selected="selected">Hi</option>_x000D_
<option value="ho">Ho</option>_x000D_
</select>_x000D_
_x000D_
<input type="submit" value="Submit" />_x000D_
_x000D_
</form>
_x000D_
You should be able to declare a cursor to be a bind variable (called parameters in other DBMS')
like Vincent wrote, you can do something like this:
begin
open :yourCursor
for 'SELECT "'|| :someField ||'" from yourTable where x = :y'
using :someFilterValue;
end;
You'd have to bind 3 vars to that script. An input string for "someField", a value for "someFilterValue" and an cursor for "yourCursor" which has to be declared as output var.
Unfortunately, I have no idea how you'd do that from C++. (One could say fortunately for me, though. ;-) )
Depending on which access library you use, it might be a royal pain or straight forward.
routes.MapRoute(
"Area",
"{area}/",
new { area = "AreaZ", controller = "ControlerX ", action = "ActionY " }
);
Have you tried that ?
When you run ajax on your form, you need to tell TinyMCE to update your textarea first:
// TinyMCE will now save the data into textarea
tinyMCE.triggerSave();
// now grap the data
var form_data = form.serialize();
Perhaps this will help you out - I've done something similar using jquery, except I'm loading up an unknown number of ckeditor objects. It took my a while to stumble onto this - it's not clear in the documentation.
function loadEditors() {
var $editors = $("textarea.ckeditor");
if ($editors.length) {
$editors.each(function() {
var editorID = $(this).attr("id");
var instance = CKEDITOR.instances[editorID];
if (instance) { instance.destroy(true); }
CKEDITOR.replace(editorID);
});
}
}
And here is what I run to get the content from the editors:
var $editors = $("textarea.ckeditor");
if ($editors.length) {
$editors.each(function() {
var instance = CKEDITOR.instances[$(this).attr("id")];
if (instance) { $(this).val(instance.getData()); }
});
}
UPDATE: I've changed my answer to use the correct method - which is .destroy(). .remove() is meant to be internal, and was improperly documented at one point.
For those using QT having this error, add this to .pro file
QMAKE_CXXFLAGS_WARN_ON += -Wno-reorder
Football Tipping. I built a GA system to predict the week to week outcome of games in the AFL (Aussie Rules Football).
A few years ago I got bored of the standard work football pool, everybody was just going online and taking the picks from some pundit in the press. So, I figured it couldn't be too hard to beat a bunch of broadcast journalism majors, right? My first thought was to take the results from Massey Ratings and then reveal at the end of the season my strategy after winning fame and glory. However, for reasons I've never discovered Massey does not track AFL. The cynic in me believes it is because the outcome of each AFL game has basically become random chance, but my complaints of recent rule changes belong in a different forum.
The system basically considered offensive strength, defensive strength, home field advantage, week to week improvement (or lack thereof) and velocity of changes to each of these. This created a set of polynomial equations for each team over the season. The winner and score for each match for a given date could be computed. The goal was to find the set of coefficients that most closely matched the outcome of all past games and use that set to predict the upcoming weeks game.
In practice, the system would find solutions that accurately predicted over 90% of past game outcomes. It would then successfully pick about 60-80% of games for the upcoming week (that is the week not in the training set).
The result: just above middle of the pack. No major cash prize nor a system that I could use to beat Vegas. It was fun though.
I built everything from scratch, no framework used.
Annotations in Java, provide a mean to describe classes, fields and methods. Essentially, they are a form of metadata added to a Java source file, they can't affect the semantics of a program directly. However, annotations can be read at run-time using Reflection & this process is known as Introspection. Then it could be used to modify classes, fields or methods.
This feature, is often exploited by Libraries & SDKs (hibernate, JUnit, Spring Framework) to simplify or reduce the amount of code that a programmer would unless do in orer to work with these Libraries or SDKs.Therefore, it's fair to say Annotations and Reflection work hand-in hand in Java.
We also get to limit the availability of an annotation to either compile-time or runtime.Below is a simple example on creating a custom annotation
Driver.java
package io.hamzeen;
import java.lang.annotation.Annotation;
public class Driver {
public static void main(String[] args) {
Class<TestAlpha> obj = TestAlpha.class;
if (obj.isAnnotationPresent(IssueInfo.class)) {
Annotation annotation = obj.getAnnotation(IssueInfo.class);
IssueInfo testerInfo = (IssueInfo) annotation;
System.out.printf("%nType: %s", testerInfo.type());
System.out.printf("%nReporter: %s", testerInfo.reporter());
System.out.printf("%nCreated On: %s%n%n",
testerInfo.created());
}
}
}
TestAlpha.java
package io.hamzeen;
import io.hamzeen.IssueInfo;
import io.hamzeen.IssueInfo.Type;
@IssueInfo(type = Type.IMPROVEMENT, reporter = "Hamzeen. H.")
public class TestAlpha {
}
IssueInfo.java
package io.hamzeen;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Hamzeen. H.
* @created 10/01/2015
*
* IssueInfo annotation definition
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IssueInfo {
public enum Type {
BUG, IMPROVEMENT, FEATURE
}
Type type() default Type.BUG;
String reporter() default "Vimesh";
String created() default "10/01/2015";
}
Disabling pyright worked perfectly for me on VS.
One reason to have both is so that authentication can be done by the database server, but authorization can be scoped to the database. That way, if you move your database to another server, you can always remap the user-login relationship on the database server, but your database doesn't have to change.
You could attempt to load the the https page in an iframe and route all ajax requests in/out of the frame via some bridge, it's a hackaround but it might work (not sure if it will impose the same access restrictions given the secure context). Otherwise a local http proxy to reroute requests (like any cross domain calls) would be the accepted solution.
foreach (DataGridViewColumn c in dataGridView.Columns)
c.Width = c.GetPreferredWidth(DataGridViewAutoSizeColumnMode.AllCells, true);
This should work whether the dataGridView
has been displayed or not (i.e. even if called from the class constructor).
The same method, but with DataGridViewAutoSizeColumnMode.DisplayedCells
, fails in the above case for the obvious reason - no cell has been displayed yet! For some non-obvious reason, AutoResizeColumns
also fails in this case.
Password boxes are also textboxes, so if you need them too:
$("input[type='text'], textarea, input[type='password']").css({width: "90%"});
and while file-input is a bit different, you may want to include them too (eg. for visual consistency):
$("input[type='text'], textarea, input[type='password'], input[type='file']").css({width: "90%"});
Try this simple class for customizing a dialog to your liking:
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
public class CustomDialog
{
private List<JComponent> components;
private String title;
private int messageType;
private JRootPane rootPane;
private String[] options;
private int optionIndex;
public CustomDialog()
{
components = new ArrayList<>();
setTitle("Custom dialog");
setMessageType(JOptionPane.PLAIN_MESSAGE);
setRootPane(null);
setOptions(new String[] { "OK", "Cancel" });
setOptionSelection(0);
}
public void setTitle(String title)
{
this.title = title;
}
public void setMessageType(int messageType)
{
this.messageType = messageType;
}
public void addComponent(JComponent component)
{
components.add(component);
}
public void addMessageText(String messageText)
{
JLabel label = new JLabel("<html>" + messageText + "</html>");
components.add(label);
}
public void setRootPane(JRootPane rootPane)
{
this.rootPane = rootPane;
}
public void setOptions(String[] options)
{
this.options = options;
}
public void setOptionSelection(int optionIndex)
{
this.optionIndex = optionIndex;
}
public int show()
{
int optionType = JOptionPane.OK_CANCEL_OPTION;
Object optionSelection = null;
if(options.length != 0)
{
optionSelection = options[optionIndex];
}
int selection = JOptionPane.showOptionDialog(rootPane,
components.toArray(), title, optionType, messageType, null,
options, optionSelection);
return selection;
}
public static String getLineBreak()
{
return "<br>";
}
}
You should check out this plugin:
https://github.com/kemayo/maphilight
and the demo:
http://davidlynch.org/js/maphilight/docs/demo_usa.html
if anything, you might be able to borrow some code from it to fix yours.
It's simple using a table:
<html>
<head>
<title>100% Height test</title>
</head>
<body>
<table style="float: left; height: 100%; width: 200px; border: 1px solid red">
<tbody>
<tr>
<td>Nav area</td>
</tr>
</tbody>
</table>
<div style="border: 1px solid green;">Content blabla... text
<br /> text
<br /> text
<br /> text
<br />
</div>
</body>
</html>
When DIV was introduced, people were so afraid of tables that the poor DIV became the metaphorical hammer.
Sadly the other posters are correct that you're
...actually as corrected by kRON, you are ok with your IE7 and a strict doc, but most of us with IE6 requirements are reduced to JS or class references for this, but it is a CSS2 property, just one without sufficient support from IE^h^h browsers.
Out of completeness, the type selector is - similar to xpath - of the form [attribute=value]
but many interesting variants exist. It will be quite powerful when it's available, good thing to keep in your head for IE8.
For single-threaded programs you can use igprof, The Ignominous Profiler: https://igprof.org/ .
It is a sampling profiler, along the lines of the... long... answer by Mike Dunlavey, which will gift wrap the results in a browsable call stack tree, annotated with the time or memory spent in each function, either cumulative or per-function.
Try this, pick or create one column and make that value required so that it's always populated such as title. A field that doesn't hold the name of the folder. Then in your filter put the filter you wanted that will select only the files you want. Then add an or to your filter, select your "required" field then set it equal to and leave the filter blank. Since all folders will have a blank in this required field your folders will show up with your files.
I don´t remember the source of this answer (I guess I found it in a .ppt in the internet), but the answer is quite simple.
A Library and a Framework are a set of classes, modules and/or code (depending of the programing language) that can be used in your applications and helps you to solve an especific "problem".
That problem can be log or debuging info in an application, draw charts, create an specific file format (html, pdf, xls), connect to a data base, create a part of an application or a complete application or a code applied to a Design Pattern.
You can have a Framework or a Library to solve all these problems and many more, normaly the frameworks helps you to solve more complex or bigger problems, but that a consecuence of their main difference, not a main definition for both.
The main difference betwen a Library and a Framework is the dependency betwen their own code, in oder words to use a Framework you need to use almost all the classes, modules or code in the FW, but to use a Library you can use one or few classes, modules or code in the lib in your own application
This means that if a Framework has, for example has 50 classes in order to use the framework in an app you need to use, let said, 10-15 or more classes in your code, because that is how is designed a Framework, some classes (objects of that classes) are inputs/parameters for methods in other classes in the framework. See the .NET framework, Spring, or any MVC framework.
But for example a log library, you can just use a Log class in your code, and helps you to solve the "logging problem", that doesn´t mean that the log library doesn't have more classes in his code, like classes to handle files, handle screen outputs, or even data bases, but you never touch/use that classes in your code, and that is the reason of why is a library and not a framework.
And also there are more categories than Frameworks and Libraries, but that is off topic.
I suppose there are applications written in C# running fast, as well as there are more C++ written apps running fast (well C++ just older... and take UNIX too...)
- the question indeed is - what is that thing, users and developers are complaining about ...
Well, IMHO, in case of C# we have very comfort UI, very nice hierarchy of libraries, and whole interface system of CLI. In case of C++ we have templates, ATL, COM, MFC and whole shebang of alreadyc written and running code like OpenGL, DirectX and so on... Developers complains of indeterminably risen GC calls in case of C# (means program runs fast, and in one second - bang! it's stuck).
To write code in C# very simple and fast (not to forget that also increase chance of errors.
In case of C++, developers complains of memory leaks, - means crushes, calls between DLLs, as well as of "DLL hell" - problem with support and replacement libraries by newer ones...
I think more skill you'll have in the programming language, the more quality (and speed) will characterize your software.
I'll add Crypto-Gram Security Podcast. Basically, Dan Henage reading Bruce Schneier newsletter Crypto-Gram.
Most of the other podcasts I listen to have been mentioned (TwiT, Security Now!, Cranky Geeks).
my 2c
The button isn't called the "browse button" — that's just the name your browser gives for it. Browsers are free to implement the file upload control however they like. In Safari, for example, it's called "Choose File" and it's on the opposite side of whatever you're probably using.
You can implement a custom look for the upload control using the technique outlined on QuirksMode, but that goes beyond just changing the button's text.
For Eclipse/STS v3.9.X windows user, you may need to update your subclipse version.
Go to Help > Install New Software > Click on Subclipse and edit the version from 1.6.X to 1.8.X
This method also apply to those who encounter JavaHL not available. You can check whether JavaHL is available or not by Go to Windows > Preference > Team > SVN. You may check it in SVN Interface > Client section.
If this work on MAC OS, kindly response in comment section. :)
From JPA 2.1 , JPA supports to call stored procedures using the dynamic StoredProcedureQuery, and the declarative @NamedStoredProcedureQuery.
You will need to add the values in the array one at a time.
var parameters = new string[items.Length];
var cmd = new SqlCommand();
for (int i = 0; i < items.Length; i++)
{
parameters[i] = string.Format("@Age{0}", i);
cmd.Parameters.AddWithValue(parameters[i], items[i]);
}
cmd.CommandText = string.Format("SELECT * from TableA WHERE Age IN ({0})", string.Join(", ", parameters));
cmd.Connection = new SqlConnection(connStr);
UPDATE: Here is an extended and reusable solution that uses Adam's answer along with his suggested edit. I improved it a bit and made it an extension method to make it even easier to call.
public static class SqlCommandExt
{
/// <summary>
/// This will add an array of parameters to a SqlCommand. This is used for an IN statement.
/// Use the returned value for the IN part of your SQL call. (i.e. SELECT * FROM table WHERE field IN ({paramNameRoot}))
/// </summary>
/// <param name="cmd">The SqlCommand object to add parameters to.</param>
/// <param name="paramNameRoot">What the parameter should be named followed by a unique value for each value. This value surrounded by {} in the CommandText will be replaced.</param>
/// <param name="values">The array of strings that need to be added as parameters.</param>
/// <param name="dbType">One of the System.Data.SqlDbType values. If null, determines type based on T.</param>
/// <param name="size">The maximum size, in bytes, of the data within the column. The default value is inferred from the parameter value.</param>
public static SqlParameter[] AddArrayParameters<T>(this SqlCommand cmd, string paramNameRoot, IEnumerable<T> values, SqlDbType? dbType = null, int? size = null)
{
/* An array cannot be simply added as a parameter to a SqlCommand so we need to loop through things and add it manually.
* Each item in the array will end up being it's own SqlParameter so the return value for this must be used as part of the
* IN statement in the CommandText.
*/
var parameters = new List<SqlParameter>();
var parameterNames = new List<string>();
var paramNbr = 1;
foreach (var value in values)
{
var paramName = string.Format("@{0}{1}", paramNameRoot, paramNbr++);
parameterNames.Add(paramName);
SqlParameter p = new SqlParameter(paramName, value);
if (dbType.HasValue)
p.SqlDbType = dbType.Value;
if (size.HasValue)
p.Size = size.Value;
cmd.Parameters.Add(p);
parameters.Add(p);
}
cmd.CommandText = cmd.CommandText.Replace("{" + paramNameRoot + "}", string.Join(",", parameterNames));
return parameters.ToArray();
}
}
It is called like this...
var cmd = new SqlCommand("SELECT * FROM TableA WHERE Age IN ({Age})");
cmd.AddArrayParameters("Age", new int[] { 1, 2, 3 });
Notice the "{Age}" in the sql statement is the same as the parameter name we are sending to AddArrayParameters. AddArrayParameters will replace the value with the correct parameters.
When you are going back and forth between scripts it may only sometimes be necessary to unload a package. Here's a simple IF statement that will prevent warnings that would appear if you tried to unload a package that was not currently loaded.
if("package:vegan" %in% search()) detach("package:vegan", unload=TRUE)
Including this at the top of a script might be helpful.
I hope that makes your day!
Just run below to your pem's
sudo chmod 600 /path/to/my/key.pem
Solution:
SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5','your text')),3,32)
Have a look at Determine and count unique values of an array.
Or, to count the number of occurrences of 5
, simply do
sum(your_matrix == 5)
I would use javascript for this.
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://my.remote.url/myremotefile.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4 && txtFile.status == 200) {
allText = txtFile.responseText;
}
document.getElementById('your div id').innerHTML = allText;
This is just a code sample, would need tweaking for all browsers, etc.
Usually, the correct way of updating certain fields in one or more model instances is to use the update()
method on the respective queryset. Then you do something like this:
affected_surveys = Survey.objects.filter(
# restrict your queryset by whatever fits you
# ...
).update(active=True)
This way, you don't need to call save()
on your model anymore because it gets saved automatically. Also, the update()
method returns the number of survey instances that were affected by your update.
I had a similar problem and the solution was to do this:
#cloud-container{
position:absolute;
top:0;
bottom:0;
}
I wanted a page-centered div with height 100% of page height, so my total solution was:
#cloud-container{
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
width: XXXpx; /*otherwise div defaults to page width*/
margin: 0 auto; /*horizontally centers div*/
}
You might need to make a parent element (or simply 'body') have position: relative;
Try my solution, I tried it in IE 6, FF2 and Chrome and it renders pixel by pixel in all the three browsers.
* {_x000D_
padding: 0px;_x000D_
margin: 0px;_x000D_
}_x000D_
#wb {_x000D_
width: 15px;_x000D_
height: 15px;_x000D_
float: left;_x000D_
}_x000D_
#somelabel {_x000D_
float: left;_x000D_
padding-left: 3px;_x000D_
}
_x000D_
<div>_x000D_
<input id="wb" type="checkbox" />_x000D_
<label for="wb" id="somelabel">Web Browser</label>_x000D_
</div>
_x000D_
If you want color animation like this,
this code will help you:
ValueAnimator anim = ValueAnimator.ofFloat(0, 1);
anim.setDuration(2000);
float[] hsv;
int runColor;
int hue = 0;
hsv = new float[3]; // Transition color
hsv[1] = 1;
hsv[2] = 1;
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
hsv[0] = 360 * animation.getAnimatedFraction();
runColor = Color.HSVToColor(hsv);
yourView.setBackgroundColor(runColor);
}
});
anim.setRepeatCount(Animation.INFINITE);
anim.start();
To only find the first locations, use lapply()
with min()
:
my_string <- c("test1", "test1test1", "test1test1test1")
unlist(lapply(gregexpr(pattern = '1', my_string), min))
#> [1] 5 5 5
# or the readable tidyverse form
my_string %>%
gregexpr(pattern = '1') %>%
lapply(min) %>%
unlist()
#> [1] 5 5 5
To only find the last locations, use lapply()
with max()
:
unlist(lapply(gregexpr(pattern = '1', my_string), max))
#> [1] 5 10 15
# or the readable tidyverse form
my_string %>%
gregexpr(pattern = '1') %>%
lapply(max) %>%
unlist()
#> [1] 5 10 15
@Hooman: actually with the latest versions of Xampp you don't need to know where the configuration or log files are; in the Control panel you have log and config buttons for each tool (php, mysql, tomcat...) and clicking them offers to open all the relevant file (you can even change the default editing application with the general Config button at the top right). Well done for whoever designed it!
Use attribute binding syntax instead
<ol class="viewer-nav"><li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value">{{ section.text }}</li>
</ol>
or
<ol class="viewer-nav"><li *ngFor="let section of sections"
attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>
</ol>
Within an htaccess file, the scope of the <Files>
directive only applies to that directory (I guess to avoid confusion when rules/directives in the htaccess of subdirectories get applied superceding ones from the parent).
So you can have:
<Files "log.txt">
Order Allow,Deny
Deny from all
</Files>
For Apache 2.4+, you'd use:
<Files "log.txt">
Require all denied
</Files>
In an htaccess file in your inscription
directory. Or you can use mod_rewrite to sort of handle both cases deny access to htaccess file as well as log.txt:
RewriteRule /?\.htaccess$ - [F,L]
RewriteRule ^/?inscription/log\.txt$ - [F,L]
This worked on my test file (note the index in VBA starts from zero):
Sub DV_Test()
Dim ValidationList(5) As Variant, i As Integer
For i = 0 To UBound(ValidationList)
ValidationList(i) = i + 1
Next
With Range("A1").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlEqual, Formula1:=Join(ValidationList, ",")
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
I used xlEqual
because that's what I think you are trying to get people to select one of the list.
Upgrading node.js to the latest version on Windows
Install chocolatey if you haven't already: Installing Chocolatey
From the command prompt, type
cup nodejs
(which is equivalent to typing choco upgrade nodejs
-- assumes you already have node installed)
NOTE: You may need to run cinst nodejs.install
for chocolatey to register your existing installation. (thanks for the comment, @mikecheel)
Installing node.js on Windows
If you have never installed node, you can use chocolatey to do that as well. Install chocolatey (see step 1 above). Then from a command prompt, type:
cinst nodejs.install
Chocolatey Gallery Node JS (Install)
Installing a specific version of node on Windows with chocolatey
cinst nodejs.install -Version 0.10.26
I fixed my problem with the following code:
<div style="width: 180px; overflow: hidden;">_x000D_
<select style="width: auto;" name="abc" id="10">_x000D_
<option value="-1">AAAAAAAAAAA</option>_x000D_
<option value="123">123</option>_x000D_
</select>_x000D_
</div>
_x000D_
Hope it helps!
This is (of course) totally VM-dependent.
Browsing through the source code of OpenJDK 7 and 8 java.util.ArrayList
, .Hashtable
, .AbstractCollection
, .PriorityQueue
, and .Vector
, you can see this claim being repeated:
/** * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
which is added by Martin Buchholz (Google) on 2010-05-09; reviewed by Chris Hegarty (Oracle).
So, probably we can say that the maximum "safe" number would be 2 147 483 639 (Integer.MAX_VALUE - 8
) and "attempts to allocate larger arrays may result in OutOfMemoryError".
(Yes, Buchholz's standalone claim does not include backing evidence, so this is a calculated appeal to authority. Even within OpenJDK itself, we can see code like return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
which shows that MAX_ARRAY_SIZE
does not yet have a real use.)
To zoom on Eclipse you can use : CTRL SHIFT + OR -
I don't think the standard HTML select will display HTML content. I'd suggest checking out Bootstrap select: http://silviomoreto.github.io/bootstrap-select/
It has several options for displaying icons or other HTML markup in the select.
<select id="mySelect" data-show-icon="true">
<option data-content="<i class='glyphicon glyphicon-cutlery'></i>">-</option>
<option data-subtext="<i class='glyphicon glyphicon-eye-open'></i>"></option>
<option data-subtext="<i class='glyphicon glyphicon-heart-empty'></i>"></option>
<option data-subtext="<i class='glyphicon glyphicon-leaf'></i>"></option>
<option data-subtext="<i class='glyphicon glyphicon-music'></i>"></option>
<option data-subtext="<i class='glyphicon glyphicon-send'></i>"></option>
<option data-subtext="<i class='glyphicon glyphicon-star'></i>"></option>
</select>
Here is a demo: https://www.codeply.com/go/l6ClKGBmLS
Sounds like you'd be better served by a singleton rather than a bunch of static methods
class Singleton
{
/**
*
* @var Singleton
*/
private static $instance;
private function __construct()
{
// Your "heavy" initialization stuff here
}
public static function getInstance()
{
if ( is_null( self::$instance ) )
{
self::$instance = new self();
}
return self::$instance;
}
public function someMethod1()
{
// whatever
}
public function someMethod2()
{
// whatever
}
}
And then, in usage
// As opposed to this
Singleton::someMethod1();
// You'd do this
Singleton::getInstance()->someMethod1();
None of these answers worked for me, when all I had was a list of directories. Then I stumbled upon the solution! You have to add -r
to --files-from
because -a
will not be recursive in this scenario (who knew?!).
rsync -aruRP --files-from=directory.list . ../new/location
When you use %
for setting heights or widths, always set the widths/heights of parent elements as well:
.table {_x000D_
display: table;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
border: 2px solid black;_x000D_
vertical-align: top;_x000D_
display: table-cell;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.container {_x000D_
height: 100%;_x000D_
border: 2px solid green;_x000D_
-moz-box-sizing: border-box;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="cell">_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
</div>_x000D_
<div class="cell">_x000D_
<div class="container">Text</div>_x000D_
</div>_x000D_
</div>
_x000D_
Use mavenCentral()
or jcenter()
adding in the build.gradle
file the script:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
}
}
You can use the for each toolbox from http://www.mathworks.com/matlabcentral/fileexchange/48729-for-each.
>> signal
signal =
sin: {{1x1x25 cell} {1x1x25 cell}}
cos: {{1x1x25 cell} {1x1x25 cell}}
>> each(fieldnames(signal))
ans =
CellIterator with properties:
NumberOfIterations: 2.0000e+000
Usage:
for bridge = each(fieldnames(signal))
signal.(bridge) = rand(10);
end
I like it very much. Credit of course go to Jeremy Hughes who developed the toolbox.
In my case, I used a keyword as a column name, which resulted in ERROR: operator does not exist: name = bigint
The solution was to use double quotes around the column name.
I just got that problem when converting from %
formatting to .format()
.
Previous code:
"SET !TIMEOUT_STEP %{USER_TIMEOUT_STEP}d" % {'USER_TIMEOUT_STEP' = 3}
Problematic syntax:
"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format('USER_TIMEOUT_STEP' = 3)
The problem is that format
is a function that needs parameters. They cannot be strings.
That is one of worst python error messages I've ever seen.
Corrected code:
"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format(USER_TIMEOUT_STEP = 3)
I use Bootstrap 3.4 For me this does not work
$('#myModal').modal('hide')
In desperation,I did this:
$('#myModal').hide();
$('.modal-backdrop').hide();
Maybe it's not elegant, but it works
Similar questions are here
detect line breaks in a text area input
You can try this:
var submit = document.getElementById('submit');_x000D_
_x000D_
submit.addEventListener('click', function(){_x000D_
var textContent = document.querySelector('textarea').value;_x000D_
_x000D_
document.getElementById('output').innerHTML = textContent.replace(/\n/g, '<br/>');_x000D_
_x000D_
_x000D_
});
_x000D_
<textarea cols=30 rows=10 >This is some text_x000D_
this is another text_x000D_
_x000D_
Another text again and again</textarea>_x000D_
<input type='submit' id='submit'>_x000D_
_x000D_
_x000D_
<p id='output'></p>
_x000D_
document.querySelector('textarea').value;
will get the text content of the
textarea and textContent.replace(/\n/g, '<br/>')
will find all the newline character in the source code /\n/g
in the content and replace it with the html line-break <br/>
.
Another option is to use the html <pre>
tag. See the demo below
var submit = document.getElementById('submit');_x000D_
_x000D_
submit.addEventListener('click', function(){_x000D_
_x000D_
var content = '<pre>';_x000D_
_x000D_
var textContent = document.querySelector('textarea').value;_x000D_
_x000D_
content += textContent;_x000D_
_x000D_
content += '</pre>';_x000D_
_x000D_
document.getElementById('output').innerHTML = content;_x000D_
_x000D_
});
_x000D_
<textarea cols=30 rows=10>This is some text_x000D_
this is another text_x000D_
_x000D_
Another text again and again </textarea>_x000D_
<input type='submit' id='submit'>_x000D_
_x000D_
<div id='output'> </div>
_x000D_
I know this has already been answered, but I wanted to share a potentially better looking way to call Popen via the use of from x import x
and functions:
from subprocess import PIPE, Popen
def cmdline(command):
process = Popen(
args=command,
stdout=PIPE,
shell=True
)
return process.communicate()[0]
print cmdline("cat /etc/services")
print cmdline('ls')
print cmdline('rpm -qa | grep "php"')
print cmdline('nslookup google.com')
I've tried this in Python 3.6.9
>>> hours, minutes, seconds = 9, 33, 35
>>> time = f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
>>> print (time)
09:33:35 am
>>> type(time)
<class 'str'>
This only works after you save a bookmark to the app to the home screen. Not if you just browse to the site normally.
To truly force maven to only use your local repo, you can run with mvn <goals> -o
. The -o
tells maven to let you work "offline", and it will stay off the network.
IE does not support for(i in obj) for native properties. Here is a list of all the props I could find.
It seems stackoverflow does some stupid filtering.
The list is available at the bottom of this google group post:- https://groups.google.com/group/hackvertor/browse_thread/thread/a9ba81ca642a63e0
UseParNewGC usually knowns as "parallel young generation collector" is same in all ways as the parallel garbage collector (-XX:+UseParallelGC), except that its more sophiscated and effiecient. Also it can be used with a "concurrent low pause collector".
See Java GC FAQ, question 22 for more information.
Note that there are some known bugs with UseParNewGC
td.description {vertical-align: top;}
where description
is the class name of the td
with that text in it
td.description {_x000D_
vertical-align: top;_x000D_
}
_x000D_
<td class="description">Description</td>
_x000D_
OR inline (yuk!)
<td style="vertical-align: top;">Description</td>
_x000D_
You must sort your data according your needs (es. in reverse order) and use select top query
You can use IterableOf
from Cactoos:
Iterable<String> names = new IterableOf<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
);
Then, you can turn it into a list using ListOf
:
List<String> names = new ListOf<>(
new IterableOf<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
)
);
Or simply this:
List<String> names = new ListOf<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
);
What kind of processing are you trying to do? You can do XmlDocument doc = new XmlDocument();
followed by doc.Load(filename)
. Then the XML document can be parsed in memory.
Read here for more information on XmlDocument:
You're nesting mocking inside of mocking. You're calling getSomeList()
, which does some mocking, before you've finished the mocking for MyMainModel
. Mockito doesn't like it when you do this.
Replace
@Test
public myTest(){
MyMainModel mainModel = Mockito.mock(MyMainModel.class);
Mockito.when(mainModel.getList()).thenReturn(getSomeList()); --> Line 355
}
with
@Test
public myTest(){
MyMainModel mainModel = Mockito.mock(MyMainModel.class);
List<SomeModel> someModelList = getSomeList();
Mockito.when(mainModel.getList()).thenReturn(someModelList);
}
To understand why this causes a problem, you need to know a little about how Mockito works, and also be aware in what order expressions and statements are evaluated in Java.
Mockito can't read your source code, so in order to figure out what you are asking it to do, it relies a lot on static state. When you call a method on a mock object, Mockito records the details of the call in an internal list of invocations. The when
method reads the last of these invocations off the list and records this invocation in the OngoingStubbing
object it returns.
The line
Mockito.when(mainModel.getList()).thenReturn(someModelList);
causes the following interactions with Mockito:
mainModel.getList()
is called,when
is called,thenReturn
is called on the OngoingStubbing
object returned by the when
method.The thenReturn
method can then instruct the mock it received via the OngoingStubbing
method to handle any suitable call to the getList
method to return someModelList
.
In fact, as Mockito can't see your code, you can also write your mocking as follows:
mainModel.getList();
Mockito.when((List<SomeModel>)null).thenReturn(someModelList);
This style is somewhat less clear to read, especially since in this case the null
has to be casted, but it generates the same sequence of interactions with Mockito and will achieve the same result as the line above.
However, the line
Mockito.when(mainModel.getList()).thenReturn(getSomeList());
causes the following interactions with Mockito:
mainModel.getList()
is called,when
is called,mock
of SomeModel
is created (inside getSomeList()
),model.getName()
is called,At this point Mockito gets confused. It thought you were mocking mainModel.getList()
, but now you're telling it you want to mock the model.getName()
method. To Mockito, it looks like you're doing the following:
when(mainModel.getList());
// ...
when(model.getName()).thenReturn(...);
This looks silly to Mockito
as it can't be sure what you're doing with mainModel.getList()
.
Note that we did not get to the thenReturn
method call, as the JVM needs to evaluate the parameters to this method before it can call the method. In this case, this means calling the getSomeList()
method.
Generally it is a bad design decision to rely on static state, as Mockito does, because it can lead to cases where the Principle of Least Astonishment is violated. However, Mockito's design does make for clear and expressive mocking, even if it leads to astonishment sometimes.
Finally, recent versions of Mockito add an extra line to the error message above. This extra line indicates you may be in the same situation as this question:
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
you can simply cast a string array to int array by:
var converted = arr.Select(int.Parse)
An important thing to consider is that some users and some resellers (Dell) install a 64 bit VM on their 64 bit Windows, and you can't use the same SWT library on 32 bit and 64 bit VMs.
This means you will need to distribute and test different packages depending on whether users have 32-bit or a 64-bit Java VM. See this problem with Azureus, for instance, but you also have it with Eclipse, where as of today the builds on the front download page do not run on a 64 bit VM.
In a typical application there is a UITabBarController and it embeds 3 or more UIViewController as its tabs. In such a case if you subclassed a UITabBarController as YourTabBarController then you can set the selected index simply by:
selectedIndex = 1 // Displays 2nd tab. The index starts from 0.
In case you are navigating to YourTabBarController from any other view, then in that view controller's prepare(for segue:) method you can do:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
if segue.identifier == "SegueToYourTabBarController" {
if let destVC = segue.destination as? YourTabBarController {
destVC.selectedIndex = 0
}
}
I am using this way of setting tab with Xcode 10 and Swift 4.2.
I've tested this for my project, it finds the max/min in O(n) time:
from django.db.models import Max
# Find the maximum value of the rating and then get the record with that rating.
# Notice the double underscores in rating__max
max_rating = App.objects.aggregate(Max('rating'))['rating__max']
return App.objects.get(rating=max_rating)
This is guaranteed to get you one of the maximum elements efficiently, rather than sorting the whole table and getting the top (around O(n*logn)).
I want to mention the Ning Async Http Client Library. I've never used it but my colleague raves about it as compared to the Apache Http Client, which I've always used in the past. I was particularly interested to learn it is based on Netty, the high-performance asynchronous i/o framework, with which I am more familiar and hold in high esteem.
$('#new_user_form').find('input').each(function(){
//your code here
});
See example.
/**
* nv_get_plaintext()
*
* @param mixed $string
* @return
*/
function nv_get_plaintext( $string, $keep_image = false, $keep_link = false )
{
// Get image tags
if( $keep_image )
{
if( preg_match_all( "/\<img[^\>]*src=\"([^\"]*)\"[^\>]*\>/is", $string, $match ) )
{
foreach( $match[0] as $key => $_m )
{
$textimg = '';
if( strpos( $match[1][$key], 'data:image/png;base64' ) === false )
{
$textimg = " " . $match[1][$key];
}
if( preg_match_all( "/\<img[^\>]*alt=\"([^\"]+)\"[^\>]*\>/is", $_m, $m_alt ) )
{
$textimg .= " " . $m_alt[1][0];
}
$string = str_replace( $_m, $textimg, $string );
}
}
}
// Get link tags
if( $keep_link )
{
if( preg_match_all( "/\<a[^\>]*href=\"([^\"]+)\"[^\>]*\>(.*)\<\/a\>/isU", $string, $match ) )
{
foreach( $match[0] as $key => $_m )
{
$string = str_replace( $_m, $match[1][$key] . " " . $match[2][$key], $string );
}
}
}
$string = str_replace( ' ', ' ', strip_tags( $string ) );
return preg_replace( '/[ ]+/', ' ', $string );
}
Create responsive tables by wrapping any .table with .table-responsive{-sm|-md|-lg|-xl}, making the table scroll horizontally at each max-width breakpoint of up to (but not including) 576px, 768px, 992px, and 1120px, respectively.
just wrap table with .table-responsive{-sm|-md|-lg|-xl}
for example
<div class="table-responsive-md">
<table class="table">
</table>
</div>
You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.
Here is a complete example from your data that shows a bar of for each required value at each date:
import pylab as pl
import datetime
data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""
values = []
dates = []
for line in data.split("\n"):
x, y = line.split()
values.append(int(x))
dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())
fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()
You need to parse the date with strptime
and set the x-axis to use dates (as described in this answer).
If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:
fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)
EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks
(and move them by half the bar width):
fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)
The Multipart File Upload worked after following code modification to Upload using RestTemplate
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new ClassPathResource(file));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<LinkedMultiValueMap<String, Object>>(
map, headers);
ResponseEntity<String> result = template.get().exchange(
contextPath.get() + path, HttpMethod.POST, requestEntity,
String.class);
And adding MultipartFilter to web.xml
<filter>
<filter-name>multipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>multipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
An Ad-Hoc Query is a query that cannot be determined prior to the moment the query is issued. It is created in order to get information when need arises and it consists of dynamically constructed SQL which is usually constructed by desktop-resident query tools.
Check: http://www.learn.geekinterview.com/data-warehouse/dw-basics/what-is-an-ad-hoc-query.html
If you just want to know package name, run adb logcat, launch the activity you want , you will get a hint on the package name.
The way I interpreted this question is needing the subtotal value of each group of answers. Subtotaling turns out to be very easy, using PARTITION
:
SUM(COUNT(0)) OVER (PARTITION BY [Grouping]) AS [MY_TOTAL]
This is what my full SQL call looks like:
SELECT MAX(GroupName) [name], MAX(AUX2)[type],
COUNT(0) [count], SUM(COUNT(0)) OVER(PARTITION BY GroupId) AS [total]
FROM [MyView]
WHERE Active=1 AND Type='APP' AND Completed=1
AND [Date] BETWEEN '01/01/2014' AND GETDATE()
AND Id = '5b9xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' AND GroupId IS NOT NULL
GROUP BY AUX2, GroupId
The data returned from this looks like:
name type count total
Training Group 2 Cancelation 1 52
Training Group 2 Completed 41 52
Training Group 2 No Show 6 52
Training Group 2 Rescheduled 4 52
Training Group 3 NULL 4 10535
Training Group 3 Cancelation 857 10535
Training Group 3 Completed 7923 10535
Training Group 3 No Show 292 10535
Training Group 3 Rescheduled 1459 10535
Training Group 4 Cancelation 2 27
Training Group 4 Completed 24 27
Training Group 4 Rescheduled 1 27
Use the @Input() decorator in your child component to allow the parent to bind to this input.
In the child component you declare it as is :
@Input() myInputName: myType
To bind a property from parent to a child you must add in you template the binding brackets and the name of your input between them.
Example :
<my-child-component [myChildInputName]="myParentVar"></my-child-component>
But beware, objects are passed as a reference, so if the object is updated in the child the parent's var will be too updated. This might lead to some unwanted behaviour sometime. With primary types the value is copied.
To go further read this :
Docs : https://angular.io/docs/ts/latest/cookbook/component-communication.html
Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:
json: cannot unmarshal object into Go struct field Comment.author of type string
Use the NORMINV
function together with RAND()
:
=NORMINV(RAND(),10,7)
To keep your set of random values from changing, select all the values, copy them, and then paste (special) the values back into the same range.
Sample output (column A), 500 numbers generated with this formula:
the strncpy is a safer version of strcpy as a matter of fact you should never use strcpy because its potential buffer overflow vulnerability which makes you system vulnerable to all sort of attacks
Firstly make sure your API Key is valid and add this into your manifest <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Here's my maps activity.. there might be some redundant information in it since it's from a larger project I created.
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
//These variable are initalized here as they need to be used in more than one methid
private double currentLatitude; //lat of user
private double currentLongitude; //long of user
private double latitudeVillageApartmets= 53.385952001750184;
private double longitudeVillageApartments= -6.599087119102478;
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
/*These methods all have to do with the map and wht happens if the activity is paused etc*/
//contains lat and lon of another marker
private void setUpMap() {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
mMap.addMarker(marker); // adding marker
}
//contains your lat and lon
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("You are here");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
@Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
There's a lot of methods here that are hard to understand but basically all update the map when it's paused etc. There are also connection timeouts etc. Sorry for just posting this, I tried to fix your code but I couldn't figure out what was wrong.
To Check JTextFiled is empty or not condition:
if( (billnotf.getText().length()==0)||(billtabtf.getText().length()==0))
This is very late, but I just wanted to add that there is a more elegant way: using reversed
for i in reversed(range(10)):
print i
gives:
4
3
2
1
0
I would use SimpleDateFormat. Someone correct me if there is an easier way to make a monthed calendar though, I do this in code now and I'm not so sure.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public String formatMonth(int month, Locale locale) {
DateFormat formatter = new SimpleDateFormat("MMMM", locale);
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, month-1);
return formatter.format(calendar.getTime());
}
I'd suggest attaching listeners to key events fired by the editable element, though you need to be aware that keydown
and keypress
events are fired before the content itself is changed. This won't cover every possible means of changing the content: the user can also use cut, copy and paste from the Edit or context browser menus, so you may want to handle the cut
copy
and paste
events too. Also, the user can drop text or other content, so there are more events there (mouseup
, for example). You may want to poll the element's contents as a fallback.
UPDATE 29 October 2014
The HTML5 input
event is the answer in the long term. At the time of writing, it is supported for contenteditable
elements in current Mozilla (from Firefox 14) and WebKit/Blink browsers, but not IE.
Demo:
document.getElementById("editor").addEventListener("input", function() {_x000D_
console.log("input event fired");_x000D_
}, false);
_x000D_
<div contenteditable="true" id="editor">Please type something in here</div>
_x000D_
PostgreSQL understands the
select column_name from information_schema.columns where table_name = 'myTable'
syntax. If you're working in the psql shell, you can also use
\d myTable
for a description (columns, and their datatypes and constraints)
An alternative to theme_classic()
is the theme that comes with the cowplot package, theme_cowplot()
(loaded automatically with the package). It looks similar to theme_classic()
, with a few subtle differences. Most importantly, the default label sizes are larger, so the resulting figures can be used in publications without further modifications needed (in particular if you save them with save_plot()
instead of ggsave()
). Also, the background is transparent, not white, which may be useful if you want to edit the figure in illustrator. Finally, faceted plots look better, in my opinion.
Example:
library(cowplot)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
p <- ggplot(df, aes(x = a, y = b)) + geom_point()
save_plot('plot.png', p) # alternative to ggsave, with default settings that work well with the theme
This is what the file plot.png
produced by this code looks like:
Disclaimer: I'm the package author.
Subclass the ArrayAdapter and override the method getView() to return your own view that contains the contents that you want to display.
you can make a javascript object with key being name of the html snippet, and value being an array of html strings, that are joined together.
var html = {
top_crimes_template:
[
'<div class="top_crimes"><h3>Top Crimes</h3></div>',
'<table class="crimes-table table table-responsive table-bordered">',
'<tr>',
'<th>',
'<span class="list-heading">Crime:</span>',
'</th>',
'<th>',
'<span id="last_crime_span"># Arrests</span>',
'</th>',
'</tr>',
'</table>'
].join(""),
top_teams_template:
[
'<div class="top_teams"><h3>Top Teams</h3></div>',
'<table class="teams-table table table-responsive table-bordered">',
'<tr>',
'<th>',
'<span class="list-heading">Team:</span>',
'</th>',
'<th>',
'<span id="last_team_span"># Arrests</span>',
'</th>',
'</tr>',
'</table>'
].join(""),
top_players_template:
[
'<div class="top_players"><h3>Top Players</h3></div>',
'<table class="players-table table table-responsive table-bordered">',
'<tr>',
'<th>',
'<span class="list-heading">Players:</span>',
'</th>',
'<th>',
'<span id="last_player_span"># Arrests</span>',
'</th>',
'</tr>',
'</table>'
].join("")
};
Since you are the only user:
git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}
( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )
Without doing any changes to your local repo, you can also do something like:
git push -f origin <sha_of_previous_commit>:master
Generally, in published repos, it is safer to do git revert
and then git push
You should be able to match it with: /<primaryAddress>(.+?)<\/primaryAddress>/
The content between the tags will be in the matched group.
Well, this is probably frowned upon but you can make a 1px transparent image, then size it as needed in between text.
Some text <img src="spacer.png" height="1px" width="10px"> Some more text
I've run into this issue when one or two spaces just wasn't enough for my design sensibilities.
change the opacity of the parent element with the border and this will re organize the stacked elements. This worked miraculously for me after hours of research and failed attempts. It was as simple as adding an opacity of 0.99 to re organize this paint process of browsers. Check out http://philipwalton.com/articles/what-no-one-told-you-about-z-index/
document.querySelector("iframe").addEventListener( "load", function(e) {_x000D_
_x000D_
this.style.backgroundColor = "red";_x000D_
alert(this.nodeName);_x000D_
_x000D_
console.log(e.target);_x000D_
_x000D_
} );
_x000D_
<iframe src="example.com" ></iframe>
_x000D_
Using regular expressions is costly in terms of performance. Trying to parse string as a long value is inefficient and unreliable, and may be not what you need.
What I suggest is to simply check if each character is a digit, what can be efficiently done using Java 8 lambda expressions:
boolean isNumeric = someString.chars().allMatch(x -> Character.isDigit(x));
There is no built-in method that allows what you intend to do.
You have to add a method to your repository, like this:
public function getWhatYouWant()
{
$qb = $this->createQueryBuilder('u');
$qb->where('u.id != :identifier')
->setParameter('identifier', 1);
return $qb->getQuery()
->getResult();
}
Hope this helps.
Use the below command to copy data from CSV in a single line without casting and changing your datatype. Please replace "NULL" by your string which creating error in copy data
copy table_name from 'path to csv file' (format csv, null "NULL", DELIMITER ',', HEADER);
you can use ajax calls to call different methods without a postback
$.ajax({
type: "POST",
url: "@(Url.Action("Action", "Controller"))",
data: {id: 'id', id1: 'id1' },
contentType: "application/json; charset=utf-8",
cache: false,
async: true,
success: function (result) {
//do something
}
});
I am using Laravel 4.2. Here how I do it:
I have a directory structure like this one:
app
--controllers
----admin
------AdminController.php
After I have created the controller I've put in the composer.json the path to the new admin directory:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/controllers/admin",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
},
Next I have run
composer dump-autoload
and then
php artisan dump-autoload
Then in the routes.php I have the controller included like this:
Route::controller('admin', 'AdminController');
And everything works fine.
if you really want to get rid of the scrollbar, split the information up into two separate pages.
Usability guidelines on scrollbars by Jakob Nielsen:
There are five essential usability guidelines for scrolling and scrollbars:
- Offer a scrollbar if an area has scrolling content. Don't rely on auto-scrolling or on dragging, which people might not notice.
- Hide scrollbars if all content is visible. If people see a scrollbar, they assume there's additional content and will be frustrated if they can't scroll.
- Comply with GUI standards and use scrollbars that look like scrollbars.
- Avoid horizontal scrolling on Web pages and minimize it elsewhere.
- Display all important information above the fold. Users often decide whether to stay or leave based on what they can see without scrolling. Plus they only allocate 20% of their attention below the fold.
To make your scrollbar only visible when it is needed (i.e. when there is content to scroll down to), use overflow: auto
.
In Oracle PL/SQL cursors will not result in table locks and it is possible to use bulk-collecting/bulk-fetching.
In Oracle 10 the often used implicit cursor
for x in (select ....) loop
--do something
end loop;
fetches implicitly 100 rows at a time. Explicit bulk-collecting/bulk-fetching is also possible.
However PL/SQL cursors are something of a last resort, use them when you are unable to solve a problem with set-based SQL.
Another reason is parallelization, it is easier for the database to parallelize big set-based statements than row-by-row imperative code. It is the same reason why functional programming becomes more and more popular (Haskell, F#, Lisp, C# LINQ, MapReduce ...), functional programming makes parallelization easier. The number CPUs per computer is rising so parallelization becomes more and more an issue.
I had similar issue, the problem i faced was i added the selenium-server-standalone-3.141.59.jar under modulepath instead it should be under classpath
so select classpath via (project -> Properties -> Java Bbuild Path -> Libraries) add the downloaded latest jar
After adding it must be something like this
And appropriate driver for browser has to be downloaded for me i checked and downloaded the same version of chrom for chrome driver and added in the C:\Program Files\Java
And following is the code that worked fine for me
public class TestuiAautomation {
public static void main(String[] args) {
System.out.println("Jai Ganesha");
try {
System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Java\\chromedriver.exe");
System.out.println(System.getProperty("webdriver.chrome.driver"));
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("no-sandbox");
chromeOptions.addArguments("--test-type");
chromeOptions.addArguments("disable-extensions");
chromeOptions.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(chromeOptions);
driver.get("https://www.google.com");
System.out.println("Google is selected");
} catch (Exception e) {
System.err.println(e);
}
}
}
It is one of the MIME
type, in this case you are reponse header MIME
type to text/html
it means it displays html type. It is a information to browser. There are other types you can set to display excel, zip etc. Please see MIME Type
for more information
I had same problem on Mac OS X El Capitan.
When I installed virtualenv
like that sudo pip3 install virtualenv
I didn't have virtualenv
under my command line.
I solved this problem by following those steps:
virtualenv
installation by calling sudo su
virtualenv
by calling pip3 install virtualenv
virtualenv
from both user
and super user
account.I will start my answer saying that most of previous answers were perfectly good answers at the time of writing them. So, thank you to them who wrote them.
Now, you can also use String Interpolation for same solution.
Edit: Adding this explanation after receiving a perfectively valid constructive comment from Heretic Monkey. I have preferred to use .ToString whenever I had need to convert an integer to string and not add the result to any other string. And, I have preferred to use interpolation whenever I had need to combine string(s) and an integer, like in below examples.
i.ToString("00")
01
i.ToString("000")
001
i.ToString("0000")
0001
$"Prefix_{i:00}"
Prefix_01
$"Prefix_{i:000}"
Prefix_001
$"Prefix_{i:0000}_Suffix"
Prefix_0001_Suffix
WORKER TIMEOUT
means your application cannot response to the request in a defined amount of time. You can set this using gunicorn timeout settings. Some application need more time to response than another.
Another thing that may affect this is choosing the worker type
The default synchronous workers assume that your application is resource-bound in terms of CPU and network bandwidth. Generally this means that your application shouldn’t do anything that takes an undefined amount of time. An example of something that takes an undefined amount of time is a request to the internet. At some point the external network will fail in such a way that clients will pile up on your servers. So, in this sense, any web application which makes outgoing requests to APIs will benefit from an asynchronous worker.
When I got the same problem as yours (I was trying to deploy my application using Docker Swarm), I've tried to increase the timeout and using another type of worker class. But all failed.
And then I suddenly realised I was limitting my resource too low for the service inside my compose file. This is the thing slowed down the application in my case
deploy:
replicas: 5
resources:
limits:
cpus: "0.1"
memory: 50M
restart_policy:
condition: on-failure
So I suggest you to check what thing slowing down your application in the first place
Well the answer was sitting right in front of me the whole time.
In SQL Server Management Studio 2008 there is a Debug button in the toolbar. Set a break point in a query window to step through.
I dismissed this functionality at the beginning because I didn't think of stepping INTO the stored procedure, which you can do with ease.
SSMS basically does what FinnNK mentioned with the MSDN walkthrough but automatically.
So easy! Thanks for your help FinnNK.
Edit: I should add a step in there to find the stored procedure call with parameters I used SQL Profiler on my database.
In C++17 this is called structured bindings, which allows for the following:
std::map< foo, bar > testing = { /*...blah...*/ };
for ( const auto& [ k, v ] : testing )
{
std::cout << k << "=" << v << "\n";
}
It is 2021, time to do better than Commons CLI... :-)
Should you build your own Java command line parser, or use a library?
Many small utility-like applications probably roll their own command line parsing to avoid the additional external dependency. picocli may be an interesting alternative.
Picocli is a modern library and framework for building powerful, user-friendly, GraalVM-enabled command line apps with ease. It lives in 1 source file so apps can include it as source to avoid adding a dependency.
It supports colors, autocompletion, subcommands, and more. Written in Java, usable from Groovy, Kotlin, Scala, etc.
Features:
<command> -xvfInputFile
as well as <command> -x -v -f InputFile
)"1..*"
, "3..5"
The usage help message is easy to customize with annotations (without programming). For example:
(source)
I couldn't resist adding one more screenshot to show what usage help messages are possible. Usage help is the face of your application, so be creative and have fun!
Disclaimer: I created picocli. Feedback or questions very welcome.
Using straight Linq, with the Distinct()
extension:
var idList = (from x in yourList select x.ID).Distinct();
You need to specify which object you're calling getElementById from. In this case you can use document. You also can't just call .value on any element directly. For example if the element is textbox .value will return the value, but if it's a div it will not have a value.
You also have a wrong condition, you're checking
if (myEle == null)
which you should change to
if (myEle != null)
var myEle = document.getElementById("myElement");
if(myEle != null) {
var myEleValue= myEle.value;
}
FindIndex seems to be what you're looking for:
FindIndex(Predicate<T>)
Usage:
list1.FindIndex(x => x==5);
Example:
// given list1 {3, 4, 6, 5, 7, 8}
list1.FindIndex(x => x==5); // should return 3, as list1[3] == 5;
@model MVCClient.Models.ProductDetails
@{
ViewBag.Title = "ProductDetails";
}
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Save").click(function () {
var ProductDetails = new Object();
ProductDetails.ProductName = $("#txt_productName").val();
ProductDetails.ProductDetail = $("#txt_desc").val();
ProductDetails.Price= $("#txt_price").val();
$.ajax({
url: "http://localhost:24481/api/Product/addProduct",
type: "Post",
dataType:'JSON',
data:ProductDetails,
success: function (data) {
alert('Updated Successfully');
//window.location.href = "../Index";
},
error: function (msg) { alert(msg); }
});
});
});
</script>
<h2>ProductDetails</h2>
<form id="form1" method="post">
<fieldset>
<legend>ProductDetails</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ProductName)
</div>
<div class="editor-field">
<input id="txt_productName" type="text" name="fname">
@Html.ValidationMessageFor(model => model.ProductName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ProductDetail)
</div>
<div class="editor-field">
<input id="txt_desc" type="text" name="fname">
@Html.ValidationMessageFor(model => model.ProductDetail)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
<input id="txt_price" type="text" name="fname">
@Html.ValidationMessageFor(model => model.Price)
</div>
<p>
<input id="Save" type="button" value="Create" />
</p>
</fieldset>
</form>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</form>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
If you are using web api then you should make a http POST
call to URL : https://www.googleapis.com/oauth2/v4/token
with following request body
client_id: <YOUR_CLIENT_ID>
client_secret: <YOUR_CLIENT_SECRET>
refresh_token: <REFRESH_TOKEN_FOR_THE_USER>
grant_type: refresh_token
refresh token never expires so you can use it any number of times. The response will be a JSON like this:
{
"access_token": "your refreshed access token",
"expires_in": 3599,
"scope": "Set of scope which you have given",
"token_type": "Bearer"
}
Unwind segues are used to "go back" to some view controller from which, through a number of segues, you got to the "current" view controller.
Imagine you have something a MyNavController
with A
as its root view controller. Now you use a push segue to B
. Now the navigation controller has A and B in its viewControllers
array, and B is visible. Now you present C
modally.
With unwind segues, you could now unwind "back" from C
to B
(i.e. dismissing the modally presented view controller), basically "undoing" the modal segue. You could even unwind all the way back to the root view controller A
, undoing both the modal segue and the push segue.
Unwind segues make it easy to backtrack. For example, before iOS 6, the best practice for dismissing presented view controllers was to set the presenting view controller as the presented view controller’s delegate, then call your custom delegate method, which then dismisses the presentedViewController. Sound cumbersome and complicated? It was. That’s why unwind segues are nice.
You can also be interested at the top answer in here: https://askubuntu.com/questions/1080204/gpg-problem-with-the-agent-permission-denied
basically the solution that worked for me too is:
gpg --decrypt --pinentry-mode=loopback <file>
class A{
public void methodA(){
new B().methodB();
//or
B.methodB1();
}
}
class B{
//instance method
public void methodB(){
}
//static method
public static void methodB1(){
}
}
I am trying to push value in an array state and set value like this and define state array and push value by map function.
this.state = {
createJob: [],
totalAmount:Number=0
}
your_API_JSON_Array.map((_) => {
this.setState({totalAmount:this.state.totalAmount += _.your_API_JSON.price})
this.state.createJob.push({ id: _._id, price: _.your_API_JSON.price })
return this.setState({createJob: this.state.createJob})
})
I would follow official projects like tar as an example. In my opinion help msg. needs to be simple and descriptive as possible. Examples of use are good too. There is no real need for "standard help".
main class
public class Test {
public static void main (String [] args){
Car thisCar= new Car ("Toyota", "$10000", "2003");
ArrayList<Car> car= new ArrayList<Car> ();
car.add(thisCar);
processCar(car);
}
public static void processCar(ArrayList<Car> car){
for(Car c : car){
System.out.println (c.getPrice());
}
}
}
car class
public class Car {
private String vehicle;
private String price;
private String model;
public Car(String vehicle, String price, String model){
this.vehicle = vehicle;
this.model = model;
this.price = price;
}
public String getVehicle() {
return vehicle;
}
public String getPrice() {
return price;
}
public String getModel() {
return model;
}
}
I found that the new version of PhpMyAdmin put the 'config.inc.php' files in /var/lib/phpmyadmin/
I spend much time in the wrong dir (/usr/share) as this is where all the files also is located, but changes are not reflected.
After putting my settings in
/var/lib/phpmyadmin/config.inc.php
They worked
Just to add to the answers, I think the specific reason in this case, in addition to the misplaced no-repeat
, is the space between url
and (
:
background-image: url ('/image/btn.png') no-repeat; /* Won't work */
background-image: url('/image/btn.png'); /* Should work */
I'm not sure if our problem was directly related with installing gulp only locally. But we had to install a bunch of dependencies ourself. This lead to a "huge" package.json and we are not sure if it is really a great idea to install gulp only locally. We had to do so because of our build environment. But I wouldn't recommend installing gulp not globally if it isn't absolutely necessary. We faced similar problems as described in the following blog-post
None of these problems arise for any of our developers on their local machines because they all installed gulp globally. On the build system we had the described problems. If someone is interested I could dive deeper into this issue. But right now I just wanted to mention that it isn't an easy path to install gulp only locally.
I'd like to give my two cents to this, I'm sorry if any other answer contains what I will explain, I read most of it and haven't find it, but I could have missed something.
I saw a lot of missconceptions and a lot of good explanations, just want to explain async in terms of how it differs from parallel programming, that I believe will make things easier to understand.
When you need to do long computations, processor intensive work, you should opt to use parallel programming, if it's possible, to optimize cores usage. This opens some threads and process things simultaneosly.
Say you have an array of numbers and want to make some expensive long calculation with every and each one of than. Parallel is your friend.
Asyncronous programming is used in a different use case.
It's used to free your thread when you are waiting for something that do not depend on your processor, like IO for example (writing and reading to/from disk), your thread does nothing when you do IO, same thing when you are awaiting for some result from an expensive query to return from DB.
Async methods free your thread when it's waiting for something long to return results. This thread can be used by other parts of your application (in a web app it process other requests, for example) or can return to OS for other use.
When your result is done, the same thread (or another one) is given back to your application to resume processing.
Async programming is not mandatory (but a good practice) in a multithreaded environment like .net, in a web app other threads will respond to new requests, but if you are in a singlethreaded framework like nodejs it's mandatory, because you can't block your only thread, or you won't be able to anwser any other request.
To summarize, long processor intensive calculations will benefit more from parallel programming and long waiting periods that do not depend on your processor, like IO or DB query or a call to some API will benefit more from async programming.
That's why Entity Framework, for example, has an async api to save, list, find, etc...
Remember that async/await is not the same as wait or waitAll, the contexts are different. Async/await release the thread and are asyncronous programming. wait / waitAll blocks all threads (they are not released) to force syncronization in parallel context... different stuff...
Hope this is usefull for someone...
As a side note, consider passing strings in setWord() as const references to avoid excess copying. Also, in displayWord, consider making this a const function to follow const-correctness.
void setWord(const std::string& word) {
theWord = word;
}
Try the following:
List<Map<String, ArrayList<String>>> mapList =
new ArrayList<Map<String, ArrayList<String>>>();
mapList.add(map);
If your list must be of type List<HashMap<String, ArrayList<String>>>
, then declare your map
variable as a HashMap
and not a Map
.
I also used @Ori Drori's answer and managed to get it to work. As your React code grows, so will the bundles compiled that the client browser will have to download on first time access. This imposes a user experience issue if you don't handle it well.
What I added to @Ori answer was to add and execute the onload function in the index.html on onload attribute of the body tag, so that the loader disappear after everything has been fully loaded in the browse, see the snippet below:
<html>
<head>
<style>
.loader:empty {
position: absolute;
top: calc(50% - 4em);
left: calc(50% - 4em);
width: 6em;
height: 6em;
border: 1.1em solid rgba(0, 0, 0, 0.2);
border-left: 1.1em solid #000000;
border-radius: 50%;
animation: load8 1.1s infinite linear;
}
@keyframes load8 {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
<script>
function onLoad() {
var loader = document.getElementById("cpay_loader");loader.className = "";}
</script>
</head>
<body onload="onLoad();">
more html here.....
</body>
</html>
this would work: -- for REDHAT use : cat "/etc/sysconfig/iptables"
iptables -I RH-Firewall-1-INPUT -s 192.168.1.3 -p tcp -m tcp --dport 80 -j ACCEPT
followed by
sudo /etc/init.d/iptables save
You need to set autoincrement property of id column to true when you create the table or you can alter your existing table to do this.
If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:
from FILE NAME import FUNCTION NAME
Note - the parts in capital letters are where you type the file name and function name.
Now you just use your function however it was meant to be.
Example:
FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py
def choose(a):
from random import randint
b = randint(0, len(a) - 1)
c = a[b]
return(c)
SCRIPT USING FUNCTION - saved wherever
from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))
OUTPUT WILL BE DOG, CAT, OR CHICKEN
Hoped this helped, now you can create function packs for download!
--------------------------------This is for Python 2.7-------------------------------------
Chrome Canary and Chromium now have WebSocket message frame inspection feature. Here are the steps to test it quickly:
Note: Every time you send or receive new messages, you have to refresh the main panel by clicking on the echo.websocket.org entry on the left.
I also posted the steps with screen shots and video.
My recently published book, The Definitive Guide to HTML5 WebSocket, also has a dedicated appendix covering the various inspection tools, including Chrome Dev Tools, Chrome net-internals, and Wire Shark.
If you love one liners, try:
d=eval('{'+re.sub('\'[\s]*?\'','\':\'',re.sub(r'([^'+input('SEP: ')+',]+)','\''+r'\1'+'\'',open(input('FILE: ')).read().rstrip('\n').replace('\n',',')))+'}')
Input FILE = Path to file, SEP = Key-Value separator character
Not the most elegant or efficient way of doing it, but quite interesting nonetheless :)
This explains better: Postman docs
Request body
While constructing requests, you would be dealing with the request body editor a lot. Postman lets you send almost any kind of HTTP request (If you can't send something, let us know!). The body editor is divided into 4 areas and has different controls depending on the body type.
form-data
multipart/form-data is the default encoding a web form uses to transfer data.This simulates filling a form on a website, and submitting it. The form-data editor lets you set key/value pairs (using the key-value editor) for your data. You can attach files to a key as well. Do note that due to restrictions of the HTML5 spec, files are not stored in history or collections. You would have to select the file again at the time of sending a request.urlencoded
This encoding is the same as the one used in URL parameters. You just need to enter key/value pairs and Postman will encode the keys and values properly. Note that you can not upload files through this encoding mode. There might be some confusion between form-data and urlencoded so make sure to check with your API first.
raw
A raw request can contain anything. Postman doesn't touch the string entered in the raw editor except replacing environment variables. Whatever you put in the text area gets sent with the request. The raw editor lets you set the formatting type along with the correct header that you should send with the raw body. You can set the Content-Type header manually as well. Normally, you would be sending XML or JSON data here.
binary
binary data allows you to send things which you can not enter in Postman. For example, image, audio or video files. You can send text files as well. As mentioned earlier in the form-data section, you would have to reattach a file if you are loading a request through the history or the collection.
UPDATE
As pointed out by VKK, the WHATWG spec say urlencoded is the default encoding type for forms.
The invalid value default for these attributes is the application/x-www-form-urlencoded state. The missing value default for the enctype attribute is also the application/x-www-form-urlencoded state.
You can use regular expresion as follows:
return Regex.Replace(strIn, @"[^\w\.@-]", "", RegexOptions.None, TimeSpan.FromSeconds(1.0));
#!/bin/bash
for i in $(seq 1 2 10)
do
echo "skip by 2 value $i"
done
From the man page, npm start:
runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.
Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.
Anyhow, what really happens is that npm looks in your package.json file, and if you have something like
"scripts": { "start": "coffee server.coffee" }
then it will do that. If npm can't find your start script, it defaults to:
node server.js
Using the knitr package:
```{r, engine='bash', code_block_name} ...
E.g.:
```{r, engine='bash', count_lines}
wc -l en_US.twitter.txt
```
You can also use:
engine='sh'
for shellengine='python'
for Pythonengine='perl'
, engine='haskell'
and a bunch of other C-like languages and even gawk
, AWK, etc.Here is the only answer that managed to work for my problem, got it figured out with the help of this webpage (nice reference).
powershell -command "& {&'some-command' someParam}"
Also, here is a neat way to do multiple commands:
powershell -command "& {&'some-command' someParam}"; "& {&'some-command' -SpecificArg someParam}"
For example, this is how I ran my 2 commands:
powershell -command "& {&'Import-Module' AppLocker}"; "& {&'Set-AppLockerPolicy' -XmlPolicy myXmlFilePath.xml}"
you might want to try this. Seems to be pretty easy and works on IE6 and Moz atleast.
<div id ="show" style="background-color:Silver;width:100px;height:100px;visibility:visible;border-bottom:outset 1px black;border-right:outset 1px black;" ></div>
The general syntax is : border-[postion]:[border-style] [border-width] [border-color] | inherit
The list of available [border-style]s are :
For your case solution is :
php artisan cache:clear
php artisan route:cache
Optimizing Route Loading is a must on production :
If you are building a large application with many routes, you should make sure that you are running the route:cache Artisan command during your deployment process:
php artisan route:cache
This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes.
Since this feature uses PHP serialization, you may only cache the routes for applications that exclusively use controller based routes. PHP is not able to serialize Closures.
Laravel 5 clear cache from route, view, config and all cache data from application
I would like to share my experience and solution. when i was working on my laravel e commerce website with gitlab. I was fetching one issue suddenly my view cache with error during development. i did try lot to refresh and something other but i can't see any more change in my view, but at last I did resolve my problem using laravel command so, let's see i added several command for clear cache from view, route, config etc.
Reoptimized class loader:
php artisan optimize
Clear Cache facade value:
php artisan cache:clear
Clear Route cache:
php artisan route:cache
Clear View cache:
php artisan view:clear
Clear Config cache:
php artisan config:cache
By using Ado.net
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace PBDataAccess
{
public class AddContact
{
// for preparing connection to sql server database
private SqlConnection conn;
// for preparing sql statement or stored procedure that
// we want to execute on database server
private SqlCommand cmd;
// used for storing the result in datatable, basically
// dataset is collection of datatable
private DataSet ds;
// datatable just for storing single table
private DataTable dt;
// data adapter we use it to manage the flow of data
// from sql server to dataset and after fill the data
// inside dataset using fill() method
private SqlDataAdapter da;
// created a method, which will return the dataset
public DataSet GetAllContactType()
{
// retrieving the connection string from web.config, which will
// tell where our database is located and on which database we want
// to perform opearation, in this case we are working on stored
// procedure so you might have created it somewhere in your database.
// connection string will include the name of the datasource, your
// database name, user name and password.
using (conn = new SqlConnection(ConfigurationManager.ConnectionString["conn"]
.ConnectionString))
{
// Addcontact is the name of the stored procedure
using (cmd = new SqlCommand("Addcontact", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// here we are passing the parameters that
// Addcontact stored procedure expect.
cmd.Parameters.Add("@CommandType",
SqlDbType.VarChar, 50).Value = "GetAllContactType";
// here created the instance of SqlDataAdapter
// class and passed cmd object in it
da = new SqlDataAdapter(cmd);
// created the dataset object
ds = new DataSet();
// fill the dataset and your result will be
stored in dataset
da.Fill(ds);
}
}
return ds;
}
}
****** Stored Procedure ******
CREATE PROCEDURE Addcontact
@CommandType VARCHAR(MAX) = NULL
AS
BEGIN
IF (@CommandType = 'GetAllContactType')
BEGIN
SELECT * FROM Contacts
END
END
Do .libPaths()
, close every R runing, check in the first directory, remove the zoo
package restart R and install
zoo
again. Of course you need to have sufficient rights.
Assuming you do not have permissions set from your LogCat
error description, here is my contents for my AndroidManifest.xml
file that has access to the internet:
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<application ...
</manifest>
Other than that, you should be fine to download a file from the internet.
I suggest to modify pdf.js: remove the download button, convert pdf (at backend part) to some intermediate format of pdf.js and put watermark also at server side.
string strData = "This is much easier"
int intDelimiterIndx = strData.IndexOf("is");
int intDelimiterLength = "is".Length;
str1 = strData.Substring(0, intDelimiterIndx);
str2 = strData.Substring(intDelimiterIndx + intDelimiterLength, strData.Length - (intDelimiterIndx + intDelimiterLength));
static methods can be synchronized. But you have one lock per class. when the java class is loaded coresponding java.lang.class class object is there. That object's lock is needed for.static synchronized methods. So when you have a static field which should be restricted to be accessed by multiple threads at once you can set those fields private and create public static synchronized setters or getters to access those fields.
This is actually javascript but related/relevant because .querySelectorAll targets by CSS syntax:
var i_will_target_self = document.querySelectorAll("ul.menu li a#example")
this example uses css to target links in a menu with id = "example"
that creates a variable which is a collection of the elements we want to change, but we still have actually change them by setting the new target ("_blank"):
for (var i = 0; i < 5; i++) {
i_will_target_self[i].target = "_blank";
}
That code assumes that there are 5 or less elements. That can be changed easily by changing the phrase "i < 5."
read more here: http://xahlee.info/js/js_get_elements.html
I wasn't able to replicate your bug:
var message = new MailMessage();
message.To.Add("[email protected]");
message.To.Add("[email protected]");
message.From = new MailAddress("[email protected]");
message.Subject = "Test";
message.Body = "Test";
var client = new SmtpClient("localhost", 25);
client.Send(message);
Dumping the contents of the To: MailAddressCollection:
MailAddressCollection (2 items)
DisplayName User Host Addressuser example.com [email protected]
user2 example.com [email protected]
And the resulting e-mail as caught by smtp4dev:
Received: from mycomputername (mycomputername [127.0.0.1])
by localhost (Eric Daugherty's C# Email Server)
3/8/2010 12:50:28 PM
MIME-Version: 1.0
From: [email protected]
To: [email protected], [email protected]
Date: 8 Mar 2010 12:50:28 -0800
Subject: Test
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
Test
Are you sure there's not some other issue going on with your code or SMTP server?
Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf
between host and guest (there is known performance issues if there are large numbers of files/directories).
/vagrant
in guestVagrant is mounting the current working directory (where Vagrantfile
resides) as /vagrant
in the guest, this is the default behaviour.
See docs
NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.
You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true
in your Vagrantfile
.
Based on the output /tmp
on host was NOT mounted during up time.
Use VAGRANT_INFO=debug vagrant up
or VAGRANT_INFO=debug vagrant reload
to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp
on host should be drwxrwxrwt
).
I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)
config.vm.synced_folder "/tmp", "/tmp/src"
output
$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src
Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw)
.
If the size of the list if fixed, then you can use an AtomicReferenceArray. This would allow you to perform indexed updates to a slot. You could write a List view if needed.
Here is a bare bones version:
Let's say that you have a date in Cell A1 in the format you described. For example: 19760210
.
Then this formula will give you the date you want:
=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2)).
On my system (Excel 2010) it works with strings or floats.
Set editable
to False
and default
to your default value.
http://docs.djangoproject.com/en/stable/ref/models/fields/#editable
b = models.CharField(max_length=7, default='0000000', editable=False)
Also, your id
field is unnecessary. Django will add it automatically.
I believe that in as early as Git 1.5.x you could make a local branch $BRANCH
track a remote branch origin/$BRANCH
, like this.
Given that $BRANCH
and origin/$BRANCH
exist, and you've not currently checked out $BRANCH
(switch away if you have), do:
git branch -f --track $BRANCH origin/$BRANCH
This recreates $BRANCH
as a tracking branch. The -f
forces the creation despite $BRANCH
existing already. --track
is optional if the usual defaults are in place (that is, the git-config parameter branch.autosetupmerge
is true).
Note, if origin/$BRANCH
doesn't exist yet, you can create it by pushing your local $BRANCH
into the remote repository with:
git push origin $BRANCH
Followed by the previous command to promote the local branch into a tracking branch.
The following will round positive or negative numbers to a given decimal position:
sub round ()
{
my ($x, $pow10) = @_;
my $a = 10 ** $pow10;
return (int($x / $a + (($x < 0) ? -0.5 : 0.5)) * $a);
}
The usual way to check whether something can be converted to an int
is to try
it and see, following the EAFP principle:
try:
int_value = int(string_value)
except ValueError:
# it wasn't an int, do something appropriate
else:
# it was an int, do something appropriate
So, in your case:
for item in mylist:
try:
int_value = int(item)
except ValueError:
pass
else:
mynewlist.append(item) # or append(int_value) if you want numbers
In most cases, a loop around some trivial code that ends with mynewlist.append(item)
can be turned into a list comprehension, generator expression, or call to map
or filter
. But here, you can't, because there's no way to put a try
/except
into an expression.
But if you wrap it up in a function, you can:
def raises(func, *args, **kw):
try:
func(*args, **kw)
except:
return True
else:
return False
mynewlist = [item for item in mylist if not raises(int, item)]
… or, if you prefer:
mynewlist = filter(partial(raises, int), item)
It's cleaner to use it this way:
def raises(exception_types, func, *args, **kw):
try:
func(*args, **kw)
except exception_types:
return True
else:
return False
This way, you can pass it the exception (or tuple of exceptions) you're expecting, and those will return True
, but if any unexpected exceptions are raised, they'll propagate out. So:
mynewlist = [item for item in mylist if not raises(ValueError, int, item)]
… will do what you want, but:
mynewlist = [item for item in mylist if not raises(ValueError, item, int)]
… will raise a TypeError
, as it should.
I like the regular expression solutions but none of the others suit me.
If you know there is only gonna be 1 result you can use the following:
$between = preg_replace('/(.*)BEFORE(.*)AFTER(.*)/sm', '\2', $string);
Change BEFORE and AFTER to the desired delimiters.
Also keep in mind this function will return the whole string in case nothing matched.
This solution is multiline but you can play with the modifiers depending on your needs.
First check if the user has granted the permission:
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED)
Then, you could use this to request to the user:
ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.CAMERA}, requestCode);
And in Marshmallow, it will appear in a dialog
Create a parent view model that contains both models.
public class MainPageModel{
public Model1 Model1{get; set;}
public Model2 Model2{get; set;}
}
This way you can add additional models at a later date with very minimum effort.
Enter while securing an area dynamically
E.G.
#include <stdio.h>
#include <stdlib.h>
char *inputString(FILE* fp, size_t size){
//The size is extended by the input with the value of the provisional
char *str;
int ch;
size_t len = 0;
str = realloc(NULL, sizeof(*str)*size);//size is start size
if(!str)return str;
while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
str[len++]=ch;
if(len==size){
str = realloc(str, sizeof(*str)*(size+=16));
if(!str)return str;
}
}
str[len++]='\0';
return realloc(str, sizeof(*str)*len);
}
int main(void){
char *m;
printf("input string : ");
m = inputString(stdin, 10);
printf("%s\n", m);
free(m);
return 0;
}
Media Queries in style-Attributes are not possible right now. But if you have to set this dynamically via Javascript. You could insert that rule via JS aswell.
document.styleSheets[0].insertRule("@media only screen and (max-width : 300px) { span { background-image:particular_ad_small.png; } }","");
This is as if the style was there in the stylesheet. So be aware of specificity.
As stated by Taylor L, you can't just "stop" a thread (by calling a simple method) due to the fact that it could leave your system in an unstable state as the external calling thread may not know what is going on inside your thread.
With this said, the best way to "stop" a thread is to have the thread keep an eye on itself and to have it know and understand when it should stop.
I have an application which I wanted to:
I had to hook process.exit(code)
to an exit
event handler, or else the mail will not be sent since calling process.exit(code)
directly kills asynchronous events.
#!/usr/bin/nodejs
var mailer = require('nodemailer');
var transport = mailer.createTransport();
mail = {
to: 'Dave Bowman',
from: 'HAL 9000',
subject: 'Sorry Dave',
html: 'Im sorry, Dave. Im afraid I cant do <B>THAT</B>.'
}
transport.sendMail(mail);
//process.exit(1);
process.on('exit', function() { process.exit(1); });
I found the problem. Instead of adding a class (.cs)
file by mistake I had added a Web API Controller
class which added a configuration file in my solution. And that configuration file was looking for the mentioned DLL (Microsoft.Web.Infrastructure 1.0.0.0).
It worked when I removed that file, cleaned the application and then published.
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.
in your sample code you must remove the brackets, because it's not a functional assignment; also for documentary reasons I would suggest you use the :=
notation (see code sample below)
Application.Thisworkbook
refers to the book containing the VBA code, not necessarily the book containing the data, so be cautious.Express the sheet you're working on as a sheet object and pass it, together with a logical variable to the following sub:
Sub SetProtectionMode(MySheet As Worksheet, ProtectionMode As Boolean)
If ProtectionMode Then
MySheet.Protect DrawingObjects:=True, Contents:=True, _
AllowSorting:=True, AllowFiltering:=True
Else
MySheet.Unprotect
End If
End Sub
Within the .Protect
method you can define what you want to allow/disallow. This code block will switch protection on/off - without password in this example, you can add it as a parameter or hardcoded within the Sub. Anyway somewhere the PW will be hardcoded. If you don't want this, just call the Protection Dialog window and let the user decide what to do:
Application.Dialogs(xlDialogProtectDocument).Show
Hope that helps
Good luck - MikeD
Just rebooting a AWS instance works for me to clear the error "shell request failed on channel 0"
To auto-select the value of in select.
<div className="form-group">
<label htmlFor="contactmethod">Contact Method</label>
<select id="contactmethod" className="form-control" value={this.state.contactmethod || ''} onChange={this.handleChange} name="contactmethod">
<option value='Email'>URL</option>
<option value='Phone'>Phone</option>
<option value="SMS">SMS</option>
</select>
</div>
Use the value attribute in the select tag
value={this.state.contactmethod || ''}
the solution is working for me.
The answer by hisdrewness will work, but it modifies the whole approach to letting a provider such as Jackson+JAXB automatically convert your returned object to some output format such as JSON. Inspired by an Apache CXF post (which uses a CXF-specific class) I've found one way to set the response code that should work in any JAX-RS implementation: inject an HttpServletResponse context and manually set the response code. For example, here is how to set the response code to CREATED
when appropriate.
@Path("/foos/{fooId}")
@PUT
@Consumes("application/json")
@Produces("application/json")
public Foo setFoo(@PathParam("fooID") final String fooID, final Foo foo, @Context final HttpServletResponse response)
{
//TODO store foo in persistent storage
if(itemDidNotExistBefore) //return 201 only if new object; TODO app-specific logic
{
response.setStatus(Response.Status.CREATED.getStatusCode());
}
return foo; //TODO get latest foo from storage if needed
}
Improvement: After finding another related answer, I learned that one can inject the HttpServletResponse
as a member variable, even for singleton service class (at least in RESTEasy)!! This is a much better approach than polluting the API with implementation details. It would look like this:
@Context //injected response proxy supporting multiple threads
private HttpServletResponse response;
@Path("/foos/{fooId}")
@PUT
@Consumes("application/json")
@Produces("application/json")
public Foo setFoo(@PathParam("fooID") final String fooID, final Foo foo)
{
//TODO store foo in persistent storage
if(itemDidNotExistBefore) //return 201 only if new object; TODO app-specific logic
{
response.setStatus(Response.Status.CREATED.getStatusCode());
}
return foo; //TODO get latest foo from storage if needed
}
I know I'm late on this (it's been two years since the question was asked) but I accomplished this by intercepting the back button press. Rather than checking for specific activities, I just look at the count and if it's less than 3 it simply sends the app to the back (pausing the app and returning the user to whatever was running before launch). I check for less than three because I only have one intro screen. Also, I check the count because my app allows the user to navigate back to the home screen through the menu, so this allows them to back up through other screens like normal if there are activities other than the intro screen on the stack.
//We want the home screen to behave like the bottom of the activity stack so we do not return to the initial screen
//unless the application has been killed. Users can toggle the session mode with a menu item at all other times.
@Override
public void onBackPressed() {
//Check the activity stack and see if it's more than two deep (initial screen and home screen)
//If it's more than two deep, then let the app proccess the press
ActivityManager am = (ActivityManager)this.getSystemService(Activity.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(3); //3 because we have to give it something. This is an arbitrary number
int activityCount = tasks.get(0).numActivities;
if (activityCount < 3)
{
moveTaskToBack(true);
}
else
{
super.onBackPressed();
}
}
Go to %appdata%\Notepad++ folder.
The macro definitions are held in shortcuts.xml inside the <Macros>
tag. You can copy the whole file, or copy the tag and paste it into shortcuts.xml at the other location.
In the latter case, be sure to use another editor, since N++ overwrites shortcuts.xml on exit.
Best practice of getting length is use length
filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}
But you can calculate count of elements in for
loop. For example:
{% set count = 0 %}
{% for nc in notcount %}
{% set count = count + 1 %}
{% endfor %}
{{ count }}
This solution helps if you want to calculate count of elements by condition, for example you have a property name
inside object and you want to calculate count of objects with not empty names:
{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
{% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}
{{ countNotEmpty }}
Useful links:
Since it seems like nobody has pointed this on out yet:
url = "www.example.com"
new_url = url[:url.rfind(".")]
This should be more efficient than the methods using split()
as no new list object is created, and this solution works for strings with several dots.
You can use this tool as well. It is really useful.
To get caller/called class name use below code, it works fine for me.
String callerClassName = new Exception().getStackTrace()[1].getClassName();
String calleeClassName = new Exception().getStackTrace()[0].getClassName();
a += b
is in this case the same as
a = a + b
In this case cnt += 1 means that cnt is increased by one.
Note that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1.
Edit: quote Carl Meyer: ``[..] the answer is misleadingly mostly correct. There is a subtle but very significant difference between + and +=, see Bastien's answer.''.
Build Solution - Build solution will build your application with building the number of projects which are having any file change. And it does not clear any existing binary files and just replacing updated assemblies in bin or obj folder.
Rebuild Solution - Rebuild solution will build your entire application with building all the projects are available in your solution with cleaning them. Before building it clears all the binary files from bin and obj folder.
Clean Solution - Clean solution is just clears all the binary files from bin and obj folder.
This happens because firewall blocks the database connection.
Disable the firewall and then try running the program again. It worked for me... :D
I'm particularly fond of this date picker built for Mootools: http://electricprism.com/aeron/calendar/
It's lovely right out of the box.
We can try like this to separate list enties by comma
string stations =
haul.Routes != null && haul.Routes.Count > 0 ?String.Join(",",haul.Routes.Select(y =>
y.RouteCode).ToList()) : string.Empty;
Looks like Firebug (Firefox add-on) has the answer:
Log Events
Closed
(manually)there will be something like this in Console tab:
...
mousemove clientX=1097, clientY=292
popupshowing
mousedown clientX=1097, clientY=292
focus
mouseup clientX=1097, clientY=292
click clientX=1097, clientY=292
mousemove clientX=1096, clientY=293
...
Source: Firebug Tip: Log Events
Try this code. Call it before making any http requests. The code will use the proxy from your Internet Explorer Settings - one thing though, I use proxy.Credentials = ....
because my proxy server is an NTLM authenticated Internet Acceleration Server. Give it a whizz.
static void setProxy()
{
WebProxy proxy = (WebProxy)WebProxy.GetDefaultProxy();
if(proxy.Address != null)
{
proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
WebRequest.DefaultWebProxy = new System.Net.WebProxy(proxy.Address, proxy.BypassProxyOnLocal, proxy.BypassList, proxy.Credentials);
}
}
My selects would not color the background until I added !important to the style.
input, select, select option{background-color:#FFE !important}
As of Angular 6 you can import formatDate
from @angular/common
utility to use inside the components.
It was intruduced at https://github.com/smdunn/angular/commit/3adeb0d96344c15201f7f1a0fae7e533a408e4ae
I can be used as:
import {formatDate} from '@angular/common';
formatDate(new Date(), 'd MMM yy HH:mm', 'en');
Although the locale has to be supplied
Interpreted languages like Python and JavaScript benefit greatly from linting, as these languages don’t have a compiling phase to display errors before execution.
Linters are also useful for code formatting and/or adhering to language specific best practices.
Lately I have been using ESLint for JS/React and will occasionally use it with an airbnb-config file.
To download ISIN code data the only place I see this is on the ISIN organizations website, www.isin.org. try http://isin.org, they should have a function where you can easily download.
Change the file name if your file name is like pandas.py or pd.py, it will shadow the real name otherwise.
Wow! Thank you for that answer! I added some features to it to create a "datatable to json" converter that I share with you.
Public Shared Sub dt2json(ByVal _dt As DataTable, ByVal _sb As StringBuilder)
Dim t As System.Type
Dim oList(_dt.Rows.Count - 1) As Object
Dim jss As New JavaScriptSerializer()
Dim i As Integer = 0
t = CompileResultType(_dt)
For Each dr As DataRow In _dt.Rows
Dim o As Object = Activator.CreateInstance(t)
For Each col As DataColumn In _dt.Columns
setvalue(o, col.ColumnName, dr.Item(col.ColumnName))
Next
oList(i) = o
i += 1
Next
jss = New JavaScriptSerializer()
jss.Serialize(oList, _sb)
End Sub
And in "compileresulttype" sub, I changed that:
For Each column As DataColumn In _dt.Columns
CreateProperty(tb, column.ColumnName, column.DataType)
Next
Private Shared Sub setvalue(ByVal _obj As Object, ByVal _propName As String, ByVal _propValue As Object)
Dim pi As PropertyInfo
pi = _obj.GetType.GetProperty(_propName)
If pi IsNot Nothing AndAlso pi.CanWrite Then
If _propValue IsNot DBNull.Value Then
pi.SetValue(_obj, _propValue, Nothing)
Else
Select Case pi.PropertyType.ToString
Case "System.String"
pi.SetValue(_obj, String.Empty, Nothing)
Case Else
'let the serialiser use javascript "null" value.
End Select
End If
End If
End Sub
For a more generic and extensible way check mergedict. It uses singledispatch
and can merge values based on its types.
Example:
from mergedict import MergeDict
class SumDict(MergeDict):
@MergeDict.dispatch(int)
def merge_int(this, other):
return this + other
d2 = SumDict({'a': 1, 'b': 'one'})
d2.merge({'a':2, 'b': 'two'})
assert d2 == {'a': 3, 'b': 'two'}
I was having the same problem just now. I solved it by uninstalling the latest Connector/NET drivers (6.7.4) and then installed the older drivers (6.6.5) and it works.
I am using Visual Studio 2010. I uninstalled the latest ones because I figured they were somehow related to .NET4.5, which I'm not able to use.
Update #1:
Supposedly another way is to register the MySql Connector with various Visual Studio versions (2010/2012/2013/2015...) during installation: Go to Modify Product Features and select all the relevant Visual Studio versions.
Update #2 - Visual Studio 2019 Update:
When I installed MySQL Community with the ConnectorNET and VisualStudio Plugin options included - MySQL didn't show up as a data provider in Visual Studio.
The installer I used included the VS Plugin version 1.2.9, which had supposedly fixed installation issues from 1.2.8, but still didn't work for me...
The solution for me was to uninstall the Connector and the Visual Studio Plugin, download them as individual components, and then install them separately (not as part of the MySQLServer Installer). Install the Connector first, then VS plugin after.
I found the solution here, Thanks to @LambertHeenan.
NOTE about Visual Studio Express
The OP asks whether MySQL is supported with Visual Studio Express (which as far as I can tell has been renamed to Visual Studio Community). In the past MySQL officially didn't support Visual Studio Express, as per @Paul's answer below, but they do officially support Visual Studio Community 2017 and 2019, according to this page.
Presumably this would work:
IF(compliment = 'set' OR compliment = 'Y' OR compliment = 1, 'Y', 'N') AS customer_compliment
Using ${mySet.toArray[0]} does not work.
I do not think it is possible without having forEach loop at least one iteration.
Its not recommended to overwrite bootstrap file, just in your local style.css use
body{background: your color !important;
here !important declaration overwrite bootstrap value.
Simply add
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
to your form object. You will see only an icon at system tray.
You can also do it like this:
BigDecimal A = new BigDecimal("10000000000");
BigDecimal B = new BigDecimal("20000000000");
BigDecimal C = new BigDecimal("30000000000");
BigDecimal resultSum = (A).add(B).add(C);
System.out.println("A+B+C= " + resultSum);
Prints:
A+B+C= 60000000000
How about the following?
irb(main):003:0> my_string = "Some text with a carriage return \r"
=> "Some text with a carriage return \r"
irb(main):004:0> my_string.gsub(/\r/,"")
=> "Some text with a carriage return "
irb(main):005:0>
Or...
irb(main):007:0> my_string = "Some text with a carriage return \r\n"
=> "Some text with a carriage return \r\n"
irb(main):008:0> my_string.gsub(/\r\n/,"\n")
=> "Some text with a carriage return \n"
irb(main):009:0>
In the first case you are simply starting a new thread while in the second case you are entering in the thread pool.
The thread pool job is to share and recycle threads. It allows to avoid losing a few millisecond every time we need to create a new thread.
There are a several ways to enter the thread pool:
You can do it the DOM way as well:
var div = document.getElementById('cart_item');
while(div.firstChild){
div.removeChild(div.firstChild);
}
There are some great example already given here. Just adding a simple example to push associative array elements to root numeric index index.
`$intial_content = array();
if (true) {
$intial_content[] = array('name' => 'xyz', 'content' => 'other content');
}`
you might want to look at the online version of xsv
This works with multiple statements:
if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6
Or you can split it over multiple lines:
if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6
You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding
class.
or try this
System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
System.Text.ASCIIEncoding.ASCII.GetByteCount(string);
Just as another option, the latest PoshConsole release includes binaries targeted to .NET 4 RC (which work fine against the RTM release) without any configuration.
The short answer is NO, PDO prepares will not defend you from all possible SQL-Injection attacks. For certain obscure edge-cases.
I'm adapting this answer to talk about PDO...
The long answer isn't so easy. It's based off an attack demonstrated here.
So, let's start off by showing the attack...
$pdo->query('SET NAMES gbk');
$var = "\xbf\x27 OR 1=1 /*";
$query = 'SELECT * FROM test WHERE name = ? LIMIT 1';
$stmt = $pdo->prepare($query);
$stmt->execute(array($var));
In certain circumstances, that will return more than 1 row. Let's dissect what's going on here:
Selecting a Character Set
$pdo->query('SET NAMES gbk');
For this attack to work, we need the encoding that the server's expecting on the connection both to encode '
as in ASCII i.e. 0x27
and to have some character whose final byte is an ASCII \
i.e. 0x5c
. As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: big5
, cp932
, gb2312
, gbk
and sjis
. We'll select gbk
here.
Now, it's very important to note the use of SET NAMES
here. This sets the character set ON THE SERVER. There is another way of doing it, but we'll get there soon enough.
The Payload
The payload we're going to use for this injection starts with the byte sequence 0xbf27
. In gbk
, that's an invalid multibyte character; in latin1
, it's the string ¿'
. Note that in latin1
and gbk
, 0x27
on its own is a literal '
character.
We have chosen this payload because, if we called addslashes()
on it, we'd insert an ASCII \
i.e. 0x5c
, before the '
character. So we'd wind up with 0xbf5c27
, which in gbk
is a two character sequence: 0xbf5c
followed by 0x27
. Or in other words, a valid character followed by an unescaped '
. But we're not using addslashes()
. So on to the next step...
$stmt->execute()
The important thing to realize here is that PDO by default does NOT do true prepared statements. It emulates them (for MySQL). Therefore, PDO internally builds the query string, calling mysql_real_escape_string()
(the MySQL C API function) on each bound string value.
The C API call to mysql_real_escape_string()
differs from addslashes()
in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using latin1
for the connection, because we never told it otherwise. We did tell the server we're using gbk
, but the client still thinks it's latin1
.
Therefore the call to mysql_real_escape_string()
inserts the backslash, and we have a free hanging '
character in our "escaped" content! In fact, if we were to look at $var
in the gbk
character set, we'd see:
?' OR 1=1 /*
Which is exactly what the attack requires.
The Query
This part is just a formality, but here's the rendered query:
SELECT * FROM test WHERE name = '?' OR 1=1 /*' LIMIT 1
Congratulations, you just successfully attacked a program using PDO Prepared Statements...
Now, it's worth noting that you can prevent this by disabling emulated prepared statements:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
This will usually result in a true prepared statement (i.e. the data being sent over in a separate packet from the query). However, be aware that PDO will silently fallback to emulating statements that MySQL can't prepare natively: those that it can are listed in the manual, but beware to select the appropriate server version).
The problem here is that we didn't call the C API's mysql_set_charset()
instead of SET NAMES
. If we did, we'd be fine provided we are using a MySQL release since 2006.
If you're using an earlier MySQL release, then a bug in mysql_real_escape_string()
meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes even if the client had been correctly informed of the connection encoding and so this attack would still succeed. The bug was fixed in MySQL 4.1.20, 5.0.22 and 5.1.11.
But the worst part is that PDO
didn't expose the C API for mysql_set_charset()
until 5.3.6, so in prior versions it cannot prevent this attack for every possible command!
It's now exposed as a DSN parameter, which should be used instead of SET NAMES
...
As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. utf8mb4
is not vulnerable and yet can support every Unicode character: so you could elect to use that instead—but it has only been available since MySQL 5.5.3. An alternative is utf8
, which is also not vulnerable and can support the whole of the Unicode Basic Multilingual Plane.
Alternatively, you can enable the NO_BACKSLASH_ESCAPES
SQL mode, which (amongst other things) alters the operation of mysql_real_escape_string()
. With this mode enabled, 0x27
will be replaced with 0x2727
rather than 0x5c27
and thus the escaping process cannot create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. 0xbf27
is still 0xbf27
etc.)—so the server will still reject the string as invalid. However, see @eggyal's answer for a different vulnerability that can arise from using this SQL mode (albeit not with PDO).
The following examples are safe:
mysql_query('SET NAMES utf8');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");
Because the server's expecting utf8
...
mysql_set_charset('gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");
Because we've properly set the character set so the client and the server match.
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));
Because we've turned off emulated prepared statements.
$pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password);
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));
Because we've set the character set properly.
$mysqli->query('SET NAMES gbk');
$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "\xbf\x27 OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();
Because MySQLi does true prepared statements all the time.
If you:
OR
utf8
/ latin1
/ ascii
/ etc)OR
NO_BACKSLASH_ESCAPES
SQL modeYou're 100% safe.
Otherwise, you're vulnerable even though you're using PDO Prepared Statements...
I've been slowly working on a patch to change the default to not emulate prepares for a future version of PHP. The problem that I'm running into is that a LOT of tests break when I do that. One problem is that emulated prepares will only throw syntax errors on execute, but true prepares will throw errors on prepare. So that can cause issues (and is part of the reason tests are borking).
The most simple (non python) working solution I can think of is
wget -q -O- icanhazip.com
I'd like to add a very short Python3 solution which makes use of the JSON API of http://hostip.info.
from urllib.request import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read().decode('utf-8'))
print(info['ip'])
You can of course add some error checking, a timeout condition and some convenience:
#!/usr/bin/env python3
from urllib.request import urlopen
from urllib.error import URLError
import json
try:
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
print(info['ip'])
except URLError as e:
print(e.reason, end=' ') # e.g. 'timed out'
print('(are you connected to the internet?)')
except KeyboardInterrupt:
pass
tried what KennyH write but it didn't solved my problem that appear while trying edit style.xml file in my android app, so I just delete the project from eclipse (not from disk of course !!) and import it back ,solved it for me in that case.
I'm a computational biologist, and when I had to compute the auto/cross-correlations between couples of time series of stochastic processes I realized that np.correlate
was not doing the job I needed.
Indeed, what seems to be missing from np.correlate
is the averaging over all the possible couples of time points at distance .
Here is how I defined a function doing what I needed:
def autocross(x, y):
c = np.correlate(x, y, "same")
v = [c[i]/( len(x)-abs( i - (len(x)/2) ) ) for i in range(len(c))]
return v
It seems to me none of the previous answers cover this instance of auto/cross-correlation: hope this answer may be useful to somebody working on stochastic processes like me.
Here is the Code. I have tested all the possible test case on Hacker Rank.
static String isBalanced(String input) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < input.length(); i++) {
Character ch = input.charAt(i);
if (input.charAt(i) == '{' || input.charAt(i) == '['
|| input.charAt(i) == '(') {
stack.push(input.charAt(i));
} else {
if (stack.isEmpty()
|| (stack.peek() == '[' && ch != ']')
|| (stack.peek() == '{' && ch != '}')
|| (stack.peek() == '(' && ch != ')')) {
return "NO";
} else {
stack.pop();
}
}
}
if (stack.empty())
return "YES";
return "NO";
}
>>> li = ['aaa', 'bbb']
>>> li.insert(0, 'wow!')
>>> li
['wow!', 'aaa', 'bbb']
You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...
For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.
Stream is a base class, you need to create one of the specific types of streams, such as MemoryStream.
for Laravel 5.4
for gmail
in .env file
MAIL_DRIVER=mail
MAIL_HOST=mail.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<username>@gmail.com
MAIL_PASSWORD=<password>
MAIL_ENCRYPTION=tls
in config/mail.php
'driver' => env('MAIL_DRIVER', 'mail'),
'from' => [
'address' => env(
'MAIL_FROM_ADDRESS', '<username>@gmail.com'
),
'name' => env(
'MAIL_FROM_NAME', '<from_name>'
),
],
Using the type="email"
or type="url"
will give you a keyboard on some phones at least, such as iPhone. For phone numbers, you can use type="tel"
.
I'm suspicious of the ActiveFileName
property. According to the log4j javadoc, there isn't such a property on the TimeBasedRollingPolicy
class. (No setActiveFileName
or getActiveFileName
methods.)
I don't know what specifying an unknown property would do, but it is possible that it will cause the containing object to be abandoned, and that could lead to the warnings that you saw.
Try leaving it out and seeing what happens.
In insert()
public void insert(String tableImg, Object object,
ContentValues dataToInsert) {
db.insert(tablename, null, dataToInsert);
}
Hope it helps you.
Just use a related field without setting many=True
.
Note that also because you want the output named category_name
, but the actual field is category
, you need to use the source
argument on the serializer field.
The following should give you the output you need...
class ItemSerializer(serializers.ModelSerializer):
category_name = serializers.RelatedField(source='category', read_only=True)
class Meta:
model = Item
fields = ('id', 'name', 'category_name')
When would you use Session Beans or Message Driven Beans ?
How are transactions handled in session beans ?
What is the difference between local and remote session beans ? This question is more about knowing that RPCs are in the picture or not, since a method that is exposed as both Local or Remote might still work differently (side-effects on parameters are possible with Locals, while not possible with Remotes).
A good test is: never ask the questions in the same order. We had the experience with offshoring that sometimes they were actually giving the response in the wrong order :-). As a result you should make sure that you can actually see the person you are interrogating.
data.matrix(SFI)
From ?data.matrix
:
Description:
Return the matrix obtained by converting all the variables in a
data frame to numeric mode and then binding them together as the
columns of a matrix. Factors and ordered factors are replaced by
their internal codes.