Expanding on Dennis R answer above ... This will get the value based on the Heading Text (so you don't need to know what column...especially if its dynamic changing).
Example setting a session variable on SelectedIndexChange.
protected void gvCustomer_SelectedIndexChanged(object sender, EventArgs e)
{
int iCustomerID = Convert.ToInt32(Library.gvGetVal(gvCustomer, "CustomerID"));
Session[SSS.CustomerID] = iCustomerID;
}
public class Library
{
public static string gvGetVal(GridView gvGrid, string sHeaderText)
{
string sRetVal = string.Empty;
if (gvGrid.Rows.Count > 0)
{
if (gvGrid.SelectedRow != null)
{
GridViewRow row = gvGrid.SelectedRow;
int iCol = gvGetColumn(gvGrid, sHeaderText);
if (iCol > -1)
sRetVal = row.Cells[iCol].Text;
}
}
return sRetVal;
}
private static int gvGetColumn(GridView gvGrid, string sHeaderText)
{
int iRetVal = -1;
for (int i = 0; i < gvGrid.Columns.Count; i++)
{
if (gvGrid.Columns[i].HeaderText.ToLower().Trim() == sHeaderText.ToLower().Trim())
{
iRetVal = i;
}
}
return iRetVal;
}
}
Try refreshing the datagrid after each insert
datagridview1.update();
datagridview1.refresh();
Hope this helps you!
Try this,
Using foreach
Loop:
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
if (chk != null && chk.Checked)
{
// ...
}
}
Use it in OnRowCommand
event and get checked CheckBox value.
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];
Let's say you have to color certain cell (not all cells of the row) by knowing two things:
In thas case you have to use event CellFormatting
In my case I use like this
private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
{
if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) > 0)
{
row.Cells["Decade1Hours"].Style.BackColor = Color.LightGreen;
}
else if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) < 0)
{
// row.DefaultCellStyle.BackColor = Color.LightSalmon; // Use it in order to colorize all cells of the row
row.Cells["Decade1Hours"].Style.BackColor = Color.LightSalmon;
}
}
}
And result you can see here
So here you can access certain cell of the row in column by its name row.Cells["Decade1Hours"]
How do you know this name? Well in my case i create column of DataGridView like this.
var Decade1Hours = new DataGridViewTextBoxColumn()
{
Name = "Decade1Hours",
Width = 50,
DataPropertyName = "Decade1Hours",
ReadOnly = true,
DefaultCellStyle = new DataGridViewCellStyle()
{
Alignment = DataGridViewContentAlignment.MiddleCenter,
ForeColor = System.Drawing.Color.Black,
Font = new Font(font, FontStyle.Bold),
Format = "n2"
},
HeaderCell = new DataGridViewColumnHeaderCell()
{
Style = new DataGridViewCellStyle()
{
Alignment = DataGridViewContentAlignment.MiddleCenter,
BackColor = System.Drawing.Color.Blue
}
}
};
Decade1Hours.HeaderText = "???.1";
dgvTrucksMaster.Columns.Add(Decade1Hours);
And well... you you need for instance colorize some of the cells in the row like ##1 4 5 and 8 you have to use cell index (it starts from 0).
And code will lok like
private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
{
if (Convert.ToInt32(row.Cells[1].Value) > 0 )
{
row.Cells[1].Style.BackColor = Color.LightGreen;
}
}
}
Use Sum()
List<string> foo = new List<string>();
foo.Add("1");
foo.Add("2");
foo.Add("3");
foo.Add("4");
Console.Write(foo.Sum(x => Convert.ToInt32(x)));
Prints:
10
This works for me
dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;
user this full solution to convert gridview to datatable
public DataTable gridviewToDataTable(GridView gv)
{
DataTable dtCalculate = new DataTable("TableCalculator");
// Create Column 1: Date
DataColumn dateColumn = new DataColumn();
dateColumn.DataType = Type.GetType("System.DateTime");
dateColumn.ColumnName = "date";
// Create Column 3: TotalSales
DataColumn loanBalanceColumn = new DataColumn();
loanBalanceColumn.DataType = Type.GetType("System.Double");
loanBalanceColumn.ColumnName = "loanbalance";
DataColumn offsetBalanceColumn = new DataColumn();
offsetBalanceColumn.DataType = Type.GetType("System.Double");
offsetBalanceColumn.ColumnName = "offsetbalance";
DataColumn netloanColumn = new DataColumn();
netloanColumn.DataType = Type.GetType("System.Double");
netloanColumn.ColumnName = "netloan";
DataColumn interestratecolumn = new DataColumn();
interestratecolumn.DataType = Type.GetType("System.Double");
interestratecolumn.ColumnName = "interestrate";
DataColumn interestrateperdaycolumn = new DataColumn();
interestrateperdaycolumn.DataType = Type.GetType("System.Double");
interestrateperdaycolumn.ColumnName = "interestrateperday";
// Add the columns to the ProductSalesData DataTable
dtCalculate.Columns.Add(dateColumn);
dtCalculate.Columns.Add(loanBalanceColumn);
dtCalculate.Columns.Add(offsetBalanceColumn);
dtCalculate.Columns.Add(netloanColumn);
dtCalculate.Columns.Add(interestratecolumn);
dtCalculate.Columns.Add(interestrateperdaycolumn);
foreach (GridViewRow row in gv.Rows)
{
DataRow dr;
dr = dtCalculate.NewRow();
dr["date"] = DateTime.Parse(row.Cells[0].Text);
dr["loanbalance"] = double.Parse(row.Cells[1].Text);
dr["offsetbalance"] = double.Parse(row.Cells[2].Text);
dr["netloan"] = double.Parse(row.Cells[3].Text);
dr["interestrate"] = double.Parse(row.Cells[4].Text);
dr["interestrateperday"] = double.Parse(row.Cells[5].Text);
dtCalculate.Rows.Add(dr);
}
return dtCalculate;
}
int rowscount = dataGridView1.Rows.Count;
for (int i = 0; i < rowscount; i++)
{
if (!(dataGridView1.Rows[i].Cells[8].Value == null))
{
dataGridView1.Rows[i].Cells[8].Style.BackColor = Color.LightGoldenrodYellow;
}
}
Your sheet is blank because your string writer in null. Here is what may help
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Here is the full code
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;
filename=FileName.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
Try the below code it should work
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked == false)
{
foreach (DataGridViewRow row in dGV1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = chk.TrueValue;
}
}
else if (checkBox2.Checked == true)
{
foreach (DataGridViewRow row in dGV1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = 1;
if (row.IsNewRow)
{
chk.Value = 0;
}
}
}
}
// This is the exact code for search facility in datagridview.
private void buttonSearch_Click(object sender, EventArgs e)
{
string searchValue=textBoxSearch.Text;
int rowIndex = 1; //this one is depending on the position of cell or column
//string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
bool valueResulet = true;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
dataGridView1.Rows[rowIndex].Selected = true;
rowIndex++;
valueResulet = false;
}
}
if (valueResulet != false)
{
MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
return;
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
You can try this click event
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
Eid_txt.Text = row.Cells["Employee ID"].Value.ToString();
Name_txt.Text = row.Cells["First Name"].Value.ToString();
Surname_txt.Text = row.Cells["Last Name"].Value.ToString();
You can also draw the string dynamically inside the RowPostPaint
event:
private void dgGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
var grid = sender as DataGridView;
var rowIdx = (e.RowIndex + 1).ToString();
var centerFormat = new StringFormat()
{
// right alignment might actually make more sense for numbers
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}
Try this:
foreach(GridViewRow row in GridView1.Rows) {
if(row.RowType == DataControlRowType.DataRow) {
HyperLink myHyperLink = row.FindControl("myHyperLinkID") as HyperLink;
}
}
If you are handling RowDataBound event, it's like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink myHyperLink = e.Row.FindControl("myHyperLinkID") as HyperLink;
}
}
Use something such as the following:
if (String.IsNullOrEmpty(MaterialTextBox.Text))
you can just do this:
string id = GridName.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
here is one very simple example:
ASPX:
<asp:GridView ID="gvTest" runat="server" SelectedRowStyle-BackColor="#996633"
SelectedRowStyle-ForeColor="Fuchsia">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdateClick"/>
Code Behind:
public partial class _Default : System.Web.UI.Page
{
private readonly DataTable _dataTable;
public _Default()
{
_dataTable = new DataTable();
_dataTable.Columns.Add("Serial", typeof (int));
_dataTable.Columns.Add("Data", typeof (string));
for (var i = 0; ++i <= 15;)
_dataTable.Rows.Add(new object[] {i, "This is row " + i});
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
private void BindData()
{
gvTest.DataSource = _dataTable;
gvTest.DataBind();
}
protected void btnUpdateClick(object sender, EventArgs e)
{
if (gvTest.SelectedIndex < 0) return;
var r = gvTest.SelectedRow;
var i = r.DataItemIndex;
//you can get primary key or anyother column vlaue by
//accessing r.Cells collection, but for this simple case
//we will use index of selected row in database.
_dataTable.Rows.RemoveAt(i);
//rebind with data
BindData();
//clear selection from grid
gvTest.SelectedIndex = -1;
}
}
you will have to use checkboxes or some other mechanism to allow users to select multiple rows and then you can browse the rows for ones with the checkbox checked and then remove those rows.
I am using a ListView instead of a GridView in 3.5. When the user wants to edit I have set the selected item of the dropdown to the exising value of that column for the record. I am able to access the dropdown in the ItemDataBound event. Here's the code:
protected void listViewABC_ItemDataBound(object sender, ListViewItemEventArgs e)
{
// This stmt is used to execute the code only in case of edit
if (((ListView)(sender)).EditIndex != -1 && ((ListViewDataItem)(e.Item)).DisplayIndex == ((ListView)(sender)).EditIndex)
{
((DropDownList)(e.Item.FindControl("ddlXType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).XTypeId.ToString();
((DropDownList)(e.Item.FindControl("ddlIType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).ITypeId.ToString();
}
}
In simple words, dereferencing means accessing the value from a certain memory location against which that pointer is pointing.
Based on David's answer I personally like to check the given object first if it is a string at all. Otherwise calling .trim()
on a not existing object would throw an exception:
function isEmpty(value) {
return typeof value == 'string' && !value.trim() || typeof value == 'undefined' || value === null;
}
Usage:
isEmpty(undefined); // true
isEmpty(null); // true
isEmpty(''); // true
isEmpty('foo'); // false
isEmpty(1); // false
isEmpty(0); // false
Unless I'm mistaken, the above code does not take unallocated space into account, so if you really want to know when you'll hit a hard limit, you should use maxbytes.
I think the code below does that. It calculates free space as "freespace" + unallocated space.
select
free.tablespace_name,
free.bytes,
reserv.maxbytes,
reserv.bytes,
reserv.maxbytes - reserv.bytes + free.bytes "max free bytes",
reserv.datafiles
from
(select tablespace_name, count(1) datafiles, sum(maxbytes) maxbytes, sum(bytes) bytes from dba_data_files group by tablespace_name) reserv,
(select tablespace_name, sum(bytes) bytes from dba_free_space group by tablespace_name) free
where free.tablespace_name = reserv.tablespace_name;
Try working with this C# snippet I just crafted:
using System;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string directory = @"C:\downloads";
DirectoryInfo di = new DirectoryInfo(directory);
DirectorySecurity ds = di.GetAccessControl();
foreach (AccessRule rule in ds.GetAccessRules(true, true, typeof(NTAccount)))
{
Console.WriteLine("Identity = {0}; Access = {1}",
rule.IdentityReference.Value, rule.AccessControlType);
}
}
}
}
And here's a reference you could also look at. My code might give you an idea as to how you could check for permissions before attempting to write to a directory.
I had the same issue. after adding below code to my app.js file it fixed.
var cors = require('cors')
app.use(cors());
\begin{tikzpicture}
\tikzstyle{every node}=[font=\fontsize{30}{30}\selectfont]
\end{tikzpicture}
Try this
$("#postcontent").submit(function() {
return false;
};
$('#postsubmit').click(function(){
// your ajax request here
});
You can look at sorting the string -- treat it as a char array -- and then do a modified binary search which counts occurrences? But I agree with @tofutim that traversing it is the most efficient -- O(N) versus O(N * logN) + O(logN)
You have two options:
Extend your .paging
class definition:
.paging:hover {
border:1px solid #999;
color:#000;
}
Use the DOM hierarchy to apply the CSS style:
div.paginate input:hover {
border:1px solid #999;
color:#000;
}
You can use the built-in function:
SUSER_ID ( [ 'myUsername' ] )
via
IF [value] IS NULL [statement]
like:
IF SUSER_ID (N'myUsername') IS NULL
CREATE LOGIN [myUsername] WITH PASSWORD=N'myPassword',
DEFAULT_LANGUAGE=[us_english],
CHECK_EXPIRATION=OFF,
CHECK_POLICY=OFF
GO
https://technet.microsoft.com/en-us/library/ms176042(v=sql.110).aspx
You may be encouraged to use the Element.getBoundingClientRect() method to get the top offset of your element. This method provides the full offset values (left, top, right, bottom, width, height) of your element in the viewport.
Check the John Resig's post describing how helpful this method is.
airline @ Github looks good. It is based on annotation and is trying to emulate Git command line structures.
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("E:/TextFieldForm.pdf"));
document.open();
PdfPTable table = new PdfPTable(2);
table.getDefaultCell().setPadding(5f); // Code 1
table.setHorizontalAlignment(Element.ALIGN_LEFT);
PdfPCell cell;
// Code 2, add name TextField
table.addCell("Name");
TextField nameField = new TextField(writer,
new Rectangle(0,0,200,10), "nameField");
nameField.setBackgroundColor(Color.WHITE);
nameField.setBorderColor(Color.BLACK);
nameField.setBorderWidth(1);
nameField.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
nameField.setText("");
nameField.setAlignment(Element.ALIGN_LEFT);
nameField.setOptions(TextField.REQUIRED);
cell = new PdfPCell();
cell.setMinimumHeight(10);
cell.setCellEvent(new FieldCell(nameField.getTextField(),
200, writer));
table.addCell(cell);
// force upper case javascript
writer.addJavaScript(
"var nameField = this.getField('nameField');" +
"nameField.setAction('Keystroke'," +
"'forceUpperCase()');" +
"" +
"function forceUpperCase(){" +
"if(!event.willCommit)event.change = " +
"event.change.toUpperCase();" +
"}");
// Code 3, add empty row
table.addCell("");
table.addCell("");
// Code 4, add age TextField
table.addCell("Age");
TextField ageComb = new TextField(writer, new Rectangle(0,
0, 30, 10), "ageField");
ageComb.setBorderColor(Color.BLACK);
ageComb.setBorderWidth(1);
ageComb.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
ageComb.setText("12");
ageComb.setAlignment(Element.ALIGN_RIGHT);
ageComb.setMaxCharacterLength(2);
ageComb.setOptions(TextField.COMB |
TextField.DO_NOT_SCROLL);
cell = new PdfPCell();
cell.setMinimumHeight(10);
cell.setCellEvent(new FieldCell(ageComb.getTextField(),
30, writer));
table.addCell(cell);
// validate age javascript
writer.addJavaScript(
"var ageField = this.getField('ageField');" +
"ageField.setAction('Validate','checkAge()');" +
"function checkAge(){" +
"if(event.value < 12){" +
"app.alert('Warning! Applicant\\'s age can not" +
" be younger than 12.');" +
"event.value = 12;" +
"}}");
// add empty row
table.addCell("");
table.addCell("");
// Code 5, add age TextField
table.addCell("Comment");
TextField comment = new TextField(writer,
new Rectangle(0, 0,200, 100), "commentField");
comment.setBorderColor(Color.BLACK);
comment.setBorderWidth(1);
comment.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
comment.setText("");
comment.setOptions(TextField.MULTILINE |
TextField.DO_NOT_SCROLL);
cell = new PdfPCell();
cell.setMinimumHeight(100);
cell.setCellEvent(new FieldCell(comment.getTextField(),
200, writer));
table.addCell(cell);
// check comment characters length javascript
writer.addJavaScript(
"var commentField = " +
"this.getField('commentField');" +
"commentField" +
".setAction('Keystroke','checkLength()');" +
"function checkLength(){" +
"if(!event.willCommit && " +
"event.value.length > 100){" +
"app.alert('Warning! Comment can not " +
"be more than 100 characters.');" +
"event.change = '';" +
"}}");
// add empty row
table.addCell("");
table.addCell("");
// Code 6, add submit button
PushbuttonField submitBtn = new PushbuttonField(writer,
new Rectangle(0, 0, 35, 15),"submitPOST");
submitBtn.setBackgroundColor(Color.GRAY);
submitBtn.
setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
submitBtn.setText("POST");
submitBtn.setOptions(PushbuttonField.
VISIBLE_BUT_DOES_NOT_PRINT);
PdfFormField submitField = submitBtn.getField();
submitField.setAction(PdfAction
.createSubmitForm("",null, PdfAction.SUBMIT_HTML_FORMAT));
cell = new PdfPCell();
cell.setMinimumHeight(15);
cell.setCellEvent(new FieldCell(submitField, 35, writer));
table.addCell(cell);
// Code 7, add reset button
PushbuttonField resetBtn = new PushbuttonField(writer,
new Rectangle(0, 0, 35, 15), "reset");
resetBtn.setBackgroundColor(Color.GRAY);
resetBtn.setBorderStyle(
PdfBorderDictionary.STYLE_BEVELED);
resetBtn.setText("RESET");
resetBtn
.setOptions(
PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
PdfFormField resetField = resetBtn.getField();
resetField.setAction(PdfAction.createResetForm(null, 0));
cell = new PdfPCell();
cell.setMinimumHeight(15);
cell.setCellEvent(new FieldCell(resetField, 35, writer));
table.addCell(cell);
document.add(table);
document.close();
}
class FieldCell implements PdfPCellEvent{
PdfFormField formField;
PdfWriter writer;
int width;
public FieldCell(PdfFormField formField, int width,
PdfWriter writer){
this.formField = formField;
this.width = width;
this.writer = writer;
}
public void cellLayout(PdfPCell cell, Rectangle rect,
PdfContentByte[] canvas){
try{
// delete cell border
PdfContentByte cb = canvas[PdfPTable
.LINECANVAS];
cb.reset();
formField.setWidget(
new Rectangle(rect.left(),
rect.bottom(),
rect.left()+width,
rect.top()),
PdfAnnotation
.HIGHLIGHT_NONE);
writer.addAnnotation(formField);
}catch(Exception e){
System.out.println(e);
}
}
}
Use JSON.stringify(<data>)
.
Change your code: data: sendInfo
to data: JSON.stringify(sendInfo)
.
Hope this can help you.
ErrorDocument 403 /maintenance.html
Order Allow,Deny
Allow from #:#:#:#:#:#
For me, this seems to work (Using IPv6 rather than IPv4) I don't know if this is different for some websites but for mine this works.
In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using
<encoder>
<pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern>
</encoder>
the %ex in pattern is what makes the difference
They do different things. exec
replaces the current process with the new process and never returns. system
invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.
I'm not sure how you could just check if something isn't undefined and at the same time get an error that it is undefined. What browser are you using?
You could check in the following way (extra = and making length a truthy evaluation)
if (typeof(sub.from) !== 'undefined' && sub.from.length) {
[update]
I see that you reset sub and thereby reset sub.from but fail to re check if sub.from exist:
for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
mainid = sub.from[i]['id'];
var sub = afcHelper_Submissions[mainid]; // <== re setting sub
My guess is that the error is not on the if statement but on the for(i...
statement. In Firebug you can break automatically on an error and I guess it'll break on that line (not on the if statement).
You have not defined a method around your code.
import java.io.*;
public class details
{
public static void main( String[] args )
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
In this case, I have assumed that you want your code to be executed in the main
method of the class. It is, of course, possible that this code goes in any other method.
I know this is an old question, but none of the answers worked for me, because I wanted to reliably (always be able to) set the cell into edit mode when possibly executing other events like Toolbar Button clicks, menu selections, etc. that may affect the default focus after those events return. I ended up needing a timer and invoke. The following code is in a new component derived from DataGridView. This code allows me to simply make a call to myXDataGridView.CurrentRow_SelectCellFocus(myDataPropertyName);
anytime I want to arbitrarily set a databound cell to edit mode (assuming the cell is Not in ReadOnly mode).
// If the DGV does not have Focus prior to a toolbar button Click,
// then the toolbar button will have focus after its Click event handler returns.
// To reliably set focus to the DGV, we need to time it to happen After event handler procedure returns.
private string m_SelectCellFocus_DataPropertyName = "";
private System.Timers.Timer timer_CellFocus = null;
public void CurrentRow_SelectCellFocus(string sDataPropertyName)
{
// This procedure is called by a Toolbar Button's Click Event to select and set focus to a Cell in the DGV's Current Row.
m_SelectCellFocus_DataPropertyName = sDataPropertyName;
timer_CellFocus = new System.Timers.Timer(10);
timer_CellFocus.Elapsed += TimerElapsed_CurrentRowSelectCellFocus;
timer_CellFocus.Start();
}
void TimerElapsed_CurrentRowSelectCellFocus(object sender, System.Timers.ElapsedEventArgs e)
{
timer_CellFocus.Stop();
timer_CellFocus.Elapsed -= TimerElapsed_CurrentRowSelectCellFocus;
timer_CellFocus.Dispose();
// We have to Invoke the method to avoid raising a threading error
this.Invoke((MethodInvoker)delegate
{
Select_Cell(m_SelectCellFocus_DataPropertyName);
});
}
private void Select_Cell(string sDataPropertyName)
{
/// When the Edit Mode is Enabled, set the initial cell to the Description
foreach (DataGridViewCell dgvc in this.SelectedCells)
{
// Clear previously selected cells
dgvc.Selected = false;
}
foreach (DataGridViewCell dgvc in this.CurrentRow.Cells)
{
// Select the Cell by its DataPropertyName
if (dgvc.OwningColumn.DataPropertyName == sDataPropertyName)
{
this.CurrentCell = dgvc;
dgvc.Selected = true;
this.Focus();
return;
}
}
}
You can actually try xhtml2pdf http://flask.pocoo.org/snippets/68/
I have used the following to add a property with a "dynamic" name to an object:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
key
is the name of the new property.
The object of properties passed to animate
will be {left: 20, width: 100, top: 10}
This is just using the required []
notation as recommended by the other answers, but with fewer lines of code!
Here is a Swift version of yasirmturk macros. Hope it helps some peoples
// MARK: System versionning
func SYSTEM_VERSION_EQUAL_TO(v: String) -> Bool {
return UIDevice.currentDevice().systemVersion.compare(v, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedSame
}
func SYSTEM_VERSION_GREATER_THAN(v: String) -> Bool {
return UIDevice.currentDevice().systemVersion.compare(v, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedDescending
}
func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v: String) -> Bool {
return UIDevice.currentDevice().systemVersion.compare(v, options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedAscending
}
func SYSTEM_VERSION_LESS_THAN(v: String) -> Bool {
return UIDevice.currentDevice().systemVersion.compare(v, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending
}
func SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v: String) -> Bool {
return UIDevice.currentDevice().systemVersion.compare(v, options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedDescending
}
let kIsIOS7: Bool = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO("7")
let kIsIOS7_1: Bool = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO("7.1")
let kIsIOS8: Bool = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO("8")
let kIsIOS9: Bool = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO("9")
dataGridView1[row, col].Style.BackColor = System.Drawing.Color.Red;
You can also use START WITH
to start a sequence from a particular point, although setval accomplishes the same thing, as in Euler's answer, eg,
SELECT MAX(a) + 1 FROM foo;
CREATE SEQUENCE foo_a_seq START WITH 12345; -- replace 12345 with max above
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
There is an (somewhat) official option: jQuery.validator.format.
Comes with jQuery Validation Plugin 1.6 (at least).
Quite similar to the String.Format
found in .NET.
Edit Fixed broken link.
I'm using:
Eclipse Java EE IDE for Web Developers.
Version: Neon.3 Release (4.6.3) Build id: 20170314-1500
The fix/trick for me was deleting my local repository in ~/.m2/repository in order to remove local dependencies and rebuilding my project in which fresh dependencies are pulled down.
You can use the clear method
List<string> test = new List<string>();
test.Clear();
Depending on your application, you'll probably want to use that Font assignment either on text change or focus/unfocus of the textbox in question.
Here's a quick sample of what it could look like (empty form, with just a textbox. Font turns bold when the text reads 'bold', case-insensitive):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
RegisterEvents();
}
private void RegisterEvents()
{
_tboTest.TextChanged += new EventHandler(TboTest_TextChanged);
}
private void TboTest_TextChanged(object sender, EventArgs e)
{
// Change the text to bold on specified condition
if (_tboTest.Text.Equals("Bold", StringComparison.OrdinalIgnoreCase))
{
_tboTest.Font = new Font(_tboTest.Font, FontStyle.Bold);
}
else
{
_tboTest.Font = new Font(_tboTest.Font, FontStyle.Regular);
}
}
}
I suggest you look at the article called "Short Introduction to log4j". It contains a short explanation of log levels and demonstrates how they can be used in practice. The basic idea of log levels is that you want to be able to configure how much detail the logs contain depending on the situation. For example, if you are trying to troubleshoot an issue, you would want the logs to be very verbose. In production, you might only want to see warnings and errors.
The log level for each component of your system is usually controlled through a parameter in a configuration file, so it's easy to change. Your code would contain various logging statements with different levels. When responding to an Exception
, you might call Logger.error
. If you want to print the value of a variable at any given point, you might call Logger.debug
. This combination of a configurable logging level and logging statements within your program allow you full control over how your application will log its activity.
In the case of log4j at least, the ordering of log levels is:
DEBUG < INFO < WARN < ERROR < FATAL
Here is a short example from that article demonstrating how log levels work.
// get a logger instance named "com.foo"
Logger logger = Logger.getLogger("com.foo");
// Now set its level. Normally you do not need to set the
// level of a logger programmatically. This is usually done
// in configuration files.
logger.setLevel(Level.INFO);
Logger barlogger = Logger.getLogger("com.foo.Bar");
// This request is enabled, because WARN >= INFO.
logger.warn("Low fuel level.");
// This request is disabled, because DEBUG < INFO.
logger.debug("Starting search for nearest gas station.");
// The logger instance barlogger, named "com.foo.Bar",
// will inherit its level from the logger named
// "com.foo" Thus, the following request is enabled
// because INFO >= INFO.
barlogger.info("Located nearest gas station.");
// This request is disabled, because DEBUG < INFO.
barlogger.debug("Exiting gas station search");
Try this. It worked for me
npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@next
This works if you want the first element, like my_list.get(0)
>>> my_list = [1,2,3]
>>> next(iter(my_list), 'fail')
1
>>> my_list = []
>>> next(iter(my_list), 'fail')
'fail'
I know it's not exactly what you asked for but it might help others.
Tested in Android Studio 0.8.14:
I was able to get a standard project running with minimal steps in this way:
You can then add your code, and choose Build > Run 'YourClassName'. Presto, your code is running with no Android device!
I wanted a more enhanced version so I ended up with a module which allows: UAC request if needed, printing and logging from nonprivileged instance (uses ipc and a network port) and some other candies. usage is just insert elevateme() in your script: in nonprivileged it listen for privileged print/logs and then exits returning false, in privileged instance it returns true immediately. Supports pyinstaller.
prototype:
# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):
winadmin.py
#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4
# (C) COPYRIGHT © Preston Landers 2010
# (C) COPYRIGHT © Matteo Azzali 2020
# Released under the same license as Python 2.6.5/3.7
import sys, os
from traceback import print_exc
from multiprocessing.connection import Listener, Client
import win32event #win32com.shell.shell, win32process
import builtins as __builtin__ # python3
# debug suffixes for remote printing
dbz=["","","",""] #["J:","K:", "G:", "D:"]
LOGTAG="LOGME:"
wrconn = None
#fake logger for message sending
class fakelogger:
def __init__(self, xlogger=None):
self.lg = xlogger
def write(self, a):
global wrconn
if wrconn is not None:
wrconn.send(LOGTAG+a)
elif self.lg is not None:
self.lg.write(a)
else:
print(LOGTAG+a)
class Writer():
wzconn=None
counter = 0
def __init__(self, tport=6000,authkey=b'secret password'):
global wrconn
if wrconn is None:
address = ('localhost', tport)
try:
wrconn = Client(address, authkey=authkey)
except:
wrconn = None
wzconn = wrconn
self.wrconn = wrconn
self.__class__.counter+=1
def __del__(self):
self.__class__.counter-=1
if self.__class__.counter == 0 and wrconn is not None:
import time
time.sleep(0.1) # slows deletion but is enough to print stderr
wrconn.send('close')
wrconn.close()
def sendx(cls, mesg):
cls.wzconn.send(msg)
def sendw(self, mesg):
self.wrconn.send(msg)
#fake file to be passed as stdout and stderr
class connFile():
def __init__(self, thekind="out", tport=6000):
self.cnt = 0
self.old=""
self.vg=Writer(tport)
if thekind == "out":
self.kind=sys.__stdout__
else:
self.kind=sys.__stderr__
def write(self, *args, **kwargs):
global wrconn
global dbz
from io import StringIO # # Python2 use: from cStringIO import StringIO
mystdout = StringIO()
self.cnt+=1
__builtin__.print(*args, **kwargs, file=mystdout, end = '')
#handles "\n" wherever it is, however usually is or string or \n
if "\n" not in mystdout.getvalue():
if mystdout.getvalue() != "\n":
#__builtin__.print("A:",mystdout.getvalue(), file=self.kind, end='')
self.old += mystdout.getvalue()
else:
#__builtin__.print("B:",mystdout.getvalue(), file=self.kind, end='')
if wrconn is not None:
wrconn.send(dbz[1]+self.old)
else:
__builtin__.print(dbz[2]+self.old+ mystdout.getvalue(), file=self.kind, end='')
self.kind.flush()
self.old=""
else:
vv = mystdout.getvalue().split("\n")
#__builtin__.print("V:",vv, file=self.kind, end='')
for el in vv[:-1]:
if wrconn is not None:
wrconn.send(dbz[0]+self.old+el)
self.old = ""
else:
__builtin__.print(dbz[3]+self.old+ el+"\n", file=self.kind, end='')
self.kind.flush()
self.old=""
self.old=vv[-1]
def open(self):
pass
def close(self):
pass
def flush(self):
pass
def isUserAdmin():
if os.name == 'nt':
import ctypes
# WARNING: requires Windows XP SP2 or higher!
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
traceback.print_exc()
print ("Admin check failed, assuming not an admin.")
return False
elif os.name == 'posix':
# Check for root on Posix
return os.getuid() == 0
else:
print("Unsupported operating system for this module: %s" % (os.name,))
exit()
#raise (RuntimeError, "Unsupported operating system for this module: %s" % (os.name,))
def runAsAdmin(cmdLine=None, wait=True, hidden=False):
if os.name != 'nt':
raise (RuntimeError, "This function is only implemented on Windows.")
import win32api, win32con, win32process
from win32com.shell.shell import ShellExecuteEx
python_exe = sys.executable
arb=""
if cmdLine is None:
cmdLine = [python_exe] + sys.argv
elif not isinstance(cmdLine, (tuple, list)):
if isinstance(cmdLine, (str)):
arb=cmdLine
cmdLine = [python_exe] + sys.argv
print("original user", arb)
else:
raise( ValueError, "cmdLine is not a sequence.")
cmd = '"%s"' % (cmdLine[0],)
params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
if len(arb) > 0:
params += " "+arb
cmdDir = ''
if hidden:
showCmd = win32con.SW_HIDE
else:
showCmd = win32con.SW_SHOWNORMAL
lpVerb = 'runas' # causes UAC elevation prompt.
# print "Running", cmd, params
# ShellExecute() doesn't seem to allow us to fetch the PID or handle
# of the process, so we can't get anything useful from it. Therefore
# the more complex ShellExecuteEx() must be used.
# procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
procInfo = ShellExecuteEx(nShow=showCmd,
fMask=64,
lpVerb=lpVerb,
lpFile=cmd,
lpParameters=params)
if wait:
procHandle = procInfo['hProcess']
obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
rc = win32process.GetExitCodeProcess(procHandle)
#print "Process handle %s returned code %s" % (procHandle, rc)
else:
rc = procInfo['hProcess']
return rc
# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):
global dbz
if not isUserAdmin():
print ("You're not an admin.", os.getpid(), "params: ", sys.argv)
import getpass
uname = getpass.getuser()
if (tport> 0):
address = ('localhost', tport) # family is deduced to be 'AF_INET'
listener = Listener(address, authkey=b'secret password')
rc = runAsAdmin(uname, wait=False, hidden=True)
if (tport> 0):
hr = win32event.WaitForSingleObject(rc, 40)
conn = listener.accept()
print ('connection accepted from', listener.last_accepted)
sys.stdout.flush()
while True:
msg = conn.recv()
# do something with msg
if msg == 'close':
conn.close()
break
else:
if msg.startswith(dbz[0]+LOGTAG):
if xlogger != None:
xlogger.write(msg[len(LOGTAG):])
else:
print("Missing a logger")
else:
print(msg)
sys.stdout.flush()
listener.close()
else: #no port connection, its silent
WaitForSingleObject(rc, INFINITE);
return False
else:
#redirect prints stdout on master, errors in error.txt
print("HIADM")
sys.stdout.flush()
if (tport > 0) and (redir):
vox= connFile(tport=tport)
sys.stdout=vox
if not errFile:
sys.stderr=vox
else:
vfrs=open("errFile.txt","w")
sys.stderr=vfrs
#print("HI ADMIN")
return True
def test():
rc = 0
if not isUserAdmin():
print ("You're not an admin.", os.getpid(), "params: ", sys.argv)
sys.stdout.flush()
#rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
rc = runAsAdmin()
else:
print ("You are an admin!", os.getpid(), "params: ", sys.argv)
rc = 0
x = raw_input('Press Enter to exit.')
return rc
if __name__ == "__main__":
sys.exit(test())
As stated in the other answers, m_
prefix is used to indicate that a variable is a class member. This is different from Hungarian notation because it doesn't indicate the type of the variable but its context.
I use m_
in C++ but not in some other languages where 'this' or 'self' is compulsory. I don't like to see 'this->' used with C++ because it clutters the code.
Another answer says m_dsc
is "bad practice" and 'description;' is "good practice" but this is a red herring because the problem there is the abbreviation.
Another answer says typing this
pops up IntelliSense but any good IDE will have a hotkey to pop up IntelliSense for the current class members.
this is select box html
<select name="selectBox" id="selectBox">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
when you want to totally remove and add option from select box then you can use this code
$("#selectBox option[value='option1']").remove();
$("#selectBox").append('<option value="option1">Option</option>');
sometime we need to hide and show option from select box , but not remove then you can use this code
$("#selectBox option[value='option1']").hide();
$("#selectBox option[value='option1']").show();
sometime need to remove selected option from select box then
$('#selectBox :selected').remove();
$("#selectBox option:selected").remove();
when you need to remove all option then this code
('#selectBox').empty();
when need to first option or last then this code
$('#selectBox').find('option:first').remove();
$('#selectBox').find('option:last').remove();
The best practice for this situation. Use RETURNING … INTO
.
INSERT INTO teams VALUES (...) RETURNING id INTO last_id;
Note this is for PLPGSQL
public class myActorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String name;
private String user;
private String pass;
private String given_table;
private String tid;
private String firstname;
private String lastname;
private String action;
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
PrintWriter out = response.getWriter();
name = request.getParameter("screenName");
user = request.getParameter("username");
pass = request.getParameter("password");
tid = request.getParameter("tid");
firstname = request.getParameter("firstname");
lastname = request.getParameter("lastname");
action = request.getParameter("action");
given_table = request.getParameter("tableName");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet JDBC</title>");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello, " + name + " </h1>");
out.println("<h1>Servlet JDBC</h1>");
/////////////////////////
// init connection object
String sqlSelect = "SELECT * FROM `" + given_table + "`";
String sqlInsert = "INSERT INTO `" + given_table + "`(`firstName`, `lastName`) VALUES ('" + firstname + "', '" + lastname + "')";
String sqlUpdate = "UPDATE `" + given_table + "` SET `firstName`='" + firstname + "',`lastName`='" + lastname + "' WHERE `id`=" + tid + "";
String sqlDelete = "DELETE FROM `" + given_table + "` WHERE `id` = '" + tid + "'";
//////////////////////////////////////////////////////////
out.println(
"<p>Reading Table Data...Pass to JSP File...Okay<p>");
ArrayList<Actor> list = new ArrayList<Actor>();
// connecting to database
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javabase", user, pass);
stmt = con.createStatement();
rs = stmt.executeQuery(sqlSelect);
// displaying records
while (rs.next()) {
Actor actor = new Actor();
actor.setId(rs.getInt("id"));
actor.setLastname(rs.getString("lastname"));
actor.setFirstname(rs.getString("firstname"));
list.add(actor);
}
request.setAttribute("actors", list);
RequestDispatcher view = request.getRequestDispatcher("myActors_1.jsp");
view.forward(request, response);
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (SQLException e) {
}
}
out.println("</body></html>");
out.close();
}
}
Try to play with
setMinSize()
setMaxSize()
setPreferredSize()
These method are used by layout when it decide what should be the size of current element. The layout manager calls setSize() and actually overrides your values.
If you want to use a bash script and keep it easy to read recommend putting the data in structured JSON, and then use lightweight tool jq in your bash command to iterate through the array. For example with the following dataset:
[
{"specialId":"123",
"specialName":"First"},
{"specialId":"456",
"specialName":"Second"},
{"specialId":"789",
"specialName":"Third"}
]
You can iterate through this data with a bash script and jq like this:
function loopOverArray(){
jq -c '.[]' testing.json | while read i; do
# Do stuff here
echo "$i"
done
}
loopOverArray
Outputs:
{"specialId":"123","specialName":"First"}
{"specialId":"456","specialName":"Second"}
{"specialId":"789","specialName":"Third"}
eval("javascript code");
it is extensively used when dealing with JSON.
I don't have found any solution on Internet, so I have implemented one.
The Autofilter code with criteria is then
iColNumber = 1
Dim aFilterValueArray() As Variant
Call ConstructFilterValueArray(aFilterValueArray, iColNumber, Array("A", "B", "C"))
ActiveSheet.range(sRange).AutoFilter Field:=iColNumber _
, Criteria1:=aFilterValueArray _
, Operator:=xlFilterValues
In fact, the ConstructFilterValueArray() method (not function) get all distinct values that it found in a specific column and remove all values present in last argument.
The VBA code of this method is
'************************************************************
'* ConstructFilterValueArray()
'************************************************************
Sub ConstructFilterValueArray(a() As Variant, iCol As Integer, aRemoveArray As Variant)
Dim aValue As New Collection
Call GetDistinctColumnValue(aValue, iCol)
Call RemoveValueList(aValue, aRemoveArray)
Call CollectionToArray(a, aValue)
End Sub
'************************************************************
'* GetDistinctColumnValue()
'************************************************************
Sub GetDistinctColumnValue(ByRef aValue As Collection, iCol As Integer)
Dim sValue As String
iEmptyValueCount = 0
iLastRow = ActiveSheet.UsedRange.Rows.Count
Dim oSheet: Set oSheet = Sheets("X")
Sheets("Data")
.range(Cells(1, iCol), Cells(iLastRow, iCol)) _
.AdvancedFilter Action:=xlFilterCopy _
, CopyToRange:=oSheet.range("A1") _
, Unique:=True
iRow = 2
Do While True
sValue = Trim(oSheet.Cells(iRow, 1))
If sValue = "" Then
If iEmptyValueCount > 0 Then
Exit Do
End If
iEmptyValueCount = iEmptyValueCount + 1
End If
aValue.Add sValue
iRow = iRow + 1
Loop
End Sub
'************************************************************
'* RemoveValueList()
'************************************************************
Sub RemoveValueList(ByRef aValue As Collection, aRemoveArray As Variant)
For i = LBound(aRemoveArray) To UBound(aRemoveArray)
sValue = aRemoveArray(i)
iMax = aValue.Count
For j = iMax To 0 Step -1
If aValue(j) = sValue Then
aValue.Remove (j)
Exit For
End If
Next j
Next i
End Sub
'************************************************************
'* CollectionToArray()
'************************************************************
Sub CollectionToArray(a() As Variant, c As Collection)
iSize = c.Count - 1
ReDim a(iSize)
For i = 0 To iSize
a(i) = c.Item(i + 1)
Next
End Sub
This code can certainly be improved in returning an Array of String but working with Array in VBA is not easy.
CAUTION: this code work only if you define a sheet named X because CopyToRange parameter used in AdvancedFilter() need an Excel Range !
It's a shame that Microfsoft doesn't have implemented this solution in adding simply a new enum as xlNotFilterValues ! ... or xlRegexMatch !
Here is how I found out a point on a circle with javascript, calculating the angle (degree) from the top of the circle.
const centreX = 50; // centre x of circle
const centreY = 50; // centre y of circle
const r = 20; // radius
const angleDeg = 45; // degree in angle from top
const radians = angleDeg * (Math.PI/180);
const pointY = centreY - (Math.cos(radians) * r); // specific point y on the circle for the angle
const pointX = centreX + (Math.sin(radians) * r); // specific point x on the circle for the angle
Adding productFlavors{} to the app build.gradle solved the issue for me. See below:
buildTypes {
release {
...
}
}
productFlavors {
}
I know this is an old question and was already answered, but for some reason, I still wanna post this alternative solution. I know it's easy to just find out which built-in function does the "magic" you need, but it doesn't hurt to know you can do it by yourself.
>>> list_1 = ['Ace', 'King']
>>> list_2 = ['Spades', 'Clubs', 'Diamonds']
>>> deck = []
>>> for i in range(max((len(list_1),len(list_2)))):
while True:
try:
card = (list_1[i],list_2[i])
except IndexError:
if len(list_1)>len(list_2):
list_2.append('')
card = (list_1[i],list_2[i])
elif len(list_1)<len(list_2):
list_1.append('')
card = (list_1[i], list_2[i])
continue
deck.append(card)
break
>>>
>>> #and the result should be:
>>> print deck
>>> [('Ace', 'Spades'), ('King', 'Clubs'), ('', 'Diamonds')]
I had such a problem and the answer, although frustrating to find, was solved by doing a search on the offending page for the ".." in the error message. I am using Visual Studio Express and the solution was changing "../../Images/" to "~/Images/" . Hopefully this will help someone.
You can use jQuery .getJSON()
function:
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) {
// JSON result in `data` variable
});
If you don't want to use jQuery you should look at this answer for pure JS solution: https://stackoverflow.com/a/2499647/1361042
In my case the error was due to lack of permissions to the folder path. I entered and saved the credentials the issue was solved.
I got the same error when I added the applicationinitialization module with lots of initializationpages and deployed it on Azure app. The issue turned out to be duplicate entries in my applicationinitialization module. I din't see any errors in the logs so it was hard to troubleshoot. Below is an example of the error code:
<configuration>
<system.webServer>
<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="true">
<add initializationPage="/init1.aspx?call=2"/>
<add initializationPage="/init1.aspx?call=2" />
</applicationInitialization>
</system.webServer>
Make sure there are no duplicate entries because those will be treated as duplicate keys which are not allowed and will result in "Cannot add duplicate collection entry" error for web.config.
As mentioned above it wont work for primitive types where 0/NO could be a valid value. I am using this code.
NSUserDefaults *defaults= [NSUserDefaults standardUserDefaults];
if([[[defaults dictionaryRepresentation] allKeys] containsObject:@"mykey"]){
NSLog(@"mykey found");
}
DECLARE @id INT
SET @id = 0
UPDATE DESTINATAIRE_TEMP
SET @id = CODE_DEST = @id + 1
GO
try this
I know this question already has an answer but I think my solution could help someone.
So, in my case I had a byte array representing the key and I needed to convert this byte array to char array of hexadecimal values in order to print it out in one line. I extracted my code to a function like this:
char const * keyToStr(uint8_t const *key)
{
uint8_t offset = 0;
static char keyStr[2 * KEY_SIZE + 1];
for (size_t i = 0; i < KEY_SIZE; i++)
{
offset += sprintf(keyStr + offset, "%02X", key[i]);
}
sprintf(keyStr + offset, "%c", '\0');
return keyStr;
}
Now, I can use my function like this:
Serial.print("Public key: ");
Serial.println(keyToStr(m_publicKey));
Serial
object is part of Arduino library and m_publicKey
is member of my class with the following declaration uint8_t m_publicKey[32]
.
**403 Forbidden **
You don't have permission to access /Folder-Name/ on this server**
The solution for this problem is:
1.go to etc/apache2/apache2.conf
2.find the below code and change AllowOverride all to AllowOverride none
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride all Change this to---> AllowOverride none
Require all granted
</Directory>
It will work fine on your Ubuntu server
I think you should understand what delayed expansion is. The existing answers don't explain it (sufficiently) IMHO.
Typing SET /?
explains the thing reasonably well:
Delayed environment variable expansion is useful for getting around the limitations of the current expansion which happens when a line of text is read, not when it is executed. The following example demonstrates the problem with immediate variable expansion:
set VAR=before if "%VAR%" == "before" ( set VAR=after if "%VAR%" == "after" @echo If you see this, it worked )
would never display the message, since the %VAR% in BOTH IF statements is substituted when the first IF statement is read, since it logically includes the body of the IF, which is a compound statement. So the IF inside the compound statement is really comparing "before" with "after" which will never be equal. Similarly, the following example will not work as expected:
set LIST= for %i in (*) do set LIST=%LIST% %i echo %LIST%
in that it will NOT build up a list of files in the current directory, but instead will just set the LIST variable to the last file found. Again, this is because the %LIST% is expanded just once when the FOR statement is read, and at that time the LIST variable is empty. So the actual FOR loop we are executing is:
for %i in (*) do set LIST= %i
which just keeps setting LIST to the last file found.
Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time. If delayed variable expansion is enabled, the above examples could be written as follows to work as intended:
set VAR=before if "%VAR%" == "before" ( set VAR=after if "!VAR!" == "after" @echo If you see this, it worked ) set LIST= for %i in (*) do set LIST=!LIST! %i echo %LIST%
Another example is this batch file:
@echo off
setlocal enabledelayedexpansion
set b=z1
for %%a in (x1 y1) do (
set b=%%a
echo !b:1=2!
)
This prints x2
and y2
: every 1 gets replaced by a 2.
Without setlocal enabledelayedexpansion
, exclamation marks are just that, so it will echo !b:1=2!
twice.
Because normal environment variables are expanded when a (block) statement is read, expanding %b:1=2%
uses the value b
has before the loop: z2
(but y2
when not set).
A _ttoi
function can convert CString
to integer, both wide char and ansi char can work. Below is the details:
CString str = _T("123");
int i = _ttoi(str);
var object = {
key1 : {
name : 'xxxxxx',
value : '100.0'
},
key2 : {
name : 'yyyyyyy',
value : '200.0'
},
key3 : {
name : 'zzzzzz',
value : '500.0'
},
}
If thats how your object looks and you want to loop each name and value then I would try and do something like.
$.each(object,function(key,innerjson){
/*
key would be key1,key2,key3
innerjson would be the name and value **
*/
//Alerts and logging of the variable.
console.log(innerjson); //should show you the value
alert(innerjson.name); //Should say xxxxxx,yyyyyy,zzzzzzz
});
you can invoke it using window.function_name() or directly function_name()
From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?
For all Windows platforms:
1) Download the .WHL package install file.
2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].
3) Make sure the latest version of pip.EXE is now installed. At this time of posting:
pip.EXE --version
pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)
4) Run pip.EXE in an Admin command shell.
- Open an Admin privileged command shell.
> easy_install.EXE --upgrade pip
- Check the pip.EXE version:
> pip.EXE --version
pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)
> pip.EXE install --use-wheel --no-index
--find-links="X:\path to wheel file\DownloadedWheelFile.whl"
Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.
Sadly due to Opera's latest update !!window.chrome
(and other tests on the window object) when testing in Opera returns true.
Conditionizr takes care of this for you and solves the Opera issue:
conditionizr.add('chrome', [], function () {
return !!window.chrome && !/opera|opr/i.test(navigator.userAgent);
});
I'd highly suggest using it as none of the above are now valid.
This allows you to do:
if (conditionizr.chrome) {...}
Conditionizr takes care of other browser detects and is much faster and reliable than jQuery hacks.
Simple rules:
A "owns" B = Composition : B has no meaning or purpose in the system
without A
A "uses" B = Aggregation : B exists independently (conceptually) from A
A "belongs/Have" B= Association; And B exists just have a relation
Example 1:
A Company is an aggregation of Employees.
A Company is a composition of Accounts. When a Company ceases to do
business its Accounts cease to exist but its People continue to exist.
Employees have association relationship with each other.
Example 2: (very simplified)
A Text Editor owns a Buffer (composition). A Text Editor uses a File
(aggregation). When the Text Editor is closed,
the Buffer is destroyed but the File itself is not destroyed.
If I got you correctly, it is as easy as
cartDiv.id = "someID";
No need for jQuery.
Have a look at the properties of a DOM Element.
For classes it is the same:
cartDiv.className = "classes here";
But note that this will overwrite already existing class names. If you want to add and remove classes dynamically, you either have to use jQuery or write your own function that does some string replacement.
parseInt(), but be aware that this function is a bit different in the sense that it for example returns 100 for parseInt("100px").
Think this is, what you are searching for: Allow access to specific projects for Users
Short description without screenshots:
Use Jenkins "Project-based Matrix Authorization Strategy" under "Manage Jenkins" => "Configure System". On the configuration page of each project, you now have "Enable project-based security". Now add each user you want to authorize.
Strangely enough, the solution ended up being to change
volumes:
- ./postgres-data:/var/lib/postgresql
to
volumes:
- ./postgres-data:/var/lib/postgresql/data
Here's an Ajax, asxh
handler and session variables approach:
Handler:
using System;
using System.Web;
public class windowSize : IHttpHandler , System.Web.SessionState.IRequiresSessionState {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/json";
var json = new System.Web.Script.Serialization.JavaScriptSerializer();
var output = json.Serialize(new { isFirst = context.Session["BrowserWidth"] == null });
context.Response.Write(output);
context.Session["BrowserWidth"] = context.Request.QueryString["Width"];
context.Session["BrowserHeight"] = context.Request.QueryString["Height"];
}
public bool IsReusable
{
get { throw new NotImplementedException(); }
}
}
Javascript:
window.onresize = function (event) {
SetWidthHeight();
}
function SetWidthHeight() {
var height = $(window).height();
var width = $(window).width();
$.ajax({
url: "windowSize.ashx",
data: {
'Height': height,
'Width': width
},
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
if (data.isFirst) {
window.location.reload();
};
}).fail(function (xhr) {
alert("Problem to retrieve browser size.");
});
}
$(function () {
SetWidthHeight();
});
On aspx file:
...
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/BrowserWindowSize.js"></script>
...
<asp:Label ID="lblDim" runat="server" Text=""></asp:Label>
...
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["BrowserWidth"] != null)
{
// Do all code here to avoid double execution first time
// ....
lblDim.Text = "Width: " + Session["BrowserWidth"] + " Height: " + Session["BrowserHeight"];
}
}
Source: https://techbrij.com/browser-height-width-server-responsive-design-asp-net
An __init__.py
file makes imports easy. When an __init__.py
is present within a package, function a()
can be imported from file b.py
like so:
from b import a
Without it, however, you can't import directly. You have to amend the system path:
import sys
sys.path.insert(0, 'path/to/b.py')
from b import a
As an additional answer for those experiencing this issue when debugging an Azure websites' web app:
When deploying from GitHub, for example, the code is compiled in Azure server optimized by default.
I tell the server to compile in a debuggable way by setting SCM_BUILD_ARGS
to /p:Configuration=Debug
but there are more options. See this: http://azure.microsoft.com/blog/2014/05/08/introduction-to-remote-debugging-on-azure-web-sites-part-3-multi-instance-environment-and-git/
Wont the below basic approach doesn't suffice your requirements?
HTML Code having a div
<div id="mydiv" onscroll='myMethod();'>
JS will have below code
function myMethod(){ alert(1); }
If you use the CMake GUI then swap to the advanced view and then the option is called CMAKE_VERBOSE_MAKEFILE.
C++ programs are built in two phases
Static library (.lib) is just a bundle of .obj files and therefore isn't a complete program. It hasn't undergone the second (linking) phase of building a program. Dlls, on the other hand, are like exe's and therefore are complete programs.
If you build a static library, it isn't linked yet and therefore consumers of your static library will have to use the same compiler that you used (if you used g++, they will have to use g++).
If instead you built a dll (and built it correctly), you have built a complete program that all consumers can use, no matter which compiler they are using. There are several restrictions though, on exporting from a dll, if cross compiler compatibility is desired.
The biggest PITA of Oracle is that is does not have a default date format!
In your installation of Oracle the combination of Locales and install options has picked (the very sensible!) YYYY-MM-DD as the format for outputting dates. Another installation could have picked "DD/MM/YYYY" or "YYYY/DD/MM".
If you want your SQL to be portable to another Oracle site I would recommend you always wrap a TO_CHAR(datecol,'YYYY-MM-DD')
or similar function around each date column your SQL or alternativly set the defualt format immediatly after you connect with
ALTER SESSION
SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';
or similar.
Padding by definition is a positive integer (including 0).
Negative padding would cause the border to collapse into the content (see the box-model page on w3) - this would make the content area smaller than the content, which doesn't make sense.
What database are you using? normally you don't save files to a database but i think sql 2008 has support for it...
A file is binary data hence UTF 8 does not matter here..
UTF 8 matters when you try to convert a string to a byte array... not a file to byte array.
private void StudentForm_Load(object sender, EventArgs e)
{
string q = @"SELECT [BatchID] FROM [Batch]"; //BatchID column name of Batch table
SqlDataReader reader = DB.Query(q);
while (reader.Read())
{
cbsb.Items.Add(reader["BatchID"].ToString()); //cbsb is the combobox name
}
}
Copy the css or js file that you want to include, to public folder or you may want to store those in public/css or public/js folders.
Eg. you are using style.css file from css folder in public directory then you can use
<link rel="stylesheet" href="{{ url() }}./css/style.css" type="text/css"/>
But in Laravel 5.2 you will have to use
<link rel="stylesheet" href="{{ url('/') }}./css/style.css" type="text/css"/>
and if you want to include javascript files from public/js folder, it's fairly simple too
<script src="{{ url() }}./js/jquery.min.js"></script>
and in Laravel 5.2 you wll have to use
<script src="{{ url('/') }}./js/jquery.min.js"></script>
the function url()
is a laravel helper function which will generate fully qualified URL to given path.
Here is my sugestion:
Dim i As integer, j as integer
With Worksheets("TimeOut")
i = 26
Do Until .Cells(8, i).Value = ""
For j = 9 to 100 ' I do not know how many rows you will need it.'
.Cells(j, i).Formula = "YourVolFormulaHere"
.Cells(j, i + 1).Formula = "YourCapFormulaHere"
Next j
i = i + 2
Loop
End With
You can customize the JsonSerializerSettings
by using the Formatters.JsonFormatter.SerializerSettings
property in the HttpConfiguration
object.
For example, you could do that in the Application_Start() method:
protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Formatting =
Newtonsoft.Json.Formatting.Indented;
}
HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.
The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.
As many folks already alluded to, this is a 32 vs. 64 bit problem for both Eclipse and Java. You cannot mix up 32 and 64 bit. Since Eclipse doesn't use JAVA_HOME
, you'll likely have to alter your PATH prior to launching Eclipse to ensure you are using not only the appropriate version of Java, but also if 32 or 64 bit (or modify the INI file as Jayath noted).
If you are installing Eclipse from a company-share, you should ensure you can tell which Eclipse version you are unzipping, and unzip to the appropriate Program Files directory to help keep track of which is which, then change the PATH (either permanently via (Windows) Control Panel -> System or set PATH=/path/to/32 or 64bit/java/bin;%PATH%
(maybe create a batch file if you don't want to set it in your system and/or user environment variables). Remember, 32-bit is in Program files (x86).
If unsure, just launch Eclipse, if you get the error, change your PATH to the other 'bit' version of Java, and then try again. Then move the Eclipse directory to the appropriate Program Files directory.
def length(i):
return len(str(i))
First Import the package as :
import org.openqa.selenium.support.ui.Select;
then write in single line as:
new Select (driver.findElement(By.id("sampleid"))).selectByValue("SampleValue");
I think it will close your activity and all Sub activity related to it.
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();]
if (id == R.id.Exit) {
this.finishAffinity();
return true;
}
return super.onOptionsItemSelected(item);
}
If your page is refreshed on submitting - yes, but only through the querystring: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx (You must use method "GET" then). Else, you can return its value from the php script.
The easiest way is to paste the following command:
cat /opt/gitlab/version-manifest.txt | head -n 1
and there you get the version installed. :)
If your JSON is without key you can do it like this:
library[library.length] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};
So, try this:
var library = {[{
"title" : "Gold Rush",
"foregrounds" : ["Slide 1","Slide 2","Slide 3"],
"backgrounds" : ["1.jpg","","2.jpg"]
}, {
"title" : California",
"foregrounds" : ["Slide 1","Slide 2","Slide 3"],
"backgrounds" : ["3.jpg","4.jpg","5.jpg"]
}]
}
Then:
library[library.length] = {"title" : "Gold Rush", "foregrounds" : ["Howdy","Slide 2"], "backgrounds" : ["1.jpg",""]};
Try this one:
android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setTitle("This is Title");
ab.setSubtitle("This is Subtitle");
By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).
With C++, Plain Old Data doesn't just mean that things like int, char, etc are the only types used. Plain Old Data really means in practice that you can take a struct memcpy it from one location in memory to another and things will work exactly like you would expect (i.e. not blow up). This breaks if your class, or any class your class contains, has as a member that is a pointer or a reference or a class that has a virtual function. Essentially, if pointers have to be involved somewhere, its not Plain Old Data.
1 - remove the margin from your BODY CSS.
2 - wrap all of your html in a wrapper <div id="wrapper"> ... all your body content </div>
3 - Define the CSS for the wrapper:
This will hold everything together, centered on the page.
#wrapper {
margin-left:auto;
margin-right:auto;
width:960px;
}
use \\:
instead of \:
.. the \
has special meaning in java strings.
The problem may be if you are using older version of jQuery. Because older versions of jQuery have 'live' method instead of 'on'
Try this:
for view in container_view.subviews {
view.removeFromSuperview()
}
If you dont know what to do in catch block, you can just log this exception, but dont leave it blank.
try
{
string a = "125";
int b = int.Parse(a);
}
catch (Exception ex)
{
Log.LogError(ex);
}
No, what you are looking for would be called a parent selector. CSS has none; they have been proposed multiple times but I know of no existing or forthcoming standard including them. You are correct that you would need to use something like jQuery or use additional class annotations to achieve the effect you want.
Here are some similar questions with similar results:
Actually I would say the 1st preference would be an external style sheet (External CSS), the 2nd preference would be writing CSS in style tags in the header section of the current page (Internal CSS)
<style type="text/css">
<!-- CSS goes here -->
</style>
And as a 3rd option - or last resort rather - I'd use CSS in the tags themselves (Inline CSS).
I am in the same boot like you. In the case you mention, I would implement the input validation UI component as a React component.
I agree the implementation of the validation logic itself should (must) not be coupled. Therefore I would put it into a separate JS module.
That is, for logic that should not be coupled use a JS module/class in separate file, and use require/import to de-couple the component from the "service".
This allows for dependency injection and unit testing of the two independently.
I have a function that does almost what you want, if you'll do a few edits, it will fit exactly:
<?php
function stripByWords($string,$length,$delimiter = '<br>') {
$words_array = explode(" ",$string);
$strlen = 0;
$return = '';
foreach($words_array as $word) {
$strlen += mb_strlen($word,'utf8');
$return .= $word." ";
if($strlen >= $length) {
$strlen = 0;
$return .= $delimiter;
}
}
return $return;
}
?>
socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions
Got this with flask :
Means that the port you're trying to bind to, is already in used by another service or process : got a hint on this in my code developed on Eclipse / windows :
if __name__ == "__main__":
# Check the System Type before to decide to bind
# If the system is a Linux machine -:)
if platform.system() == "Linux":
app.run(host='0.0.0.0',port=5000, debug=True)
# If the system is a windows /!\ Change /!\ the /!\ Port
elif platform.system() == "Windows":
app.run(host='0.0.0.0',port=50000, debug=True)
Similar to @Aaron Digulla's suggestion except that I would suggest a graphics design tool, select the base color, in your case the background color, then adjust the Hue, Saturation and Value. Using this you can create color swatches very easily. Paint.Net is free and I use it all the time for this and also the pay-for-tools will also do this.
Use event delegation by assigning the onclick
to the <ol>
. Then pass the event
object as the argument, and using that, grab the text from the clicked element.
function addText(event) {_x000D_
var targ = event.target || event.srcElement;_x000D_
document.getElementById("alltext").value += targ.textContent || targ.innerText;_x000D_
}
_x000D_
<textarea id="alltext"></textarea>_x000D_
_x000D_
<ol onclick="addText(event)">_x000D_
<li>Hello</li>_x000D_
<li>World</li>_x000D_
<li>Earthlings</li>_x000D_
</ol>
_x000D_
Note that this method of passing the event
object works in older IE as well as W3 compliant systems.
You can use:
$("#myform").data('validator').resetForm();
I added the prop as a parameter, to make it more general and reusable
/**
* Represents a search trough an array.
* @function search
* @param {Array} array - The array you wanna search trough
* @param {string} key - The key to search for
* @param {string} [prop] - The property name to find it in
*/
function search(array, key, prop){
// Optional, but fallback to key['name'] if not selected
prop = (typeof prop === 'undefined') ? 'name' : prop;
for (var i=0; i < array.length; i++) {
if (array[i][prop] === key) {
return array[i];
}
}
}
Usage:
var array = [
{
name:'string 1',
value:'this',
other: 'that'
},
{
name:'string 2',
value:'this',
other: 'that'
}
];
search(array, 'string 1');
// or for other cases where the prop isn't 'name'
// ex: prop name id
search(array, 'string 1', 'id');
Mocha test:
var assert = require('chai').assert;
describe('Search', function() {
var testArray = [
{
name: 'string 1',
value: 'this',
other: 'that'
},
{
name: 'string 2',
value: 'new',
other: 'that'
}
];
it('should return the object that match the search', function () {
var name1 = search(testArray, 'string 1');
var name2 = search(testArray, 'string 2');
assert.equal(name1, testArray[0]);
assert.equal(name2, testArray[1]);
var value1 = search(testArray, 'this', 'value');
var value2 = search(testArray, 'new', 'value');
assert.equal(value1, testArray[0]);
assert.equal(value2, testArray[1]);
});
it('should return undefined becuase non of the objects in the array have that value', function () {
var findNonExistingObj = search(testArray, 'string 3');
assert.equal(findNonExistingObj, undefined);
});
it('should return undefined becuase our array of objects dont have ids', function () {
var findById = search(testArray, 'string 1', 'id');
assert.equal(findById, undefined);
});
});
test results:
Search
? should return the object that match the search
? should return undefined becuase non of the objects in the array have that value
? should return undefined becuase our array of objects dont have ids
3 passing (12ms)
if you wanna know more why it's bad practice then see this article:
Why is extending native objects a bad practice?
Prototype version of doing an array search:
Array.prototype.search = function(key, prop){
for (var i=0; i < this.length; i++) {
if (this[i][prop] === key) {
return this[i];
}
}
}
Usage:
var array = [
{ name:'string 1', value:'this', other: 'that' },
{ name:'string 2', value:'this', other: 'that' }
];
array.search('string 1', 'name');
Because gets
doesn't do any kind of check while getting bytes from stdin and putting them somewhere. A simple example:
char array1[] = "12345";
char array2[] = "67890";
gets(array1);
Now, first of all you are allowed to input how many characters you want, gets
won't care about it. Secondly the bytes over the size of the array in which you put them (in this case array1
) will overwrite whatever they find in memory because gets
will write them. In the previous example this means that if you input "abcdefghijklmnopqrts"
maybe, unpredictably, it will overwrite also array2
or whatever.
The function is unsafe because it assumes consistent input. NEVER USE IT!
Notepad++ provides 2 types of features:
Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.
To do that, you just need to change a setting.
Settings
> Preferences...
> Auto-completion
Enable Auto-completion on each input
Function completion
and not Word completion
Function parameter hint on input
(if you have this option)On version 6.5.5 of Notepad++, I have this setting
Some documentation about auto-completion is available in Notepad++ Wiki.
For throttling FPS to any value, pls see jdmayfields answer. However, for a very quick and easy solution to halve your frame rate, you can simply do your computations only every 2nd frame by:
requestAnimationFrame(render);
function render() {
// ... computations ...
requestAnimationFrame(skipFrame);
}
function skipFrame() { requestAnimationFrame(render); }
Similarly you could always call render
but use a variable to control whether you do computations this time or not, allowing you to also cut FPS to a third or fourth (in my case, for a schematic webgl-animation 20fps is still enough while considerably lowering computational load on the clients)
Worth noting, that depending on your purpose (mine was the autofill results of a searchbar) you may want the height to be changeable, and for the scrollbar to only exist if the height exceeds that.
If you want that, replace height: x;
with max-height: x;
, and overflow:scroll
with overflow:auto
.
Additionally, you can use overflow-x
and overflow-y
if you want, and obviously the same thing works horizontally with width : x;
This is a example for get the url image, escape the p tag from some item.
Try this:
$('#img').attr('src').split('<p>')[1].split('</p>')[0]
That is called a shebang, it tells the shell what program to interpret the script with, when executed.
In your example, the script is to be interpreted and run by the bash shell.
Some other example shebangs are:
(From Wikipedia)
#!/bin/sh — Execute the file using sh, the Bourne shell, or a compatible shell
#!/bin/csh — Execute the file using csh, the C shell, or a compatible shell
#!/usr/bin/perl -T — Execute using Perl with the option for taint checks
#!/usr/bin/php — Execute the file using the PHP command line interpreter
#!/usr/bin/python -O — Execute using Python with optimizations to code
#!/usr/bin/ruby — Execute using Ruby
and a few additional ones I can think off the top of my head, such as:
#!/bin/ksh
#!/bin/awk
#!/bin/expect
In a script with the bash shebang, for example, you would write your code with bash syntax; whereas in a script with expect shebang, you would code it in expect syntax, and so on.
Response to updated portion:
It depends on what /bin/sh
actually points to on your system. Often it is just a symlink to /bin/bash
. Sometimes portable scripts are written with #!/bin/sh
just to signify that it's a shell script, but it uses whichever shell is referred to by /bin/sh
on that particular system (maybe it points to /bin/bash
, /bin/ksh
or /bin/zsh
)
This error can come not only because of the Date conversions
This error can come when we try to pass date whereas varchar is expected
or
when we try to pass varchar whereas date is expected.
Use to_char(sysdate,'YYYY-MM-DD') when varchar is expected
Sample of the Recursive Level:
DECLARE @VALUE_CODE AS VARCHAR(5);
--SET @VALUE_CODE = 'A' -- Specify a level
WITH ViewValue AS
(
SELECT ValueCode
, ValueDesc
, PrecedingValueCode
FROM ValuesTable
WHERE PrecedingValueCode IS NULL
UNION ALL
SELECT A.ValueCode
, A.ValueDesc
, A.PrecedingValueCode
FROM ValuesTable A
INNER JOIN ViewValue V ON
V.ValueCode = A.PrecedingValueCode
)
SELECT ValueCode, ValueDesc, PrecedingValueCode
FROM ViewValue
--WHERE PrecedingValueCode = @VALUE_CODE -- Specific level
--WHERE PrecedingValueCode IS NULL -- Root
This is a not-hard approach:
<div>
<img src="sample.jpg" />
</div>
then in css:
div {
position: absolute;
}
img, div {
width: ##%;
height: ##%;
}
In Bootstrap 4, if you want to do something like this:
Mobile | Desktop
-----------------------------
A | A
C | B C
B | D
D |
You need to reverse the order of B then C then apply order-{breakpoint}-first
to B. And apply two different settings, one that will make them share the same cols and other that will make them take the full width of the 12 cols:
Smaller screens: 12 cols to B and 12 cols to C
Larger screens: 12 cols between the sum of them (B + C = 12)
Like this
<div class='row no-gutters'>
<div class='col-12'>
A
</div>
<div class='col-12'>
<div class='row no-gutters'>
<div class='col-12 col-md-6'>
C
</div>
<div class='col-12 col-md-6 order-md-first'>
B
</div>
</div>
</div>
<div class='col-12'>
D
</div>
</div>
The way to think about this is to "think like a compiler".
Imagine you are writing a compiler. And you see code like this.
// file: A.h
class A {
B _b;
};
// file: B.h
class B {
A _a;
};
// file main.cc
#include "A.h"
#include "B.h"
int main(...) {
A a;
}
When you are compiling the .cc file (remember that the .cc and not the .h is the unit of compilation), you need to allocate space for object A
. So, well, how much space then? Enough to store B
! What's the size of B
then? Enough to store A
! Oops.
Clearly a circular reference that you must break.
You can break it by allowing the compiler to instead reserve as much space as it knows about upfront - pointers and references, for example, will always be 32 or 64 bits (depending on the architecture) and so if you replaced (either one) by a pointer or reference, things would be great. Let's say we replace in A
:
// file: A.h
class A {
// both these are fine, so are various const versions of the same.
B& _b_ref;
B* _b_ptr;
};
Now things are better. Somewhat. main()
still says:
// file: main.cc
#include "A.h" // <-- Houston, we have a problem
#include
, for all extents and purposes (if you take the preprocessor out) just copies the file into the .cc. So really, the .cc looks like:
// file: partially_pre_processed_main.cc
class A {
B& _b_ref;
B* _b_ptr;
};
#include "B.h"
int main (...) {
A a;
}
You can see why the compiler can't deal with this - it has no idea what B
is - it has never even seen the symbol before.
So let's tell the compiler about B
. This is known as a forward declaration, and is discussed further in this answer.
// main.cc
class B;
#include "A.h"
#include "B.h"
int main (...) {
A a;
}
This works. It is not great. But at this point you should have an understanding of the circular reference problem and what we did to "fix" it, albeit the fix is bad.
The reason this fix is bad is because the next person to #include "A.h"
will have to declare B
before they can use it and will get a terrible #include
error. So let's move the declaration into A.h itself.
// file: A.h
class B;
class A {
B* _b; // or any of the other variants.
};
And in B.h, at this point, you can just #include "A.h"
directly.
// file: B.h
#include "A.h"
class B {
// note that this is cool because the compiler knows by this time
// how much space A will need.
A _a;
}
HTH.
You can use AdminSite.site_header
to change that text. Here is the docs
More simplified:
resultList.Remove(resultList.Single(x => x.Id == 2));
there is no needing to create a new var object.
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
In general you just have to define a slightly transparent color when creating the shape.
You can achieve that by setting the colors alpha channel.
#FF000000
will get you a solid black whereas #00000000
will get you a 100% transparent black (well it isn't black anymore obviously).
The color scheme is like this #AARRGGBB
there A stands for alpha channel, R stands for red, G for green and B for blue.
The same thing applies if you set the color in Java. There it will only look like 0xFF000000
.
UPDATE
In your case you'd have to add a solid
node. Like below.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/shape_my">
<stroke android:width="4dp" android:color="#636161" />
<padding android:left="20dp"
android:top="20dp"
android:right="20dp"
android:bottom="20dp" />
<corners android:radius="24dp" />
<solid android:color="#88000000" />
</shape>
The color here is a half transparent black.
You can use a padding for the button and you can play with drawablePadding
<Button
style="@style/botonesMenu"
android:padding="15dp"
android:drawablePadding="-15dp"
android:text="@string/actualizarBD"
android:textAlignment="gravity"
android:gravity="center"
android:layout_row="1"
android:layout_column="0"
android:drawableTop="@drawable/actualizar"
android:id="@+id/btnActualizar"
android:onClick="actualizarBD" />
you can use a specific padding depends where put your drawable, with android:paddingLeft="10dp" or android:paddingBottom="10dp" or android:paddingRight="10dp" or android:paddingTop="10dp"
Create a broadcast receiver
[BroadcastReceiver(Enabled = true, Exported = false)]
public class BCReceiver : BroadcastReceiver
{
BCReceiver receiver;
public override void OnReceive(Context context, Intent intent)
{
//Do something here
}
}
From your activity add this code:
LocalBroadcastManager.getInstance(ApplicationContext)
.registerReceiver(receiver, filter);
You can either change the thread identity, or P/Invoke WNetAddConnection2. I prefer the latter, as I sometimes need to maintain multiple credentials for different locations. I wrap it into an IDisposable and call WNetCancelConnection2 to remove the creds afterwards (avoiding the multiple usernames error):
using (new NetworkConnection(@"\\server\read", readCredentials))
using (new NetworkConnection(@"\\server2\write", writeCredentials)) {
File.Copy(@"\\server\read\file", @"\\server2\write\file");
}
I'm guessing that when you enter a value into the totals field that value expression somehow gets overwritten.
However, you can take an alternative approach: Create a field for the total value and when either one
or two
changes update that field.
<li>Total <input type="text" ng-model="total">{{total}}</li>
And change the javascript:
function TodoCtrl($scope) {
$scope.$watch('one * two', function (value) {
$scope.total = value;
});
}
Example fiddle here.
You can do this with the code below, and the code in your question was actually very close to what you needed, all you have to do is call the cmap
object you have.
import matplotlib
cmap = matplotlib.cm.get_cmap('Spectral')
rgba = cmap(0.5)
print(rgba) # (0.99807766255210428, 0.99923106502084169, 0.74602077638401709, 1.0)
For values outside of the range [0.0, 1.0] it will return the under and over colour (respectively). This, by default, is the minimum and maximum colour within the range (so 0.0 and 1.0). This default can be changed with cmap.set_under()
and cmap.set_over()
.
For "special" numbers such as np.nan
and np.inf
the default is to use the 0.0 value, this can be changed using cmap.set_bad()
similarly to under and over as above.
Finally it may be necessary for you to normalize your data such that it conforms to the range [0.0, 1.0]
. This can be done using matplotlib.colors.Normalize
simply as shown in the small example below where the arguments vmin
and vmax
describe what numbers should be mapped to 0.0 and 1.0 respectively.
import matplotlib
norm = matplotlib.colors.Normalize(vmin=10.0, vmax=20.0)
print(norm(15.0)) # 0.5
A logarithmic normaliser (matplotlib.colors.LogNorm) is also available for data ranges with a large range of values.
(Thanks to both Joe Kington and tcaswell for suggestions on how to improve the answer.)
If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?
Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("name");
allNames.add(name);
}
(typed straight into the browser, so not tested).
This worked for me on iOS 5.0 simulator.
Run the app on the simulator.
Go to the path where you can see something like this:
/Users/arshad/Library/Application\ Support/iPhone\ Simulator/5.0/Applications/34BC3FDC-7398-42D4-9114-D5FEFC737512/…
Copy all the package contents including the app, lib, temp and Documents.
Clear all the applications installed on the simulator so that it is easier to see what is happening.
Run a pre-existing app you have on your simulator.
Look for the same package content for that application as in step 3 and delete all.
Paste the package contents that you have previously copied.
Close the simulator and start it again. The new app icon of the intended app will replace the old one.
Another non-reflective solution for Java 8, in the line of paxdiabo's answer but without using a series of if
's, would be to stream all fields and check for nullness:
return Stream.of(id, name)
.allMatch(Objects::isNull);
This remains quite easy to maintain while avoiding the reflection hammer.
It is neither pass-by-value or pass-by-reference - it is call-by-object. See this, by Fredrik Lundh:
http://effbot.org/zone/call-by-object.htm
Here is a significant quote:
"...variables [names] are not objects; they cannot be denoted by other variables or referred to by objects."
In your example, when the Change
method is called--a namespace is created for it; and var
becomes a name, within that namespace, for the string object 'Original'
. That object then has a name in two namespaces. Next, var = 'Changed'
binds var
to a new string object, and thus the method's namespace forgets about 'Original'
. Finally, that namespace is forgotten, and the string 'Changed'
along with it.
In the URL you pointed to, the button_text.xml is being used to set the textColor attribute.That it is reason they had the button_text.xml in res/color folder and therefore they used @color/button_text.xml
But you are trying to use it for background attribute. The background attribute looks for something in res/drawable folder.
check this i got this selector custom button from the internet.I dont have the link.but i thank the poster for this.It helped me.have this in the drawable folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<gradient
android:startColor="@color/yellow1"
android:endColor="@color/yellow2"
android:angle="270" />
<stroke
android:width="3dp"
android:color="@color/grey05" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item android:state_focused="true" >
<shape>
<gradient
android:endColor="@color/orange4"
android:startColor="@color/orange5"
android:angle="270" />
<stroke
android:width="3dp"
android:color="@color/grey05" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:endColor="@color/white1"
android:startColor="@color/white2"
android:angle="270" />
<stroke
android:width="3dp"
android:color="@color/grey05" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
</selector>
And i used in my main.xml layout like this
<Button android:id="@+id/button1"
android:layout_alignParentLeft="true"
android:layout_marginTop="150dip"
android:layout_marginLeft="45dip"
android:textSize="7pt"
android:layout_height="wrap_content"
android:layout_width="230dip"
android:text="@string/welcomebtntitle1"
android:background="@drawable/custombutton"/>
Hope this helps. Vik is correct.
EDIT : Here is the colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="yellow1">#F9E60E</color>
<color name="yellow2">#F9F89D</color>
<color name="orange4">#F7BE45</color>
<color name="orange5">#F7D896</color>
<color name="blue2">#19FCDA</color>
<color name="blue25">#D9F7F2</color>
<color name="grey05">#ACA899</color>
<color name="white1">#FFFFFF</color>
<color name="white2">#DDDDDD</color>
</resources>
Without a subplots
, you can universally remove the ticks like this:
plt.xticks([])
plt.yticks([])
I modified @kolbyjack code to make it work for
http://website1/service
http://website1/service/
with parameters
location ~ ^/service/?(.*) {
return 301 http://service_url/$1$is_args$args;
}
Pure JS solution (eg. when you don't use jQuery or another framework to other things and don't want to download that just for this task):
<div>A</div>
<div>B</div>
<div>C</div>
<div style="display:none">D</div>
<div style="display:none">E</div>
<script>
var divs = document.getElementsByTagName('div');
var last;
if (divs) {
for (var i = 0; i < divs.length; i++) {
if (divs[i].style.display != 'none') {
last = divs[i];
}
}
}
if (last) {
last.style.background = 'red';
}
</script>
Try this
<input type="checkbox" style="zoom:1.5;" />
/* The value 1.5 i.e., the size of checkbox will be increased by 0.5% */
One thing that to be remembered while solving such problems is that in JSON file, a {
indicates a JSONObject
and a [
indicates JSONArray
. If one could manage them properly, it would be very easy to accomplish the task of parsing the JSON file. The above code was really very helpful for me and I hope this content adds some meaning to the above code.
The Gson JsonReader documentation explains how to handle parsing of JsonObjects
and JsonArrays
:
- Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().
- Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().
It's worth noting that Java can overload a method such as abs
so that it works with an integer or a double. In C, overloading doesn't exist, so you need different functions for integer versus double.
Another way to get to the deleted commit is with the git fsck
command.
git fsck --lost-found
This will output something like at the last line:
dangling commit xyz
We can check that it is the same commit using reflog
as suggested in other answers. Now we can do a git merge
git merge xyz
Note:
We cannot get the commit back with fsck
if we have already run a git gc
command which will remove the reference to the dangling commit.
If you have a SharedPreferenceActivity by which you have saved your values
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String imgSett = prefs.getString(keyChannel, "");
if the value is saved in a SharedPreference in an Activity then this is the correct way to saving it.
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(keyChannel, email);
editor.commit();// commit is important here.
and this is how you can retrieve the values.
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyChannel, ""));
Also be aware that you can do so in a non-Activity class too but the only condition is that you need to pass the context of the Activity. use this context in to get the SharedPreferences.
mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);
Just an update:
You should use ::ng-deep
instead of /deep/
which seems to be deprecated.
Per documentation:
The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.
You can find it here
Make sure no other apache servers are running as it generates an error when you try to access it on the browser even with a different port. Go to Finder and below Device you will usually see the lampp icon. You can also open the htdocs from any of the ide or code editor by opening files or project once you locate the lampp icon. Make sure you mount the stack.
Basically, you only need junit.jar on the classpath - and here's a quick way to do it:
Make sure you have a source folder (e.g. test
) marked as a Test Root.
Create a test, for example like this:
public class MyClassTest {
@Test
public void testSomething() {
}
}
Since you haven't configured junit.jar (yet), the @Test
annotation will be marked as an error (red), hit f2 to navigate to it.
Hit alt-enter and choose Add junit.jar to the classpath
There, you're done! Right-click on your test and choose Run 'MyClassTest' to run it and see the test results.
Maven Note: Altervatively, if you're using maven, at step 4 you can instead choose the option Add Maven Dependency..., go to the Search for artifact pane, type junit
and take whichever version (e.g. 4.8 or 4.9).
Simple Override onBackPressed Method:
@Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
If you are using a linux system you can get a random number out of /dev/random or /dev/urandom. Be carefull /dev/random will block if there are not enough random numbers available. If you need speed over randomness use /dev/urandom.
These "files" will be filled with random numbers generated by the operating system. It depends on the implementation of /dev/random on your system if you get true or pseudo random numbers. True random numbers are generated with help form noise gathered from device drivers like mouse, hard drive, network.
You can get random numbers from the file with dd
It is matching because it is finding "a match" not a match of the full string. You can fix this by changing your regexp to specifically look for the beginning and end of the string.
^\d+$
You could use GNU Awk, see this article of the user guide.
As an improvement to the solution presented in the article (in June 2015), the following gawk command allows double quotes inside double quoted fields; a double quote is marked by two consecutive double quotes ("") there. Furthermore, this allows empty fields, but even this can not handle multiline fields. The following example prints the 3rd column (via c=3
) of textfile.csv:
#!/bin/bash
gawk -- '
BEGIN{
FPAT="([^,\"]*)|(\"((\"\")*[^\"]*)*\")"
}
{
if (substr($c, 1, 1) == "\"") {
$c = substr($c, 2, length($c) - 2) # Get the text within the two quotes
gsub("\"\"", "\"", $c) # Normalize double quotes
}
print $c
}
' c=3 < <(dos2unix <textfile.csv)
Note the use of dos2unix
to convert possible DOS style line breaks (CRLF i.e. "\r\n") and UTF-16 encoding (with byte order mark) to "\n" and UTF-8 (without byte order mark), respectively. Standard CSV files use CRLF as line break, see Wikipedia.
If the input may contain multiline fields, you can use the following script. Note the use of special string for separating records in output (since the default separator newline could occur within a record). Again, the following example prints the 3rd column (via c=3
) of textfile.csv:
#!/bin/bash
gawk -- '
BEGIN{
RS="\0" # Read the whole input file as one record;
# assume there is no null character in input.
FS="" # Suppose this setting eases internal splitting work.
ORS="\n####\n" # Use a special output separator to show borders of a record.
}
{
nof=patsplit($0, a, /([^,"\n]*)|("(("")*[^"]*)*")/, seps)
field=0;
for (i=1; i<=nof; i++){
field++
if (field==c) {
if (substr(a[i], 1, 1) == "\"") {
a[i] = substr(a[i], 2, length(a[i]) - 2) # Get the text within
# the two quotes.
gsub(/""/, "\"", a[i]) # Normalize double quotes.
}
print a[i]
}
if (seps[i]!=",") field=0
}
}
' c=3 < <(dos2unix <textfile.csv)
There is another approach to the problem. csvquote can output contents of a CSV file modified so that special characters within field are transformed so that usual Unix text processing tools can be used to select certain column. For example the following code outputs the third column:
csvquote textfile.csv | cut -d ',' -f 3 | csvquote -u
csvquote
can be used to process arbitrary large files.
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
4g is a bit overkill, if you do not want to change buildGradle you can use FILE -> Invalid caches / restart.
Thats work fine for me ...
I'm not sure what the original poster is asking exactly. Since indexOf(...) and contains(...) both probably use loops internally, perhaps he's looking to see if this is possible at all without a loop? I can think of two ways off hand, one would of course be recurrsion:
public boolean containsChar(String s, char search) {
if (s.length() == 0)
return false;
else
return s.charAt(0) == search || containsChar(s.substring(1), search);
}
The other is far less elegant, but completeness...:
/**
* Works for strings of up to 5 characters
*/
public boolean containsChar(String s, char search) {
if (s.length() > 5) throw IllegalArgumentException();
try {
if (s.charAt(0) == search) return true;
if (s.charAt(1) == search) return true;
if (s.charAt(2) == search) return true;
if (s.charAt(3) == search) return true;
if (s.charAt(4) == search) return true;
} catch (IndexOutOfBoundsException e) {
// this should never happen...
return false;
}
return false;
}
The number of lines grow as you need to support longer and longer strings of course. But there are no loops/recurrsions at all. You can even remove the length check if you're concerned that that length() uses a loop.
As some sugested you can use apache or jax-ws. You can also use tools that generate code from WSDL such as ws-import but in my opinion the best way to consume web service is to create a dynamic client and invoke only operations you want not everything from wsdl. You can do this by creating a dynamic client: Sample code:
String endpointUrl = ...;
QName serviceName = new QName("http://com/ibm/was/wssample/echo/",
"EchoService");
QName portName = new QName("http://com/ibm/was/wssample/echo/",
"EchoServicePort");
/** Create a service and add at least one port to it. **/
Service service = Service.create(serviceName);
service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointUrl);
/** Create a Dispatch instance from a service.**/
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName,
SOAPMessage.class, Service.Mode.MESSAGE);
/** Create SOAPMessage request. **/
// compose a request message
MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
// Create a message. This example works with the SOAPPART.
SOAPMessage request = mf.createMessage();
SOAPPart part = request.getSOAPPart();
// Obtain the SOAPEnvelope and header and body elements.
SOAPEnvelope env = part.getEnvelope();
SOAPHeader header = env.getHeader();
SOAPBody body = env.getBody();
// Construct the message payload.
SOAPElement operation = body.addChildElement("invoke", "ns1",
"http://com/ibm/was/wssample/echo/");
SOAPElement value = operation.addChildElement("arg0");
value.addTextNode("ping");
request.saveChanges();
/** Invoke the service endpoint. **/
SOAPMessage response = dispatch.invoke(request);
/** Process the response. **/
When you use a TemplateField and bind literal text to it like you are doing, asp.net will actually insert a control FOR YOU! It gets put into a DataBoundLiteralControl. You can see this if you look in the debugger near your line of code that is getting the empty text.
So, to access the information without changing your template to use a control, you would cast like this:
string percentage = ((DataBoundLiteralControl)e.Row.Cells[7].Controls[0]).Text;
That will get you your text!
if you are using tortoise svn client - while exporting - it displays ..export / checkout , it is confusing , it is just export only. only view/read use export , to commit use - "checkout"
$ export VAR=/home/me/mydir/file.c
$ export DIR=${VAR%/*}
$ echo "${DIR}"
/home/me/mydir
$ echo "${VAR##*/}"
file.c
To avoid dependency with basename
and dirname
<ul id="category-tabs">
<li><a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>
<ul>
<li><a href="javascript:void">item 1</a></li>
<li><a href="javascript:void">item 2</a></li>
<li><a href="javascript:void">item 3</a></li>
</ul>
</li> </ul>
//Jquery
$(document).ready(function() {
$('li').click(function() {
$('i').toggleClass('fa-plus-square fa-minus-square');
});
});
There are 3 scenarios, you describe:
.c
files and with int i;
in the header..c
files and with int i=100;
in the header (or any other value; that doesn't matter)..c
file and with int i=100;
in the header.In each scenario, imagine the contents of the header file inserted into the .c
file and this .c
file compiled into a .o
file and then these linked together.
Then following happens:
works fine because of the already mentioned "tentative definitions": every .o
file contains one of them, so the linker says "ok".
doesn't work, because both .o
files contain a definition with a value, which collide (even if they have the same value) - there may be only one with any given name in all .o
files which are linked together at a given time.
works of course, because you have only one .o
file and so no possibility for collision.
IMHO a clean thing would be
extern int i;
or just int i;
into the header file,int i = 100;
) into file1.c
. In this case, this initialization gets used at the start of the program and the corresponding line in main()
can be omitted. (Besides, I hope the naming is only an example; please don't name any global variables as i
in real programs.)<javascript>
slots=''; hidden=''; basket = 0;
cost_per_slot = $("#cost_per_slot").val();
//cost_per_slot = parseFloat(cost_per_slot).toFixed(2)
for (i=0; i< check_array.length; i++) {
slots += check_array[i] + '\r\n';
hidden += check_array[i].substring(0, 8) + '|';
basket = (basket + parseFloat(cost_per_slot));
}
// Populate the Selected Slots section
$("#selected_slots").html(slots);
// Update hidden slots_booked form element with booked slots
$("#slots_booked").val(hidden);
// Update basket total box
basket = basket.toFixed(2);
$("#total").html(basket);
If your variable is used only within the context of a single function, you're better off using a stack variable, i.e., Option 2. As others have said, you do not have to manage the lifetime of stack variables - they are constructed and destructed automatically. Also, allocating/deallocating a variable on the heap is slow by comparison. If your function is called often enough, you'll see a tremendous performance improvement if use stack variables versus heap variables.
That said, there are a couple of obvious instances where stack variables are insufficient.
If the stack variable has a large memory footprint, then you run the risk of overflowing the stack. By default, the stack size of each thread is 1 MB on Windows. It is unlikely that you'll create a stack variable that is 1 MB in size, but you have to keep in mind that stack utilization is cumulative. If your function calls a function which calls another function which calls another function which..., the stack variables in all of these functions take up space on the same stack. Recursive functions can run into this problem quickly, depending on how deep the recursion is. If this is a problem, you can increase the size of the stack (not recommended) or allocate the variable on the heap using the new operator (recommended).
The other, more likely condition is that your variable needs to "live" beyond the scope of your function. In this case, you'd allocate the variable on the heap so that it can be reached outside the scope of any given function.
Since you are using SQL, would recommend against using adhoc ('writing statements in strings'), especially given that you are loading an image.
ADO.NET can do all of the hard work of mapping, escaping etc for you.
Either create a Stored Procedure, or use SqlParameter to do the binding.
As the other posters say, use VARBINARY(MAX) as your storage type - IMAGE is being depracated.
Using the Functional Java library, import these:
import static fj.pre.Monoid.stringMonoid;
import static fj.data.List.list;
import fj.data.List;
... then you can do this:
List<String> ss = list("foo", "bar", "baz");
String s = stringMonoid.join(ss, ", ");
Or, the generic way, if you don't have a list of Strings:
public static <A> String showList(List<A> l, Show<A> s) {
return stringMonoid.join(l.map(s.showS_()), ", ");
}
Please see @jlareau answer here: https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl
You can use a function to generate the template string:
var app = angular.module('app',[]);
app.config(
function($routeProvider) {
$routeProvider.
when('/', {templateUrl:'/home'}).
when('/users/:user_id',
{
controller:UserView,
templateUrl: function(params){ return '/users/view/' + params.user_id; }
}
).
otherwise({redirectTo:'/'});
}
);
ObservableCollection is a list so if you don't know the element position you have to look at each element until you find the expected one.
Possible optimization If your elements are sorted use a binary search to improve performances otherwise use a Dictionary as index.
I like to make use of the css :before
and a data-*
attribute for the list
HTML:
<ul data-header="heading">
<li>list item </li>
<li>list item </li>
<li>list item </li>
</ul>
CSS:
ul:before{
content:attr(data-header);
font-size:120%;
font-weight:bold;
margin-left:-15px;
}
This will make a list with the header on it that is whatever text is specified as the list's data-header
attribute. You can then easily style it to your needs.
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
Should be probably changed to
firstName = firstName.trim().replaceAll("\\.", "");
If you want to use jquery $("..").is(":focus")
.
You can take a look at this stack
First you need to make sure that the project has been built. You can build a project with the hammer icon in the toolbar. You can choose to build either a Debug or Release version. If you cannot build the project then the problem is that you either don't have a compiler installed or that the IDE does not find the compiler.
To see if you have a compiler installed in a Mac you can run the following command from the command line:
g++ --version
If you have it already installed (it gets installed when you install the XCode tools) you can see its location running:
which g++
If you were able to build the project but you still get the "binary not found" message then the issue might be that a default launch configuration is not being created for the project. In that case do this:
Right click project > Run As > Run Configurations... >
Then create a new configuration under the "C/C++ Application" section > Enter the full path to the executable file (the file that was created in the build step and that will exist in either the Debug or Release folder). Your launch configuration should look like this:
Normally the parameter -d
is interpreted as form-encoded. You need the -H
parameter:
curl -v -H "Content-Type: application/json" -X POST -d '{"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
Maybe you should try this: intent.setType("plain/text");
I found it here. I've used it in my app and it shows only E-Mail and Gmail options.
Try:
mmatrix = np.zeros((nrows, ncols))
Since the shape parameter has to be an int or sequence of ints
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
Otherwise you are passing ncols
to np.zeros
as the dtype.
This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video controls >
<source src="sample.mp4" type="video/mp4">
<track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">
</video>
</body>
</html>
the video and subtitle files are stored in the same folder as default.htm
I have the very latest version of Chrome (just updated this morning)
When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!
(note that if I input localhost.. to IE11 the video plays!!!!
In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.
This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4
In C programming language, \
is used to print some of the special characters which has sepcial meaning in C. Those special characters are listed below
\\ - Backslash
\' - Single Quotation Mark
\" - Double Quatation Mark
\n - New line
\r - Carriage Return
\t - Horizontal Tab
\b - Backspace
\f - Formfeed
\a - Bell(beep) sound
Easy in your conf/main.php. This is my example with bootstrap. You can see that here
'components'=>array(
'clientScript' => array(
'scriptMap' => array(
'jquery.js'=>false, //disable default implementation of jquery
'jquery.min.js'=>false, //desable any others default implementation
'core.css'=>false, //disable
'styles.css'=>false, //disable
'pager.css'=>false, //disable
'default.css'=>false, //disable
),
'packages'=>array(
'jquery'=>array( // set the new jquery
'baseUrl'=>'bootstrap/',
'js'=>array('js/jquery-1.7.2.min.js'),
),
'bootstrap'=>array( //set others js libraries
'baseUrl'=>'bootstrap/',
'js'=>array('js/bootstrap.min.js'),
'css'=>array( // and css
'css/bootstrap.min.css',
'css/custom.css',
'css/bootstrap-responsive.min.css',
),
'depends'=>array('jquery'), // cause load jquery before load this.
),
),
),
),
The explanation given by Merlyn above is pretty complete. However, I would like to elaborate on coding standards.
When several IF's are chained, the final command is executed when all the previous conditions are meet; this is equivalent to an AND operator. I used this behavior now and then, but I clearly indicate what I intend to do via an auxiliary Batch variable called AND:
SET AND=IF
IF EXIST somefile.txt %AND% EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt
Of course, this is NOT a true And operator and must not be used in combination with ELSE clause. This is just a programmer aid to increase the legibility of an instruction that is rarely used.
When I write Batch programs I always use several auxiliary variables that I designed with the sole purpose of write more readable code. For example:
SET AND=IF
SET THEN=(
SET ELSE=) ELSE (
SET NOELSE=
SET ENDIF=)
SET BEGIN=(
SET END=)
SET RETURN=EXIT /B
These variables aids in writting Batch programs in a much clearer way and helps to avoid subtle errors, as Merlyn suggested. For example:
IF EXIST "somefile.txt" %THEN%
IF EXIST "someotherfile.txt" %THEN%
SET var="somefile.txt,someotherfile.txt"
%NOELSE%
%ENDIF%
%NOELSE%
%ENDIF%
IF EXIST "%~1" %THEN%
SET "result=%~1"
%ELSE%
SET "result="
%ENDIF%
I even have variables that aids in writting WHILE-DO and REPEAT-UNTIL like constructs. This means that Batch variables may be used in some degree as preprocessor values.
If you want to trim all spaces, only in lines that have a comma, and use awk
, then the following will work for you:
awk -F, '/,/{gsub(/ /, "", $0); print} ' input.txt
If you only want to remove spaces in the second column, change the expression to
awk -F, '/,/{gsub(/ /, "", $2); print$1","$2} ' input.txt
Note that gsub
substitutes the character in //
with the second expression, in the variable that is the third parameter - and does so in-place
- in other words, when it's done, the $0
(or $2
) has been modified.
Full explanation:
-F, use comma as field separator
(so the thing before the first comma is $1, etc)
/,/ operate only on lines with a comma
(this means empty lines are skipped)
gsub(a,b,c) match the regular expression a, replace it with b,
and do all this with the contents of c
print$1","$2 print the contents of field 1, a comma, then field 2
input.txt use input.txt as the source of lines to process
EDIT I want to point out that @BMW's solution is better, as it actually trims only leading and trailing spaces with two successive gsub
commands. Whilst giving credit I will give an explanation of how it works.
gsub(/^[ \t]+/,"",$2); - starting at the beginning (^) replace all (+ = zero or more, greedy)
consecutive tabs and spaces with an empty string
gsub(/[ \t]+$/,"",$2)} - do the same, but now for all space up to the end of string ($)
1 - ="true". Shorthand for "use default action", which is print $0
- that is, print the entire (modified) line
This solved the same error for me on Debian:
sudo apt-get install libffi-dev
and compile again
Reference: issue31652
all:
echo ${PATH}
Or change PATH just for one command:
all:
PATH=/my/path:${PATH} cmd
When using the data on the server, your characters can reach with the addition of slashes eg if string = {"hello"} comes as string = {\ "hello \"} to solve the following function can be used later to use json decode.
<?php
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$array = $_POST['jObject'];
$array = stripslashes_deep($array);
$data = json_decode($array, true);
print_r($data);
?>
Those who suggested chmod 400 id_rsa.pub did not sound right at all. It was quite possible that op used pub key instead of private key to ssh.
So it might be as simple as ssh -i /Users/tudouya/.ssh/vm/vm_id_rsa (the private key) user@host
to fix it.
--- update ---
Check this article https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2 for how to set up ssh key
What you basically want to do is to force push your local branch, in order to overwrite the remote one.
If you want a more detailed explanation of each of the following commands, then see my details section below. You basically have 4 different options for force pushing with Git:
git push <remote> <branch> -f
git push origin master -f # Example
git push <remote> -f
git push origin -f # Example
git push -f
git push <remote> <branch> --force-with-lease
If you want a more detailed explanation of each command, then see my long answers section below.
Warning: force pushing will overwrite the remote branch with the state of the branch that you're pushing. Make sure that this is what you really want to do before you use it, otherwise you may overwrite commits that you actually want to keep.
You can completely specify specific branches and a remote. The -f
flag is the short version of --force
git push <remote> <branch> --force
git push <remote> <branch> -f
When the branch to push branch is omitted, Git will figure it out based on your config settings. In Git versions after 2.0, a new repo will have default settings to push the currently checked-out branch:
git push <remote> --force
while prior to 2.0, new repos will have default settings to push multiple local branches. The settings in question are the remote.<remote>.push
and push.default
settings (see below).
When both the remote and the branch are omitted, the behavior of just git push --force
is determined by your push.default
Git config settings:
git push --force
As of Git 2.0, the default setting, simple
, will basically just push your current branch to its upstream remote counter-part. The remote is determined by the branch's branch.<remote>.remote
setting, and defaults to the origin repo otherwise.
Before Git version 2.0, the default setting, matching
, basically just pushes all of your local branches to branches with the same name on the remote (which defaults to origin).
You can read more push.default
settings by reading git help config
or an online version of the git-config(1) Manual Page.
--force-with-lease
Force pushing with a "lease" allows the force push to fail if there are new commits on the remote that you didn't expect (technically, if you haven't fetched them into your remote-tracking branch yet), which is useful if you don't want to accidentally overwrite someone else's commits that you didn't even know about yet, and you just want to overwrite your own:
git push <remote> <branch> --force-with-lease
You can learn more details about how to use --force-with-lease
by reading any of the following:
I know this is extremely late to the game, but I wanted to post the additional issue I faced when using mysql, if anyone faces the same issue in future.
As some of the answers mentioned above, setting these in the application.properties will mostly fix the problem
spring.http.multipart.max-file-size=16MB
spring.http.multipart.max-request-size=16MB
I am setting it to 16 MB, because I am using mysql MEDIUMBLOB datatype to store the file.
But after fixing the application.properties, When uploading a file > 4MB gave the error: org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [insert into test_doc(doc_id, duration_of_doc, doc_version_id, file_name, doc) values (?, ?, ?, ?, ?)]; Packet for query is too large (6656781 > 4194304). You can change this value on the server by setting the max_allowed_packet' variable.; nested exception is com.mysql.jdbc.PacketTooBigException: Packet for query is too large (6656781 > 4194304). You can change this value on the server by setting the max_allowed_packet' variable.
So I ran this command from mysql:
SET GLOBAL max_allowed_packet = 1024*1024*16;
1) add the "libxml2.dylib" library to my project's TARGET (Build Phases -> Link Binary With Libraries)
2) add "$(SDKROOT)/usr/include/libxml2" to the Header Search Paths on the TARGET (Build Settings -> Header Search Paths)
After this, the target should build successfully.
In Gitlab version v11.4.4-ee, you can:
If you don't want hexagons, you can use numpy's histogram2d
function:
import numpy as np
import numpy.random
import matplotlib.pyplot as plt
# Generate some test data
x = np.random.randn(8873)
y = np.random.randn(8873)
heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
plt.clf()
plt.imshow(heatmap.T, extent=extent, origin='lower')
plt.show()
This makes a 50x50 heatmap. If you want, say, 512x384, you can put bins=(512, 384)
in the call to histogram2d
.
Example:
Nothing elegant but this could be another satisfactory answer.
merge(x = DF1, y = DF2, by = "Client", all.x=TRUE)[,c("Client","LO","CON")]
This will be useful especially when you don't need the keys that were used to join the tables in your results.
A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called username
and password
:
data: 'username='+username+'&password='+password,
In the FILE2.php example, you would retrieve those values like this:
$uname = $_POST['username'];
$pword = $_POST['password'];
Then do your MySQL lookup and return the values thus:
echo 'You are logged in';
This would deliver the message You are logged in
to the success function in FILE1.php, and the message string would be stored in the variable called "data". Therefore, the alert(data);
line in the success function would alert that message. Of course, you can echo
anything that you like, even large amounts of HTML, such as entire table structures.
Here is another good example to review.
The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.
The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples).
The jQuery/AJAX code is javascript, so you have two options: you can place it within <script type="text/javascript"></script>
tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?>
at the bottom of your PHP document. If you are using jQuery, don't forget to include the jQuery library as in the examples given.
In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works.
@echo off
Set filename="C:\Documents and Settings\All Users\Desktop\Dostips.cmd"
call :expand %filename%
:expand
set filename=%~nx1
echo The name of the file is %filename%
set folder=%~dp1
echo It's path is %folder%
//a[text()='programming quesions site']/@href
which basically identifies an anchor node <a>
that has the text you want, and extracts the href
attribute.
Window
->Show View
->device
(if not found ->Other
->Device
) in right most side, there is arrow, click that, you will see reset adb, just click and enjoy!! It worked for me.
It is basically a two-step process:
pip install cmap
pip install https://pypi.python.org/packages/da/06/bd3e241c4eb0a662914b3b4875fc52dd176a9db0d4a2c915ac2ad8800e9e/dlib-19.7.0-cp36-cp36m-win_amd64.whl#md5=b7330a5b2d46420343fbed5df69e6a3f
fun hideKeyboard(activity: Activity) {
val view = activity.currentFocus
val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
assert(view != null)
methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
private fun showKeyboard(activity: Activity) {
val view = activity.currentFocus
val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
assert(view != null)
methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
public static void hideKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
assert methodManager != null && view != null;
methodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
private static void showKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
assert methodManager != null && view != null;
methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
The answer by @AKX works on the command line, but not within a batch file. Within a batch file, you need an extra %
, like this:
@echo off
for /R TutorialSteps %%F in (*.py) do echo %%~nF
toFixed
isn't a method of non-numeric variable types. In other words, Low
and High
can't be fixed because when you get the value of something in Javascript, it automatically is set to a string type. Using parseFloat()
(or parseInt()
with a radix, if it's an integer) will allow you to convert different variable types to numbers which will enable the toFixed()
function to work.
var Low = parseFloat($SliderValFrom.val()),
High = parseFloat($SliderValTo.val());
LatLngBounds
must be defined with points in (south-west, north-east) order. Your points are not in that order.
The general fix, especially if you don't know the points will definitely be in that order, is to extend an empty bounds:
var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);
The API will sort out the bounds.
I think what you need might be simply:
\d( \w)?
Note that your regex would have worked too if it was written as \d \w|\d
instead of \d|\d \w
.
This is because in your case, once the regex matches the first option, \d
, it ceases to search for a new match, so to speak.
Simple and with little changes. And also hide load more when entire list is loaded.
jsFiddle here.
$(document).ready(function () {
// Load the first 3 list items from another HTML file
//$('#myList').load('externalList.html li:lt(3)');
$('#myList li:lt(3)').show();
$('#showLess').hide();
var items = 25;
var shown = 3;
$('#loadMore').click(function () {
$('#showLess').show();
shown = $('#myList li:visible').size()+5;
if(shown< items) {$('#myList li:lt('+shown+')').show();}
else {$('#myList li:lt('+items+')').show();
$('#loadMore').hide();
}
});
$('#showLess').click(function () {
$('#myList li').not(':lt(3)').hide();
});
});
According to this article, != performs faster
TextField text = new TextField();
text.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable,
String oldValue, String newValue) {
try {
Integer.parseInt(newValue);
if (newValue.endsWith("f") || newValue.endsWith("d")) {
manualPriceInput.setText(newValue.substring(0, newValue.length()-1));
}
} catch (ParseException e) {
text.setText(oldValue);
}
}
});
The if
clause is important to handle inputs like 0.5d or 0.7f which are correctly parsed by Int.parseInt(), but shouldn't appear in the text field.
<textarea name="post" id="post" onclick="if(this.value == 'Write Something here..............') this.value='';" onblur="if(this.value == '') this.value='Write Something here..............';" >Write Something here..............</textarea>
I had the same problem and after reading this topic, I've solved adding this to my CSS:
.navbar-fixed-top {
z-index: 10000;
}
because in my case, I'm using the fixed top menu.
You can use this conversion table: http://roselab.jhu.edu/~raj/MISC/hexdectxt.html
eg, if you want a transparency of 60%, you use 3C (hex equivalent).
This is usefull for IE background gradient transparency:
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#3C545454, endColorstr=#3C545454);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#3C545454, endColorstr=#3C545454)";
where startColorstr and endColorstr: 2 first characters are a hex value for transparency, and the six remaining are the hex color.
My implementation:
def get_nested(data, *args):
if args and data:
element = args[0]
if element:
value = data.get(element)
return value if len(args) == 1 else get_nested(value, *args[1:])
Example usage:
>>> dct={"foo":{"bar":{"one":1, "two":2}, "misc":[1,2,3]}, "foo2":123}
>>> get_nested(dct, "foo", "bar", "one")
1
>>> get_nested(dct, "foo", "bar", "two")
2
>>> get_nested(dct, "foo", "misc")
[1, 2, 3]
>>> get_nested(dct, "foo", "missing")
>>>
There are no exceptions raised in case a key is missing, None value is returned in that case.
You need to pass in a Comparator instance to the sort method otherwise the elements will be sorted in their natural order.
For more information check Collections.sort(List, Comparator)