MsgBox("Variable {0} " , variable)
Not in VB.NET, you have to select all lines at then Edit, Advanced, Comment Selection menu, or a keyboard shortcut for that menu.
http://bytes.com/topic/visual-basic-net/answers/376760-how-block-comment
You can also use showdialog
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
Handles Button3.Click
dim mydialogbox as new aboutbox1
aboutbox1.showdialog()
End Sub
Edited and fixed (thanks to Shredder)
If you mean you want to open a new tab, try the below:
protected void Page_Load(object sender, EventArgs e)
{
this.Form.Target = "_blank";
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Otherpage.aspx");
}
This will keep the original page to stay open and cause the redirects on the current page to affect the new tab only.
-J
I find the safest way is
If Not editTransactionRow.pay_id Is Nothing
It might read terribly, but the ISIL is actually very different from IsNot Nothing, and it doesn't try and evaluate the expression, which could give a null reference exception.
'In Visual Basic
Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml
Dim FilePath ="C:\MyFolderName" & "\" & FileName 'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.
If System.IO.File.Exists(FilePath) Then
MsgBox("The file exists")
Else
MsgBox("the file doesn't exist")
End If
Either use one of the standard date and time format strings which only specifies the date (e.g. "D" or "d"), or a custom date and time format string which only uses the date parts (e.g. "yyyy/MM/dd").
In the load events, use Me.Hide
.
In WebBrowser1.DocuementCompleted, use Me.Show
Use PE Explorer click here to know more and download
I've created a small plugin (available on NuGet) that allows you to add any (if supported by your terminal) color to your console output, without the limitations of the classic solutions.
It works by extending the String
object and the syntax is very simple:
"colorize me".Pastel("#1E90FF");
Both foreground and background colors are supported.
Is
is not the same as =
-- Is
compares the references, whilst =
will compare the values.
If you're using v2 of the .Net Framework (or later), there is the IsNot
operator which will do the right thing, and read more naturally.
Here's another way to do it, using a LINQ lambda:
C#:
SomeObject.GetType().GetProperties().ToList().ForEach(x => Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, null)}"));
VB.NET:
SomeObject.GetType.GetProperties.ToList.ForEach(Sub(x) Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, Nothing)}"))
Use the following Imports
Imports System.Data.SqlClient
Imports System.Data.Sql
Public SQLConn As New SqlConnection With {.ConnectionString = "Server=Desktop1[enter image description here][1];Database=Infostudio; Trusted_Connection=true;"}
I know this has been answered, but in VB.net above 2013 (the lowest I've personally used) you can just compare strings with an =
operator. This is the easiest way.
So basically:
If string1 = string2 Then
'do a thing
End If
You can check this like below :
if varDate = "#01/01/0001#" then
' blank date. do something.
else
' Date is not blank. Do some other thing
end if
You can also use System.Text.StringBuilder
class in this way:
Dim sValue As New System.Text.StringBuilder
sValue.AppendLine("1st Line")
sValue.AppendLine("2nd Line")
sValue.AppendLine("3rd Line")
Then you get the multiline string using:
sValue.ToString()
This happened to me already twice in a complex WPF app, in it there are 4 multi platform projects, 1 shared project, 2 support libraries, and 1 test project..
This very specific XAML namespace error happened twice on very recently modified files on the Shared project. In both of my cases, it was a new c# file added with a repeating namespace entry;
Like namespace MyProgram.MyFolder.MyProgram.MyFolder
I double pasted it once by mistake, and once it was due to JetBrains Rider double pasting the namespace. (If you ever rename a project in Rider, it time to time starts double pasting namespaces on new file creations, especially on Shared projects..). These c# files with repeating namespaces were then called in the ViewModels where XAML files were referencing to. Well you then get these unrelated and misleading errors, you can have a problem with one file, all your Xaml files will start erroring out eventually.
Anyways, if you get these kind of errors, it's most of the time an issue on a very newly added file or code change. My suggestions would be to look at your very recent changes.
Use chars:
Dim firstChar As char;
firstChar = s.Chars(0);
http://vb.net-informations.com/string/vb.net_String_Chars.htm
Public Sub PDFTxtToPdf(ByVal sTxtfile As String, ByVal sPDFSourcefile As String)
Dim sr As StreamReader = New StreamReader(sTxtfile)
Dim doc As New Document()
PdfWriter.GetInstance(doc, New FileStream(sPDFSourcefile, FileMode.Create))
doc.Open()
doc.Add(New Paragraph(sr.ReadToEnd()))
doc.Close()
End Sub
use <meta http-equiv="X-Frame-Options" content="allow">
in the one to show in the iframe to allow it.
Since you are asking about .NET, you should change the parameter from Long
to Integer
. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)
Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)
Really though, the managed method isn't difficult...
System.Threading.Thread.CurrentThread.Sleep(5000)
Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep
a good idea.
Much simpler solution, Select the Combo-box, and in the option of Selected item, select the item index (0 for the first item) and set it to be the default value in the combo box.
WebClient
doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:
Using client as new WebClient
result = client.UploadString(someurl, "param1=somevalue¶m2=othervalue")
End Using
n = ThisWorkbook.Worksheets(1).Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
This is the simple way:
text = "the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3
The String
class has a Replace
method that will do that.
Dim clean as String
clean = myString.Replace(",", "")
VB.net 4.0 framework Code :
Threading.Thread.Sleep(5000)
The integer is in miliseconds ( 1 sec = 1000 miliseconds)
I did test it and it works
I think what you're looking for is:
textBox1.Select();
in the constructor. (This is in C#. Maybe in VB that would be the same but without the semicolon.)
From http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx :
Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.
If you want to prevent resize by dragging sizegrips and by the maximize button and by maximize by doubleclick on the header text, than insert the following code in the load event of the form:
Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle ' Prevent size grips
Me.MaximumSize = Me.Size ' Prevent maximize (also by doubleclick of header text)
Of course all choices of a formborderstyle beginning with Fixed will do.
Using ddl.Items.Clear()
will clear the dropdownlist however you must be sure that your dropdownlist is not set to:
AppendDataBoundItems="True"
This option will cause the rebound data to be appended to the existing list which will NOT be cleared prior to binding.
SOLUTION
Add AppendDataBoundItems="False"
to your dropdownlist.
Now when data is rebound it will automatically clear all existing data beforehand.
Protected Sub ddl1_SelectedIndexChanged(sender As Object, e As EventArgs)
ddl2.DataSource = sql2
ddl2.DataBind()
End Sub
NOTE: This may not be suitable in all situations as appenddatbound items can cause your dropdown to append its own data on each change of the list.
TOP TIP
Still want a default list item adding to your dropdown but need to rebind data?
Use AppendDataBoundItems="False"
to prevent duplication data on postback and then directly after binding your dropdownlist insert a new default list item.
ddl.Items.Insert(0, New ListItem("Select ...", ""))
This is basically Muhammad Saqib's answer except two diffs:
1: Adds width and height function parameters.
2: This is a small nuance which can be ignored... Saying 'As Bitmap', instead of 'As Image'. 'As Image' does work just fine. I just prefer to match Return
types. See Image VS Bitmap Class.
Public Shared Function ResizeImage(ByVal InputBitmap As Bitmap, width As Integer, height As Integer) As Bitmap
Return New Bitmap(InputImage, New Size(width, height))
End Function
Ex.
Dim someimage As New Bitmap("C:\somefile")
someimage = ResizeImage(someimage,800,600)
Stopping the timer doesn't mean that it won't be called again, depending on when you stop the timer, the timer_tick may still be queued on the message loop for the form. What will happen is that you'll get one more tick that you may not be expecting. What you can do is in your timer_tick, check the Enabled property of your timer before executing the Timer_Tick method.
It's your "fault" in that that's how Or
is defined, so it's the behaviour you should expect:
In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.
But you don't have to endure it. You can use OrElse
to get short-circuiting behaviour.
So you probably want:
If (example Is Nothing OrElse Not example.Item = compare.Item) Then
'Proceed
End If
I can't say it reads terribly nicely, but it should work...
Constant Value Description
----------------------------------------------------------------
vbCr Chr(13) Carriage return
vbCrLf Chr(13) & Chr(10) Carriage return–linefeed combination
vbLf Chr(10) Line feed
vbCr : - return to line beginning
Represents a carriage-return character for print and display functions.
vbCrLf : - similar to pressing Enter
Represents a carriage-return character combined with a linefeed character for print and display
functions.
vbLf : - go to next line
Represents a linefeed character for print and display functions.
Read More from Constants Class
The function you're looking for is 'Insert'. It takes as its parameters the index you want to insert at, and an array of values to use for the new row values. Typical usage might include:
myDataGridView.Rows.Insert(4,new object[]{value1,value2,value3});
or something to that effect.
You could just use this
FileOpen(1, "C:\my files\2010\SomeFileName.txt", OpenMode.Output)
FileClose(1)
This opens the file replaces whatever is in it and closes the file.
Try this,
string Date = datePicker1.SelectedDate.Value.ToString("dd-MMM-yyyy");
It worked for me the output format will be '02-May-2016'
I just learned this trick from a friend. Put your code inside these 2 statements and it will be commented out.
#if false
#endif
var Test = (from row in Dataset1.Tables[0].AsEnumerable()
select row.Field<string>("attribute1_name") + row.Field<int>("attribute2_name")).Distinct();
Module MyHelpers
<Extension()>
Public Function UnEscape(ByVal aString As String) As String
Return Regex.Unescape(aString)
End Function
End Module
Usage:
console.writeline("Ciao!\n".unEscape)
For readability:
using System.Threading;
Thread.Sleep(TimeSpan.FromMilliseconds(50));
You may just remove all spaces and leverage LINQ All
:
Determines whether all elements of a sequence satisfy a condition.
Use it as shown below:
Dim number As String = "077 234 211"
If number.Replace(" ", "").All(AddressOf Char.IsDigit) Then
Console.WriteLine("The string is all numeric (spaces ignored)!")
Else
Console.WriteLine("The string contains a char that is not numeric and space!")
End If
To only check if a string consists of only digits use:
If number.All(AddressOf Char.IsDigit) Then
Is Nothing requires an object that has been assigned to the value Nothing. IsNothing() can take any variable that has not been initialized, including of numeric type. This is useful for example when testing if an optional parameter has been passed.
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (i.e. simple text) and not typed as DateTime
instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )
Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse
or DateTime.TryParseExact
, but implementing that is an exercise for the reader.
Short answer:
Neither
Longer answer:
using Argument*Exception (except in a library that is a product on its on, such as component library) is a smell. Exceptions are to handle exceptional situation, not bugs, and not user's (i.e. API consumer) shortfalls.
Longest answer:
Throwing exceptions for invalid arguments is rude, unless you write a library.
I prefer using assertions, for two (or more) reasons:
Here is what handling of null exception looks like (being sarcastic, obviously):
try {
library.Method(null);
}
catch (ArgumentNullException e) {
// retry with real argument this time
library.Method(realArgument);
}
Exceptions shall be used when situation is expected but exceptional (things happen that are outside of consumer's control, such as IO failure). Argument*Exception is an indication of a bug and shall be (my opinion) handled with tests and assisted with Debug.Assert
BTW: In this particular case, you could have used Month type, instead of int. C# falls short when it comes to type safety (Aspect# rulez!) but sometimes you can prevent (or catch at compile time) those bugs all together.
And yes, MicroSoft is wrong about that.
try..
Dim sortedList = From entry In mylist Order By entry.name Ascending Select entry
mylist = sortedList.ToList
Web.Config file:
<configuration>
<system.net>
<mailSettings>
<smtp from="[email protected]">
<network host="smtp.gmail.com"
port="587"
userName="[email protected]"
password="yourpassword"
enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
You can loop through the DataColumn and DataRow collections in your DataTable:
// Sum rows.
foreach (DataRow row in dt.Rows) {
int rowTotal = 0;
foreach (DataColumn col in row.Table.Columns) {
Console.WriteLine(row[col]);
rowTotal += Int32.Parse(row[col].ToString());
}
Console.WriteLine("row total: {0}", rowTotal);
}
// Sum columns.
foreach (DataColumn col in dt.Columns) {
int colTotal = 0;
foreach (DataRow row in col.Table.Rows) {
Console.WriteLine(row[col]);
colTotal += Int32.Parse(row[col].ToString());
}
Console.WriteLine("column total: {0}", colTotal);
}
Beware: The code above does not do any sort of checking before casting an object to an int.
EDIT: add a DataRow displaying the column sums
Try this to create a new row to display your column sums:
DataRow totalsRow = dt.NewRow();
foreach (DataColumn col in dt.Columns) {
int colTotal = 0;
foreach (DataRow row in col.Table.Rows) {
colTotal += Int32.Parse(row[col].ToString());
}
totalsRow[col.ColumnName] = colTotal;
}
dt.Rows.Add(totalsRow);
This approach is fine if the data type of any of your DataTable's DataRows are non-numeric or if you want to inspect the value of each cell as you sum. Otherwise I believe @Tim's response using DataTable.Compute
is a better.
Just remove the :
in your Quantity
. Make sure that your attribute is the same with the parameter you include in the code, like this:
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
If Me.DataGridView1.Rows(i).Cells("Quantity").Value < 5 Then
Me.DataGridView1.Rows(i).Cells("Quantity").Style.ForeColor = Color.Red
End If
Next
End Sub
private void SortDataTable(DataTable dt, string sort)
{
DataTable newDT = dt.Clone();
int rowCount = dt.Rows.Count;
DataRow[] foundRows = dt.Select(null, sort);
// Sort with Column name
for (int i = 0; i < rowCount; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j] = foundRows[i][j];
}
DataRow data_row = newDT.NewRow();
data_row.ItemArray = arr;
newDT.Rows.Add(data_row);
}
//clear the incoming dt
dt.Rows.Clear();
for (int i = 0; i < newDT.Rows.Count; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j] = newDT.Rows[i][j];
}
DataRow data_row = dt.NewRow();
data_row.ItemArray = arr;
dt.Rows.Add(data_row);
}
}
try
total.Text = DateTime.Now.ToString()
or
Dim theDate As DateTime = System.DateTime.Now
total.Text = theDate.ToString()
You declare Start
as an Integer
, while you are trying to put a DateTime
in it, which is not possible.
You either have to make the method Shared
or use an instance of the class General
:
Dim gen = New General()
gen.updateDynamics(get_prospect.dynamicsID)
or
General.updateDynamics(get_prospect.dynamicsID)
Public Shared Sub updateDynamics(dynID As Int32)
' ... '
End Sub
The maximum size for an int is 2147483647. You could use an Int64/Long which is far larger.
This works for me:
Console.OutputEncoding = System.Text.Encoding.Default;
To display some of the symbols, it's required to set Command Prompt's font to Lucida Console:
Open Command Prompt;
Right click on the top bar of the Command Prompt;
Click Properties;
If the font is set to Raster Fonts, change it to Lucida Console.
The discussion here gives the answer:
Actually, the specific discussion I witnessed did in fact hinge over functional purity. In an expression, there are frequently assumptions made about not having side-effects. Having ForEach is specifically inviting side-effects rather than just putting up with them. -- Keith Farmer (Partner)
Basically the decision was made to keep the extension methods functionally "pure". A ForEach would encourage side-effects when using the Enumerable extension methods, which was not the intent.
I think your first line would actually work but I think you need four quotation marks for a string containing a single one (in VB at least):
s = s.Replace("""", "")
for C# you'd have to escape the quotation mark using a backslash:
s = s.Replace("\"", "");
You can't, because it does not generate any SQL.
The parameterized query (the one in CommandText
) is sent to the SQL Server as the equivalent of a prepared statement. When you execute the command, the parameters and the query text are treated separately. At no point in time a complete SQL string is generated.
You can use SQL Profiler to take a look behind the scenes.
See this page for the solution! https://msdn.microsoft.com/en-us/library/7aw8zc76(v=vs.110).aspx
I was able to implement the Child
form inside the parent.
In the Example below Form2
should change to the name of your child form.
NewMDIChild.MdiParent=me
is the main form since the control that opens (shows) the child form is the parent or Me
.
NewMDIChild.Show()
is your child form since you associated your child form with Dim NewMDIChild As New Form2()
Protected Sub MDIChildNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click
Dim NewMDIChild As New Form2()
'Set the Parent Form of the Child window.
NewMDIChild.MdiParent = Me
'Display the new form.
NewMDIChild.Show()
End Sub
Simple and it works.
I opened one Word file, 2. Now I open another word file through vb.net runtime programmatically. 3. I want to kill the second process alone through programmatically. 4. Do not kill first process
Try this.
var dateAsString = DateTime.Now.ToString("dd/MM/yyyy");
// dateAsString = "09/07/2013"
If you are looking for the amount of time that the associated thread has spent running code inside the application.
You can use ProcessThread.UserProcessorTime
Property which you can get under System.Diagnostics
namespace.
TimeSpan startTime= Process.GetCurrentProcess().Threads[i].UserProcessorTime; // i being your thread number, make it 0 for main
//Write your function here
TimeSpan duration = Process.GetCurrentProcess().Threads[i].UserProcessorTime.Subtract(startTime);
Console.WriteLine($"Time caluclated by CurrentProcess method: {duration.TotalSeconds}"); // This syntax works only with C# 6.0 and above
Note: If you are using multi threads, you can calculate the time of each thread individually and sum it up for calculating the total duration.
The following code can help you to understand some real world use of predicates (Combined with named iterators).
namespace Predicate
{
class Person
{
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
foreach (Person person in OlderThan(18))
{
Console.WriteLine(person.Age);
}
}
static IEnumerable<Person> OlderThan(int age)
{
Predicate<Person> isOld = x => x.Age > age;
Person[] persons = { new Person { Age = 10 }, new Person { Age = 20 }, new Person { Age = 19 } };
foreach (Person person in persons)
if (isOld(person)) yield return person;
}
}
}
You can use DataSet.Tables(0).Columns.Contains(name)
to check whether the DataTable
contains a column with a particular name.
Use:
dateTimePicker.Value.ToString("yyyy/MM/dd")
Refer to the following link:
http://www.vbdotnetforums.com/schedule-time/15001-datetimepicker-format.html
I have suffered a similar problem, with a Sub not accessible in runtime, but absolutely legal in editor. It was solved by changing destination Framework from 4.5.1 to 4.5. It seems that my IIS only had 4.5 version.
:)
I like to use the following method (it supports up to terabytes, which is enough for most cases, but it can easily be extended):
private string GetSizeString(long length)
{
long B = 0, KB = 1024, MB = KB * 1024, GB = MB * 1024, TB = GB * 1024;
double size = length;
string suffix = nameof(B);
if (length >= TB) {
size = Math.Round((double)length / TB, 2);
suffix = nameof(TB);
}
else if (length >= GB) {
size = Math.Round((double)length / GB, 2);
suffix = nameof(GB);
}
else if (length >= MB) {
size = Math.Round((double)length / MB, 2);
suffix = nameof(MB);
}
else if (length >= KB) {
size = Math.Round((double)length / KB, 2);
suffix = nameof(KB);
}
return $"{size} {suffix}";
}
Please keep in mind that this is written for C# 6.0 (2015), so it might need a little editing for earlier versions.
A good resource start off point would be MSDN as your looking into a microsoft product
I think your ListBox already clear with ListBox2.Items.Clear(). The problem is that you also need to clear your dataset from previous results with ds6.Tables.Clear().
Add this in your code:
da6 = New SqlDataAdapter("select distinct(component_type) from component where component_name='" & ListBox1.SelectedItem() & "'", con)
ListBox1.Items.Clear() ' clears ListBox1
ListBox2.Items.Clear() ' clears ListBox2
ds6.Tables.Clear() ' clears DataSet <======= DON'T FORGET TO DO THIS
da6.Fill(ds6, "component")
For Each row As DataRow In ds6.Tables(0).Rows
ListBox2.Items.Add(row.Field(Of String)("component_type"))
Next
Form myForm;
myForm.WindowState = FormWindowState.Minimized;
You should create a pseudo-random number generator only once:
Dim Generator As System.Random = New System.Random()
Then, if an integer suffices for your needs, you can use:
Public Function GetRandom(myGenerator As System.Random, ByVal Min As Integer, ByVal Max As Integer) As Integer
'min is inclusive, max is exclusive (dah!)
Return myGenerator.Next(Min, Max + 1)
End Function
as many times as you like. Using the wrapper function is justified only because the maximum value is exclusive - I know that the random numbers work this way but the definition of .Next is confusing.
Creating a generator every time you need a number is in my opinion wrong; the pseudo-random numbers do not work this way.
First, you get the problem with initialization which has been discussed in the other replies. If you initialize once, you do not have this problem.
Second, I am not at all certain that you get a valid sequence of random numbers; rather, you get a collection of the first number of multiple different sequences which are seeded automatically based on computer time. I am not certain that these numbers will pass the tests that confirm the randomness of the sequence.
For formatting options, see this
Dim v1 as Double = Val(txtD.Text) / Val(txtC.Text) *
Val(txtF.Text) / Val(txtE.Text)
txtA.text = v1.ToString("N2");
Try to use DateTime.ParseExact method, in which you can specify both of datetime mask and original parsed string. You can read about it here: MSDN: DateTime.ParseExact
?? To state the answer differently ??
In Xaml verify that there are no Missing Parent Nodes or incorrect nodes in the defined areas.
For example
There is no proper parent for the ItemsPanelTemplate
child node below:
<ItemsControl ItemsSource="{Binding TimeSpanChoices}">
<ItemsPanelTemplate>
<UniformGrid Rows="1" />
</ItemsPanelTemplate>
...
</ItemsControl>
<ItemsControl ItemsSource="{Binding TimeSpanChoices}">
<ItemsControl.ItemsPanel> <!-- I am the missing parent! -->
<ItemsPanelTemplate>
<UniformGrid Rows="1" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
...
</ItemsControl>
There is a proper parent node of <ItemsControl.ItemsPanel>
provided^^^.
Convert.ToIntXX doesn't like being passed strings of decimals.
To be safe use
Convert.ToInt32(Convert.ToDecimal(txtPrice.Text))
If you want more control over how the conversion takes place, you can use ConvertAll:
var stringList = myList.ConvertAll(obj => obj.SomeToStringMethod());
Yeah, for most cases, you don't need to create a class with getters and setters. Just create a new Dictionary and bind it to the data source. Here's an example in VB using a for loop to set the DisplayMember and ValueMember of a combo box from a list:
Dim comboSource As New Dictionary(Of String, String)()
cboMenu.Items.Clear()
For I = 0 To SomeList.GetUpperBound(0)
comboSource.Add(SomeList(I).Prop1, SomeList(I).Prop2)
Next I
cboMenu.DataSource = New BindingSource(comboSource, Nothing)
cboMenu.DisplayMember = "Value"
cboMenu.ValueMember = "Key"
Then you can set up a data grid view's rows according to the value or whatever you need by calling a method on click:
Private Sub cboMenu_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMenu.SelectionChangeCommitted
SetListGrid(cboManufMenu.SelectedValue)
End Sub
Not sure what you mean with "class constructor" but I'd assume you mean one of the ones below.
Instance constructor:
Public Sub New()
End Sub
Shared constructor:
Shared Sub New()
End Sub
VB Version:
Class:
Protected divControl As System.Web.UI.HtmlControls.HtmlGenericControl
OnLoad/Other function:
divControl.Style("height") = "200px"
I've never tried the Add method with the styles. What if the height already exists on the DIV?
foo.ToArray().Aggregate((a, b) => (a + "," + b)).ToString()
or
string.Concat(foo.ToArray().Select(a => a += ",").ToArray())
Updating, as this is extremely old. You should, of course, use string.Join now. It didn't exist as an option at the time of writing.
I sympathise with the question - I too found (find?) the choice bewildering, so I set out scientifically to see which data structure is the fastest (I did the test using VB, but I imagine C# would be the same, since both languages do the same thing at the CLR level). You can see some benchmarking results conducted by me here (there's also some discussion of which data type is best to use in which circumstances).
This is an improved version of the recursive GetAllControls() that actually works on private vars:
private void Test()
{
List<Control> allTextboxes = GetAllControls(this);
}
private List<Control> GetAllControls(Control container, List<Control> list)
{
foreach (Control c in container.Controls)
{
if (c is TextBox) list.Add(c);
if (c.Controls.Count > 0)
list = GetAllControls(c, list);
}
return list;
}
private List<Control> GetAllControls(Control container)
{
return GetAllControls(container, new List<Control>());
}
An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files.
AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.
For Each row As DataGridViewRow In yourDGV.SelectedRows
yourDGV.Rows.Remove(row)
Next
This will delete all rows that had been selected.
I think the problem is that you're adding a new entry to the database, but not the data structure that the datagrid represents. You're only querying the database for data in the load event, so if the database changes after that you're not going to know about it.
To solve the problem you need to either re-query the database after each insert, or add the item to tables(0) data structure in addition to the Access table after each insert.
hi friend in this case you can use the
AppendDataBound="true"
and after this use the list item. for e.g.:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
but the problem in this is after second time select data are append with old data.
Check out Environment.NewLine
. As for web pages, break lines with <br>
or <p></p>
tags.
In SQL you need to use GETDATE()
:
UPDATE table SET date = GETDATE();
There is no NOW()
function.
To answer your question:
In a large table, since the function is evaluated for each row, you will end up getting different values for the updated field.
So, if your requirement is to set it all to the same date I would do something like this (untested):
DECLARE @currDate DATETIME;
SET @currDate = GETDATE();
UPDATE table SET date = @currDate;
For those who are stuck maintaining old .net, here is one that works in .net framework 2.x:
Dim lstOfStrings As New List(of String)( new String(){"v1","v2","v3"} )
A different approach would be to have two tab controls, one visible, and one not. You can move the tabs from one to the other like this (vb.net):
If Me.chkShowTab1.Checked = True Then
Me.tabsShown.TabPages.Add(Me.tabsHidden.TabPages("Tab1"))
Me.tabsHidden.TabPages.RemoveByKey("Tab1")
Else
Me.tabsHidden.TabPages.Add(Me.tabsShown.TabPages("Tab1"))
Me.tabsShown.TabPages.RemoveByKey("Tab1")
End If
If the tab order is important, change the .Add method on tabsShown to .Insert and specify the ordinal position. One way to do that is to call a routine that returns the desired ordinal position.
Use this syntax for VB.NET 2005/2008 compatibility:
Dim theVar As New List(Of String)(New String() {"one", "two", "three"})
Although the VB.NET 2010 syntax is prettier.
Private Function LoaderData(ByVal strSql As String) As DataTable
Dim cnn As SqlConnection
Dim dad As SqlDataAdapter
Dim dtb As New DataTable
cnn = New SqlConnection(My.Settings.mySqlConnectionString)
Try
cnn.Open()
dad = New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
cnn.Close()
dad.Dispose()
Catch ex As Exception
cnn.Close()
MsgBox(ex.Message)
End Try
Return dtb
End Function
Some times this problem arise when Application is build in one PC and try to run another PC. And also build the application with Visual Studio 2010.I have the following problem
Problem Description
Stop Working
Problem Signature
Problem Event Name: CLR20r3
Problem Signature 01: diagnosticcentermngr.exe
Problem Signature 02: 1.0.0.0
Problem Signature 03: 4f8c1772
Problem Signature 04: System.Drawing
Problem Signature 05: 2.0.0.0
Problem Signature 06: 4a275e83
Problem Signature 07: 7af
Problem Signature 08: 6c
Problem Signature 09: System.ArgumentException
OS Version: 6.1.7600.2.0.0.256.1
Locale ID: 1033
Read our privacy statement online:
http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409
If the online privacy statement is not available, please read our privacy statement offline:
C:\Windows\system32\en-US\erofflps.txt
Dont worry, Please check out following link and install .net framework 4.Although my application .net properties was .net framework 2.
http://www.microsoft.com/download/en/details.aspx?id=17718
restart your PC and try again.
Imports System.Net
Module MainLine
Sub Main()
Dim hostName As String = Dns.GetHostName
Console.WriteLine("Host Name : " & hostName & vbNewLine)
For Each address In Dns.GetHostEntry(hostName).AddressList()
Select Case Convert.ToInt32(address.AddressFamily)
Case 2
Console.WriteLine("IP Version 4 Address: " & address.ToString)
Case 23
Console.WriteLine("IP Version 6 Address: " & address.ToString)
End Select
Next
Console.ReadKey()
End Sub
End Module
I saw in getwindowtext (user32) on pinvoke.net that you can place a MarshalAs
statement to state that the StringBuffer is equivalent to LPSTR.
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Public Function GetWindowText(hwnd As IntPtr, <MarshalAs(UnManagedType.LPStr)>lpString As System.Text.StringBuilder, cch As Integer) As Integer
End Function
The data from the request (content, inputs, files, querystring values) is all on this object HttpContext.Current.Request
To read the posted content
StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();
To navigate through the all inputs
foreach (string key in HttpContext.Current.Request.Form.AllKeys)
{
string value = HttpContext.Current.Request.Form[key];
}
I have always used OLEDB
for this, something like...
Dim sSheetName As String
Dim sConnection As String
Dim dtTablesList As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
oleExcelConnection = New OleDbConnection(sConnection)
oleExcelConnection.Open()
dtTablesList = oleExcelConnection.GetSchema("Tables")
If dtTablesList.Rows.Count > 0 Then
sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
End If
dtTablesList.Clear()
dtTablesList.Dispose()
If sSheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
nOutputRow = 0
While oleExcelReader.Read
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
The ACE.OLEDB
provider will read both .xls
and .xlsx
files and I have always found the speed quite good.
try to clear workspace.
rm -rf ' ~/Library/Application\ Support/"your programm name" '
<a href="/fruits/index.html">Back to Fruits List</a>
This is the optimal way, I found, to do this:
private void GetSubArrayThroughArraySegment() {
int[] array = { 10, 20, 30 };
ArraySegment<int> segment = new ArraySegment<int>(array, 1, 2);
Console.WriteLine("-- Array --");
int[] original = segment.Array;
foreach (int value in original)
{
Console.WriteLine(value);
}
Console.WriteLine("-- Offset --");
Console.WriteLine(segment.Offset);
Console.WriteLine("-- Count --");
Console.WriteLine(segment.Count);
Console.WriteLine("-- Range --");
for (int i = segment.Offset; i <= segment.Count; i++)
{
Console.WriteLine(segment.Array[i]);
}
}
Hope It Helps!
You can use the two dots at the end of expression, too. See this example:
//*[title="50"]/..
Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET
command. The first one to stop the service, the second one to start the service. Give them a STOP
and START
argument, followed by the service name.
In this example we restart the Printer Spooler service.
NET STOP "Print Spooler"
NET START "Print Spooler"
Note: unfortunately NET RESTART <service name>
does not exist.
I will use one example to explain how JNDI can be used to configure database without any application developer knowing username and password of the database.
1) We have configured the data source in JBoss server's standalone-full.xml. Additionally, we can configure pool details also.
<datasource jta="false" jndi-name="java:/DEV.DS" pool-name="DEV" enabled="true" use-ccm="false">
<connection-url>jdbc:oracle:thin:@<IP>:1521:DEV</connection-url>
<driver-class>oracle.jdbc.OracleDriver</driver-class>
<driver>oracle</driver>
<security>
<user-name>usname</user-name>
<password>pass</password>
</security>
<security>
<security-domain>encryptedSecurityDomain</security-domain>
</security>
<validation>
<validate-on-match>false</validate-on-match>
<background-validation>false</background-validation>
<background-validation-millis>1</background-validation-millis>
</validation>
<statement>
<prepared-statement-cache-size>0</prepared-statement-cache-size>
<share-prepared-statements>false</share-prepared-statements>
<pool>
<min-pool-size>5</min-pool-size>
<max-pool-size>10</max-pool-size>
</pool>
</statement>
</datasource>
Now, this jndi-name and its associated datasource object will be available for our application.application.
2) We can retrieve this datasource object using JndiDataSourceLookup class.
Spring will instantiate the datasource bean, after we provide the jndi-name.
Now, we can change the pool size, user name or password as per our environment or requirement, but it will not impact the application.
Note : encryptedSecurityDomain, we need to configure it separately in JBoss server like
<security-domain name="encryptedSecurityDomain" cache-type="default">
<authentication>
<login-module code="org.picketbox.datasource.security.SecureIdentityLoginModule" flag="required">
<module-option name="username" value="<usernamefordb>"/>
<module-option name="password" value="894c8a6aegc8d028ce169c596d67afd0"/>
</login-module>
</authentication>
</security-domain>
This is one of the use cases. Hope it clarifies.
I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.
This one does not use SendKeys.
Let me know if this helps! JFV
You can use this program instead of sprintf.
void itochar(int x, char *buffer, int radix);
int main()
{
char buffer[10];
itochar(725, buffer, 10);
printf ("\n %s \n", buffer);
return 0;
}
void itochar(int x, char *buffer, int radix)
{
int i = 0 , n,s;
n = s;
while (n > 0)
{
s = n%radix;
n = n/radix;
buffer[i++] = '0' + s;
}
buffer[i] = '\0';
strrev(buffer);
}
void main(){
var x = "4";
int number = int.parse(x);//STRING to INT
var y = "4.6";
double doubleNum = double.parse(y);//STRING to DOUBLE
var z = 55;
String myStr = z.toString();//INT to STRING
}
int.parse() and double.parse() can throw an error when it couldn't parse the String
Proper way now is the following:
git filter-branch --prune-empty --subdirectory-filter FOLDER_NAME [first_branch] [another_branch]
GitHub now even have small article about such cases.
But be sure to clone your original repo to separate directory first (as it would delete all the files and other directories and you probable need to work with them).
So your algorithm should be:
git filter-branch
left only files under some subdirectory, push to new remoteThis is the intended use case for Ray, which is a library for parallel and distributed Python. Under the hood, it serializes objects using the Apache Arrow data layout (which is a zero-copy format) and stores them in a shared-memory object store so they can be accessed by multiple processes without creating copies.
The code would look like the following.
import numpy as np
import ray
ray.init()
@ray.remote
def func(array, param):
# Do stuff.
return 1
array = np.ones(10**6)
# Store the array in the shared memory object store once
# so it is not copied multiple times.
array_id = ray.put(array)
result_ids = [func.remote(array_id, i) for i in range(4)]
output = ray.get(result_ids)
If you don't call ray.put
then the array will still be stored in shared memory, but that will be done once per invocation of func
, which is not what you want.
Note that this will work not only for arrays but also for objects that contain arrays, e.g., dictionaries mapping ints to arrays as below.
You can compare the performance of serialization in Ray versus pickle by running the following in IPython.
import numpy as np
import pickle
import ray
ray.init()
x = {i: np.ones(10**7) for i in range(20)}
# Time Ray.
%time x_id = ray.put(x) # 2.4s
%time new_x = ray.get(x_id) # 0.00073s
# Time pickle.
%time serialized = pickle.dumps(x) # 2.6s
%time deserialized = pickle.loads(serialized) # 1.9s
Serialization with Ray is only slightly faster than pickle, but deserialization is 1000x faster because of the use of shared memory (this number will of course depend on the object).
See the Ray documentation. You can read more about fast serialization using Ray and Arrow. Note I'm one of the Ray developers.
This got me the value and text of the selected options for the jQuery multiselect.js plugin:
$("#selectBox").multiSelect({
afterSelect: function(){
var selections = [];
$("#selectBox option:selected").each(function(){
var optionValue = $(this).val();
var optionText = $(this).text();
console.log("optionText",optionText);
// collect all values
selections.push(optionValue);
});
// use array "selections" here..
}
});
very usefull if you need it for your "onChange" event ;)
Another workaround is to turn off Internet connection, reboot and restart VS installation. Without Internet connectivity VS installer won't try to update Windows first and will continue without delay.
Replace the desired hyphen with an underscore; it will automatically be rendered as a hyphen:
@Html.ActionLink("Edit", "edit", "markets",
new { id = 1 },
new {@class="ui-btn-right", data_icon="gear"})
becomes:
<form action="markets/Edit/1" class="ui-btn-right" data-icon="gear" .../>
You're getting a linker error, so your extern is working (the compiler compiled a.c
without a problem), but when it went to link the object files together at the end it couldn't resolve your extern -- void doSomething(int);
wasn't actually found anywhere. Did you mess up the extern? Make sure there's actually a doSomething
defined in b.c
that takes an int
and returns void
, and make sure you remembered to include b.c
in your file list (i.e. you're doing something like gcc a.c b.c
, not just gcc a.c
)
Try this, it should work for what you need:
editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
//do here your stuff f
return true;
}
return false;
}
});
A more elegant and simple solution is to use
git stash
It will return to the most resent local version of the branch and also save your changes in stash, so if you like to undo this action do:
git stash apply
this fails:
DECLARE @vPortalUID NVARCHAR(32)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
PRINT @nPortalUID
this works
DECLARE @vPortalUID NVARCHAR(36)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
PRINT @nPortalUID
the difference is NVARCHAR(36)
, your input parameter is too small!
A simpler way would be to create a link called cudart64_101.dll
to point to cudart64_102.dll
. This is not very orthodox but since TensorFlow is looking for cudart64_101.dll
exported symbols and the nvidia folks are not amateurs, they would most likely not remove symbols from 101 to 102. It works, based on this assumption (mileage may vary).
I think you need to use the notifications that are provided about the keyboard:
Keyboard Notifications
When the system shows or hides the keyboard, it posts several keyboard notifications. These notifications contain information about the keyboard, including its size, which you can use for calculations that involve moving views. Registering for these notifications is the only way to get some types of information about the keyboard. The system delivers the following notifications for keyboard-related events:
* UIKeyboardWillShowNotification * UIKeyboardDidShowNotification * UIKeyboardWillHideNotification * UIKeyboardDidHideNotification
For more information about these notifications, see their descriptions in UIWindow Class Reference. For information about how to show and hide the keyboard, see Text and Web.
This is my main activity where i take the username and password from edit text and setting to the intent
class MainActivity : AppCompatActivity() {
val userName = null
val password = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
val intent = Intent(this@MainActivity,SecondActivity::class.java);
var userName = username.text.toString()
var password = password_field.text.toString()
intent.putExtra("Username", userName)
intent.putExtra("Password", password)
startActivity(intent);
}
}
This is my second activity where i have to receive values from the main activity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
var strUser: String = intent.getStringExtra("Username")
var strPassword: String = intent.getStringExtra("Password")
user_name.setText("Seelan")
passwor_print.setText("Seelan")
}
In Notepad++, choose the "Encoding" menu, then "Encode in UTF-8 without BOM". Then save.
See Stack Overflow question How to make Notepad to save text in UTF-8 without BOM?.
SELECT * FROM courses WHERE (NOW() + INTERVAL 2 HOUR) > start_time
Note for git submodule users - the solutions here will not work for you as-is.
Let's say you have a parent repository called dev
, for example, and your submodule repository is called api
.
if you are inside of api
and you get the error mentioned in this question:
error: bad index file sha1 signature
fatal: index file corrupt
The index
file will NOT be inside of a .git
folder. In fact, the .git
won't even be a folder - it will will be a text document with the location of the real .git data for this repository. Likely something like this:
~/dev/api $ cat .git
gitdir: ../.git/modules/api
So, instead of rm -f .git/index
, you will need to do this:
rm -f ../.git/modules/api/index
git reset
or, more generally,
rm -f ../.git/modules/INSERT_YOUR_REPO_NAME_HERE/index
git reset
You probably shouldn't, and you can probably do what you want to do in a safer and simpler way. Technically to use variable number of arguments in C you include stdarg.h. From that you'll get the va_list
type as well as three functions that operate on it called va_start()
, va_arg()
and va_end()
.
#include<stdarg.h>
int maxof(int n_args, ...)
{
va_list ap;
va_start(ap, n_args);
int max = va_arg(ap, int);
for(int i = 2; i <= n_args; i++) {
int a = va_arg(ap, int);
if(a > max) max = a;
}
va_end(ap);
return max;
}
If you ask me, this is a mess. It looks bad, it's unsafe, and it's full of technical details that have nothing to do with what you're conceptually trying to achieve. Instead, consider using overloading or inheritance/polymorphism, builder pattern (as in operator<<()
in streams) or default arguments etc. These are all safer: the compiler gets to know more about what you're trying to do so there are more occasions it can stop you before you blow your leg off.
It depends on what runs cron on your system, but all you have to do to run a php script from cron is to do call the location of the php installation followed by the script location. An example with crontab running every hour:
# crontab -e
00 * * * * /usr/local/bin/php /home/path/script.php
On my system, I don't even have to put the path to the php installation:
00 * * * * php /home/path/script.php
On another note, you should not be using mysql extension because it is deprecated, unless you are using an older installation of php. Read here for a comparison.
In my case, I needed to add the JMETER_HOME
environment variable to be available via my Ant build scripts across all projects on my Jenkins server (Linux), in a way that would not interfere with my local build environment (Windows and Mac) in the build.xml
script. Setting the environment variable via Manage Jenkins - Configure System - Global properties was the easiest and least intrusive way to accomplish this. No plug-ins are necessary.
The environment variable is then available in Ant via:
<property environment="env" />
<property name="jmeter.home" value="${env.JMETER_HOME}" />
This can be verified to works by adding:
<echo message="JMeter Home: ${jmeter.home}"/>
Which produces:
JMeter Home: ~/.jmeter
Switch the order of the code: You're calling the click event before it is attached.
$(document).ready(function() {
$("#checkbox_div input:radio").click(function() {
alert("clicked");
});
$("input:radio:first").prop("checked", true).trigger("click");
});
People keep upvoting my answer, but it's a terrible solution compared to the joy of sass or less, particularly given the number of easy to use gui's for both these days. If you have any sense ignore everything I suggest below.
You could put a comment in the css before each colour in order to serve as a sort of variable, which you can change the value of using find/replace, so...
At the top of the css file
/********************* Colour reference chart****************
*************************** comment ********* colour ********
box background colour bbg #567890
box border colour bb #abcdef
box text colour bt #123456
*/
Later in the CSS file
.contentBox {background: /*bbg*/#567890; border: 2px solid /*bb*/#abcdef; color:/*bt*/#123456}
Then to, for example, change the colour scheme for the box text you do a find/replace on
/*bt*/#123456
For an external (cross-site) solution, you can use: Get contents of a link tag with JavaScript - not CSS
It uses $.ajax()
function, so it includes jquery.
PHP redirects are better if you can as with the JavaScript one you're causing the client to load the page before the redirect, whereas with the PHP one it sends the proper header.
However the PHP shouldn't go in the <head>, it should go before any output is sent to the client, as to do otherwise will cause errors.
Using <meta> tags have the same issue as Javascript in causing the initial page to load before doing the redirect. Server-side redirects are almost always better, if you can use them.
If you want to call them like that, you should declare them static.
How about something like:
<script src='http://code.jquery.com/jquery-latest.js'></script>
function print_r(o){
return JSON.stringify(o,null,'\t').replace(/\n/g,'<br>').replace(/\t/g,' '); }
The problem is your query returned false
meaning there was an error in your query. After your query you could do the following:
if (!$result) {
die(mysqli_error($link));
}
Or you could combine it with your query:
$results = mysqli_query($link, $query) or die(mysqli_error($link));
That will print out your error.
Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:
$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";
In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist
Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.
You must conform to 2 rules:
[HttpGet("xxx")]
,[HttpPost("xxx")]
or ... instead of [Route("xxx")]
.[NonAction]
Attribute.Note that http://localhost:XXXX/swagger/ page requests for http://localhost:XXXX/swagger/v1/swagger.json file, but an Exception will occur from Swagger if you wouldn't conform above rules.
change ;memory_limit=512M
to ;memory_limit=-1
in
it's too dangerous for a server Your PHP code may have a memory leak somewhere and you are telling the server to just use all the memory that it wants. You wouldn't have fixed the problem at all. If you monitor your server, you will see that it is now probably using up most of the RAM and even swapping to disk.
Try this:
import re
mystr = 'This is a string, with words!'
wordList = re.sub("[^\w]", " ", mystr).split()
How it works:
From the docs :
re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function.
so in our case :
pattern is any non-alphanumeric character.
[\w] means any alphanumeric character and is equal to the character set [a-zA-Z0-9_]
a to z, A to Z , 0 to 9 and underscore.
so we match any non-alphanumeric character and replace it with a space .
and then we split() it which splits string by space and converts it to a list
so 'hello-world'
becomes 'hello world'
with re.sub
and then ['hello' , 'world']
after split()
let me know if any doubts come up.
Those integer types are all defined in stdint.h
Again for completeness I'll add my most useful use-case for with
statements.
I do a lot of scientific computing and for some activities I need the Decimal
library for arbitrary precision calculations. Some part of my code I need high precision and for most other parts I need less precision.
I set my default precision to a low number and then use with
to get a more precise answer for some sections:
from decimal import localcontext
with localcontext() as ctx:
ctx.prec = 42 # Perform a high precision calculation
s = calculate_something()
s = +s # Round the final result back to the default precision
I use this a lot with the Hypergeometric Test which requires the division of large numbers resulting form factorials. When you do genomic scale calculations you have to be careful of round-off and overflow errors.
Those reference pretty much answered your question. Simply put, vectors' lengths are dynamic while arrays have a fixed size. when using an array, you specify its size upon declaration:
int myArray[100];
myArray[0]=1;
myArray[1]=2;
myArray[2]=3;
for vectors, you just declare it and add elements
vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
...
at times you wont know the number of elements needed so a vector would be ideal for such a situation.
to_string() is only present in c++11 so if c++ version is less use some alternate methods such as sprintf or ostringstream
I would prefer to shelve changes instead of stashing them if I am not sharing my changes elsewhere.
Stashing is a git feature and doesn't give you the option to select specific files or changes inside a file. Shelving can do that but this is an IDE-specific feature, not a git feature:
As you can see I am able to choose to specify which files/lines to include on my shelve. Note that I can't do that with stashing.
Beware using shelves in the IDE may limit the portability of your patches because those changes are not stored in a .git folder.
Some helpful links:
Ya its possible to do without support of javascript..
We can use html5 auto focus attribute
For Example:
<input type="text" name="name" autofocus="autofocus" id="xax" />
If use it (autofocus="autofocus") in text field means that text field get focused when page gets loaded..
For more details:
http://www.hscripts.com/tutorials/html5/autofocus-attribute.html
Tested on Firefox: removing and putting back the image works! And it's transparent at the execution, too. For instance,
$('.imageContainerClass').mousedown(function() {
var id = $(this).attr('id');
$('#'+id).remove();
$('#'+id).append('Image tag code');
});
EDIT: This works only on IE and on Firefox, strangely. I also added draggable = false
on each image. Still a ghost with Chrome and Safari.
EDIT 2: The background-image solution is genuinely the best one. The only subtlety is that the background-size
property has to be redefined every time the background-image is changed! Or so, that's what it looked like from my side. Better still, I had an issue with normal img
tags under IE, where IE failed to resize the images. Now, the images have the correct dimensions. Simple:
$(id).css( 'background-image', url('blah.png') );
$(id).css( 'background-size', '40px');
Also, perhaps consider those:
background-Repeat:no-repeat;
background-Position: center center;
export class ClassComponent implements OnInit {
classes = [
{
name: 'string',
level: 'string',
code: 'number',
currentLesson: '1'
}]
checkCurrentLession(current){
this.classes.forEach((obj)=>{
if(obj.currentLession == current){
return true;
}
});
return false;
}
<ul class="table lessonOverview">
<li>
<p>Lesson 1</p>
<button [routerLink]="['/lesson1']"
[disabled]="checkCurrentLession(1)" class="primair">
Start lesson</button>
</li>
<li>
<p>Lesson 2</p>
<button [routerLink]="['/lesson2']"
[disabled]="!checkCurrentLession(2)" class="primair">
Start lesson</button>
</li>
</ul>
Suppose originally there were 3 commits, A
,B
,C
:
Then developer Dan created commit D
, and developer Ed created commit E
:
Obviously, this conflict should be resolved somehow. For this, there are 2 ways:
MERGE:
Both commits D
and E
are still here, but we create merge commit M
that inherits changes from both D
and E
. However, this creates diamond shape, which many people find very confusing.
REBASE:
We create commit R
, which actual file content is identical to that of merge commit M
above. But, we get rid of commit E
, like it never existed (denoted by dots - vanishing line). Because of this obliteration, E
should be local to developer Ed and should have never been pushed to any other repository. Advantage of rebase is that diamond shape is avoided, and history stays nice straight line - most developers love that!
there is a function that will return an array of all the strings found.
Filter(sourcearray, match[, include[, compare]])
The sourcearray has to be 1 dimensional
The function will return all strings in the array that have the match
string in them
In Python3, you can:
print("%02d" % a)
After perusing your previous questions I eventually determined you are probably on SQL Server 2005. For US format you would use style 101
select Subject,
CONVERT(varchar,DeliveryDate,101) as DeliveryDate
from Email_Administration
where MerchantId =@MerchantID
Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate XslCompiledTransform.Transform overload:
var myXslTrans = new XslCompiledTransform();
myXslTrans.Load("stylesheet.xsl");
myXslTrans.Transform("source.xml", "result.html");
(Sorry for posing this as an answer, but the code block
support in comments is rather limited.)
In VB.NET, you don't even need a variable:
With New XslCompiledTransform()
.Load("stylesheet.xsl")
.Transform("source.xml", "result.html")
End With
Try using cygwin instead of bash. that worked for me
You can also hide a column using the col element https://developer.mozilla.org/en/docs/Web/HTML/Element/col
To hide the second column in a table:
<table>
<col />
<col style="visibility:collapse"/>
<tr><td>visible</td><td>hidden</td></tr>
<tr><td>visible</td><td>hidden</td></tr>
Known issues: this won't work in Google Chrome. Please vote for the bug at https://bugs.chromium.org/p/chromium/issues/detail?id=174167
The error usually means that the port you are trying to open is being already used by another application. Try using netstat to see which ports are open and then use an available port.
Also check if you are binding to the right ip address (I am assuming it would be localhost)
Based on previous posts, I ended up with the following light-weigh alias solution that can be added to .bashrc
:
if [ -n "$(type -P xclip)" ]
then
alias xclip='xclip -selection clipboard'
alias clipboard='if [ -p /dev/stdin ]; then xclip -in; fi; xclip -out'
fi
Examples:
# Copy
$ date | clipboard
Sat Dec 29 14:12:57 PST 2018
# Paste
$ date
Sat Dec 29 14:12:57 PST 2018
# Chain
$ date | clipboard | wc
1 6 29
Just to add to answers by Mr. Dimitrov and Jason, if you are using a specific profile and you have put your region setting there,then for all the requests you need to add
"--profile" option.
For example:
Lets say you have AWS Playground profile, and the ~/.aws/config has [profile playground] which further has something like,
[profile playground]
region=us-east-1
then, use something like below
aws ecs list-container-instances --cluster default --profile playground
You can take this trick to use only qplot. Use inner variable $mapping
. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.
cpu_metric2 <- qplot(y=Y2,x=X1)
cpu_metric1 <- qplot(y=Y1,
x=X1,
xlab="Time", ylab="%")
combined_cpu_plot <- cpu_metric1 +
geom_line() +
geom_point(mapping=cpu_metric2$mapping)+
geom_line(mapping=cpu_metric2$mapping)
The best solution is to use annotation GeneratedValue(strategy = ...)
, i.e.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column ...
private int OperationID;
it says, that this column is generated by database using IDENTITY strategy and you don't need to take care of - database will do it.
To force enable TLSv1.2 in JRE7u_80 I had to use following code snippet before creating JDBC connection.
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import javax.net.ssl.SSLContextSpi;
import sun.security.jca.GetInstance;
import sun.security.jca.ProviderList;
import sun.security.jca.Providers;
public static void enableTLSv12ForMssqlJdbc() throws NoSuchAlgorithmException
{
ProviderList providerList = Providers.getProviderList();
GetInstance.Instance instance = GetInstance.getInstance("SSLContext", SSLContextSpi.class, "TLS");
for (Provider provider : providerList.providers())
{
if (provider == instance.provider)
{
provider.put("Alg.Alias.SSLContext.TLS", "TLSv1.2");
}
}
}
Able to connect to Windows 10 with SQL server 2017 & TLSv1.2 enabled OS.
Sybase :
% : Matches any string of zero or more characters.
_ : Matches a single character.
[specifier] : Brackets enclose ranges or sets, such as [a-f]
or [abcdef].Specifier can take two forms:
rangespec1-rangespec2:
rangespec1 indicates the start of a range of characters.
- is a special character, indicating a range.
rangespec2 indicates the end of a range of characters.
set:
can be composed of any discrete set of values, in any
order, such as [a2bR].The range [a-f], and the
sets [abcdef] and [fcbdae] return the same
set of values.
Specifiers are case-sensitive.
[^specifier] : A caret (^) preceding a specifier indicates
non-inclusion. [^a-f] means "not in the range
a-f"; [^a2bR] means "not a, 2, b, or R."
You will have to assign both left
and right
property 0
value for margin: auto
to center the logo.
So in this case:
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left: 0;
right: 0;
margin: 0 auto;
}
You might also want to set position: relative
for #header
.
This works because, setting left
and right
to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin
is set to auto
. margin
takes up all the extra space(equally on each side) leaving the content to its specified width
. This results in content becoming center aligned.
var obj = $.parseJSON(result);
for (var prop in obj) {
alert(prop + " is " + obj[prop]);
}
There is also a change between Java 7 and Java 8. Admittedly it involves the a deprecated call, but I had to add a "/" to get our program working! Here is the link discussing it Why does servletContext.getRealPath returns null on tomcat 8?
The POSIX standard has its own method to get file size.
Include the sys/stat.h
header to use the function.
stat(3)
.st_size
property.Note: It limits the size to 4GB
. If not Fat32
filesystem then use the 64bit version!
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char** argv)
{
struct stat info;
stat(argv[1], &info);
// 'st' is an acronym of 'stat'
printf("%s: size=%ld\n", argv[1], info.st_size);
}
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char** argv)
{
struct stat64 info;
stat64(argv[1], &info);
// 'st' is an acronym of 'stat'
printf("%s: size=%ld\n", argv[1], info.st_size);
}
The ANSI C doesn't directly provides the way to determine the length of the file.
We'll have to use our mind. For now, we'll use the seek approach!
#include <stdio.h>
int main(int argc, char** argv)
{
FILE* fp = fopen(argv[1]);
int f_size;
fseek(fp, 0, SEEK_END);
f_size = ftell(fp);
rewind(fp); // to back to start again
printf("%s: size=%ld", (unsigned long)f_size);
}
If the file is
stdin
or a pipe. POSIX, ANSI C won't work.
It will going return0
if the file is a pipe orstdin
.Opinion: You should use POSIX standard instead. Because, it has 64bit support.
Timer is another way to do your work but be quiet sure to add runOnUiThread
if you are working with UI.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
CheckBox optSingleShot;
Button btnStart, btnCancel;
TextView textCounter;
Timer timer;
MyTimerTask myTimerTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
optSingleShot = (CheckBox)findViewById(R.id.singleshot);
btnStart = (Button)findViewById(R.id.start);
btnCancel = (Button)findViewById(R.id.cancel);
textCounter = (TextView)findViewById(R.id.counter);
btnStart.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 5000);
}
}});
btnCancel.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if (timer!=null){
timer.cancel();
timer = null;
}
}
});
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
runOnUiThread(new Runnable(){
@Override
public void run() {
textCounter.setText(strDate);
}});
}
}
}
and xml is...
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<CheckBox
android:id="@+id/singleshot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Single Shot"/>
Another Way to use CountDownTimer
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Schedule a countdown until a time in the future, with regular notifications on intervals along the way. Example of showing a 30 second countdown in a text field:
Watch out for case sensitivity. If you have a file
/Content/bootstrap.css
and you redirect in your Bundle.config to
.Include("~/Content/Bootstrap.css")
it will not load the css.
Just FYI, if you are using Java 11+, there is an exception to this rule: if you run your java file directly (without compilation). In this mode, there is no restriction on a single public class per file. However, the class with the main
method must be the first one in the file.
if you prefer a visual approach rather than coding it use this method:
in your info.plist
simply add View controller-based status bar appearance
to NO
and Status bar is initially hidden
as YES
You can accomplish this using the mysqldump command-line function.
For example:
If it's an entire DB, then:
$ mysqldump -u [uname] -p db_name > db_backup.sql
If it's all DBs, then:
$ mysqldump -u [uname] -p --all-databases > all_db_backup.sql
If it's specific tables within a DB, then:
$ mysqldump -u [uname] -p db_name table1 table2 > table_backup.sql
You can even go as far as auto-compressing the output using gzip (if your DB is very big):
$ mysqldump -u [uname] -p db_name | gzip > db_backup.sql.gz
If you want to do this remotely and you have the access to the server in question, then the following would work (presuming the MySQL server is on port 3306):
$ mysqldump -P 3306 -h [ip_address] -u [uname] -p db_name > db_backup.sql
It should drop the .sql
file in the folder you run the command-line from.
EDIT: Updated to avoid inclusion of passwords in CLI commands, use the -p
option without the password. It will prompt you for it and not record it.
Need to merge the properties in object. For Example,
const boxStyle = {
width : "50px",
height : "50px"
};
const redBackground = {
...boxStyle,
background: "red",
};
const blueBackground = {
...boxStyle,
background: "blue",
}
<div style={redBackground}></div>
<div style={blueBackground}></div>
The parseInt function has a "radix" parameter which defines the numeral system used on the conversion, so calling parseInt(jQuery('#something').css('margin-left'), 10);
returns the left margin as an Integer.
This is what JSizes use.
set max-height as you need:
.navbar-fixed-top
.navbar-collapse,
.navbar-fixed-bottom
.navbar-collapse {
max-height: 700px;
}
In a situation where you have this:
enum fruit {
apple,
orange,
grape,
banana,
// etc.
};
I like to put this in the header file where the enum is defined:
static inline char *stringFromFruit(enum fruit f)
{
static const char *strings[] = { "apple", "orange", "grape", "banana", /* continue for rest of values */ };
return strings[f];
}
On top of PoolingHttpClientConnectionManager
along with Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslFactory).build();
If you want an asynchronous httpclient using PoolingNHttpClientConnectionManager
the code shoudl be similar to following
SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
});
SSLContext sslContext = builder.build();
SchemeIOSessionStrategy sslioSessionStrategy = new SSLIOSessionStrategy(sslContext,
new HostnameVerifier(){
@Override
public boolean verify(String hostname, SSLSession session) {
return true;// TODO as of now allow all hostnames
}
});
Registry<SchemeIOSessionStrategy> sslioSessionRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create().register("https", sslioSessionStrategy).build();
PoolingNHttpClientConnectionManager ncm = new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor(),sslioSessionRegistry);
CloseableHttpAsyncClient asyncHttpClient = HttpAsyncClients.custom().setConnectionManager(ncm).build();
asyncHttpClient.start();
It seems that in VBA macro code for an ActiveX checkbox control you use
If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)
and for a Form checkbox control you use
If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
Where fadeTo parameters are fadeTo(speed, opacity)
I think this is a bit better :
/**
* draws the view's content to a bitmap. code initially based on :
* http://nadavfima.com/android-snippet-inflate-a-layout-draw-to-a-bitmap/
*/
@Nullable
public static Bitmap drawToBitmap(final View viewToDrawFrom, int width, int height) {
boolean wasDrawingCacheEnabled = viewToDrawFrom.isDrawingCacheEnabled();
if (!wasDrawingCacheEnabled)
viewToDrawFrom.setDrawingCacheEnabled(true);
if (width <= 0 || height <= 0) {
if (viewToDrawFrom.getWidth() <= 0 || viewToDrawFrom.getHeight() <= 0) {
viewToDrawFrom.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
width = viewToDrawFrom.getMeasuredWidth();
height = viewToDrawFrom.getMeasuredHeight();
}
if (width <= 0 || height <= 0) {
final Bitmap bmp = viewToDrawFrom.getDrawingCache();
final Bitmap result = bmp == null ? null : Bitmap.createBitmap(bmp);
if (!wasDrawingCacheEnabled)
viewToDrawFrom.setDrawingCacheEnabled(false);
return result;
}
viewToDrawFrom.layout(0, 0, width, height);
} else {
viewToDrawFrom.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
viewToDrawFrom.layout(0, 0, viewToDrawFrom.getMeasuredWidth(), viewToDrawFrom.getMeasuredHeight());
}
final Bitmap drawingCache = viewToDrawFrom.getDrawingCache();
final Bitmap bmp = ThumbnailUtils.extractThumbnail(drawingCache, width, height);
final Bitmap result = bmp == null || bmp != drawingCache ? bmp : Bitmap.createBitmap(bmp);
if (!wasDrawingCacheEnabled)
viewToDrawFrom.setDrawingCacheEnabled(false);
return result;
}
Using the above code, you don't have to specify the size of the bitmap (use 0 for width&height) if you want to use the one of the view itself.
Also, if you wish to convert special views (SurfaceView, Surface or Window, for example) to a bitmap, you should consider using PixelCopy class instead. It requires API 24 and above though. I don't know how to do it before.
Form nesting can be achieved with new HTML5 input element's form attribute. Although we don't nest forms structurally, inputs are evaluated as they are in their own form. In my tests, 3 major browsers support this except IE(IE11). Form nesting limitation was a big obstacle for HTML UI design.
Here is a sample code, when you click Save button you should see "2 3 success" (Original http://www.impressivewebs.com/html5-form-attribute/):
<form id="saveForm" action="/post/dispatch/save" method="post"></form>
<form id="deleteForm" action="/post/dispatch/delete" method="post"></form>
<div id="toolbar">
<input type="text" name="foo" form="saveForm" />
<input type="hidden" value="some_id" form="deleteForm" />
<input type="text" name="foo2" id="foo2" form="saveForm" value="success" />
<input type="submit" name="save" value="Save" form="saveForm" onclick="alert(document.getElementById('deleteForm').elements.length + ' ' + document.getElementById('saveForm').elements.length + ' ' + document.getElementById('saveForm').elements['foo2'].value);return false;" />
<input type="submit" name="delete" value="Delete" form="deleteForm" />
<a href="/home/index">Cancel</a>
</div>
i using FF 16.0.2 and jquery 1.8.3, all the code in the answer didn't work.
I use code like this and work.
$("input[type=text]").focus().select();
You need something like this: https://github.com/axkibe/lsyncd It is a tool which combines rsync and inotify - the former is a tool that mirrors, with the correct options set, a directory to the last bit. The latter tells the kernel to notify a program of changes to a directory ot file. It says:
It aggregates and combines events for a few seconds and then spawns one (or more) process(es) to synchronize the changes.
But - according to Digital Ocean at https://www.digitalocean.com/community/tutorials/how-to-mirror-local-and-remote-directories-on-a-vps-with-lsyncd - it ought to be in the Ubuntu repository!
I have similar requirements, and this tool, which I have yet to try, seems suitable for the task.
Well,
The container div is very good to have, because if You want the site centered, You just can't do it just with body or html... But You can, with divs. Why container? Its usually used, just because the code itselve has to be clean and readable. So that is container... It contains all website, in case You want to mess with it around :)
Good luck
An easier way would be to inline the transparent background image using Data URIs as follows:
.click-through {
pointer-events: none;
background: url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7);
}
As a noobie I was confused by this until I realized that the so called "path" is the path relative to the MyClass.class file in the file system and not the MyClass.java file. My IDE copies the resources (like xx.jpg, xx.xml) to a directory local to the MyClass.class. For example, inside a pkg directory called "target/classes/pkg. The class-file location may be different for different IDE's and depending on how the build is structured for your application. You should first explore the file system and find the location of the MyClass.class file and the copied location of the associated resource you are seeking to extract. Then determine the path relative to the MyClass.class file and write that as a string value with "dots" and "slashes".
For example, here is how I make an app1.fxml file available to my javafx application where the relevant "MyClass.class" is implicitly "Main.class". The Main.java file is where this line of resource-calling code is contained. In my specific case the resources are copied to a location at the same level as the enclosing package folder. That is: /target/classes/pkg/Main.class and /target/classes/app1.fxml. So paraphrasing...the relative reference "../app1.fxml" is "start from Main.class, go up one directory level, now you can see the resource".
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("../app1.fxml"));
Note that in this relative-path string "../app1.fxml", the first two dots reference the directory enclosing Main.class and the single "." indicates a file extension to follow. After these details become second nature, you will forget why it was confusing.
Many answers here describe dangerous methods where they instantiate a file input stream but do not get a reference to the input stream in order to close the stream later. This results in dangling input streams and memory leaks. The correct way of loading the properties should be similar to following:
Properties prop = new Properties();
try(InputStream fis = new FileInputStream("myProp.properties")) {
prop.load(fis);
}
catch(Exception e) {
System.out.println("Unable to find the specified properties file");
e.printStackTrace();
return;
}
Note the instantiating of the file input stream in try-with-resources
block. Since a FileInputStream
is autocloseable, it will be automatically closed after the try-with-resources
block is exited. If you want to use a simple try
block, you must explicitly close it using fis.close();
in the finally
block.
List<List> list = map.values().stream().collect(Collectors.toList());
List<Employee> employees2 = new ArrayList<>();
list.stream().forEach(
n-> employees2.addAll(n));
Loading an excel file without explicitly naming a sheet but instead giving the number of the sheet order (often one will simply load the first sheet) goes like:
import pandas as pd
myexcel = pd.ExcelFile("C:/filename.xlsx")
myexcel = myexcel.parse(myexcel.sheet_names[0])
Since .sheet_names
returns a list of sheet names, it is easy to load one or more sheets by simply calling the list element(s).
Don't forget the awesome scitech .net memory profiler
It's great for tracking down why your .net app is running out of memory.
replaceAll(search, replaceWith)
[MDN]
".a.b.c.".replaceAll('.', ' ')
// result: " a b c "
// Using RegEx. You MUST use a global RegEx.
".a.b.c.".replaceAll(/\./g, ' ')
// result: " a b c "
replaceAll()
replaces ALL occurrences of search
with replaceWith
.
It's actually the same as using replace()
[MDN] with a global regex(*), merely replaceAll()
is a bit more readable in my view.
(*) Meaning it'll match all occurrences.
Important(!) if you choose regex:
when using a
regexp
you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".
step1.
git init
step2.
a) for all files
git add -a
b) only specific folder
git add <folder1> <folder2> <etc.>
step3.
git commit -m "Your message about the commit"
step4.
git remote add origin https://github.com/yourUsername/yourRepository.git
step5.
git push -u origin master
git push origin master
if you are face this error than
! [rejected] master -> master (fetch first)
error: failed to push some refs to 'https://github.com/harishkumawat2610/Qt5-with-C-plus-plus.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
Use this command
git push --force origin master
To update a little bit Brian's answer, there is now a nice backport of inspect.signature
that you can use in older python versions: funcsigs
.
So my personal preference would go for
try: # python 3.3+
from inspect import signature
except ImportError:
from funcsigs import signature
def aMethod(arg1, arg2):
pass
sig = signature(aMethod)
print(sig)
For fun, if you're interested in playing with Signature
objects and even creating functions with random signatures dynamically you can have a look at my makefun
project.
Use @RequestParam
@RequestMapping(value="user", method = RequestMethod.GET)
public @ResponseBody Item getItem(@RequestParam("data") String itemid){
Item i = itemDao.findOne(itemid);
String itemName = i.getItemName();
String price = i.getPrice();
return i;
}
You can chain class selectors without a space between them:
.a.b {
color: #666;
}
Note that, if it matters to you, IE6 treats .a.b
as .b
, so in that browser both div.a.b
and div.b
will have gray text. See this answer for a comparison between proper browsers and IE6.
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
You can use the redirect URL to controller:
Class Ctrlr1 extends CI_Controller{
public void my_fct1(){
redirect('Ctrlr2 /my_fct2', 'refresh');
}
}
Class Ctrlr2 extends CI_Controller{
public void my_fct2(){
$this->load->view('view1');
}
}
Just pressing F5 is not always working.
why?
Because your ISP is also caching web data for you.
Solution: Force Refresh.
Force refresh your browser by pressing CTRL + F5 in Firefox or Chrome to clear ISP cache too, instead of just pressing F5
You then can see 200 response instead of 304 in the browser F12 developer tools network tab.
Another trick is to add question mark ?
at the end of the URL string of the requested page:
http://localhost:52199/Customers/Create?
The question mark will ensure that the browser refresh the request without caching any previous requests.
Additionally in Visual Studio you can set the default browser to Chrome in Incognito mode to avoid cache issues while developing, by adding Chrome in Incognito mode as default browser, see the steps (self illustrated):
I would like to add that there is a Parallel class with ForEach function built in that can be used for this purpose.
Pure JavaScript version:
document.querySelector('input[name="myradio"][value="5"]').checked = true;
For anyone stumbling across this question that is not on a Mac: assuming you know that your server is running on port 3000, you can do this in one shot by executing the following:
fuser -k 3000/tcp
But as Toby has mentioned, the implementation of fuser in Mac OS is rather primitive and this command will not work on mac.
This should be fine:
const char* bool_cast(const bool b) {
return b ? "true" : "false";
}
But, if you want to do it more C++-ish:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string bool_cast(const bool b) {
ostringstream ss;
ss << boolalpha << b;
return ss.str();
}
int main() {
cout << bool_cast(true) << "\n";
cout << bool_cast(false) << "\n";
}
Try this,
IFS=''
while read line
do
echo $line
done < file.txt
EDIT:
From man bash
IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with the read builtin command. The default value is
``<space><tab><newline>''
First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:
raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it
freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level
Then you need to create a data frame out of it, melt it and plot it:
Names=c("Food","Music","People") # create list of names
data=data.frame(cbind(freq),Names) # combine them into a data frame
data=data[,c(5,3,1,2,4)] # sort columns
# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')
# plot everything
ggplot(data.m, aes(Names, value)) +
geom_bar(aes(fill = variable), position = "dodge", stat="identity")
Is this what you're after?
To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:
> head(df)
ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1 1 A 1980 450 338 154 36 13 9
2 2 A 2000 288 407 212 54 16 23
3 3 A 2020 196 434 246 68 19 36
4 4 B 1980 111 326 441 90 21 11
5 5 B 2000 63 298 443 133 42 21
6 6 B 2020 36 257 462 162 55 30
Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape
and plotted.
For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw))
to get this:
> data
Names Very.Bad Bad Good Very.Good
1 Food 7 6 5 2
2 Music 5 5 7 3
3 People 6 3 7 4
Just imagine you have Very.Bad
, Bad
, Good
and so on instead of X1PCE
, X2PCE
, X3PCE
. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw))
.
Here is a quick start to get the gears turning...
ParkingLot is a class.
ParkingSpace is a class.
ParkingSpace has an Entrance.
Entrance has a location or more specifically, distance from Entrance.
ParkingLotSign is a class.
ParkingLot has a ParkingLotSign.
ParkingLot has a finite number of ParkingSpaces.
HandicappedParkingSpace is a subclass of ParkingSpace.
RegularParkingSpace is a subclass of ParkingSpace.
CompactParkingSpace is a subclass of ParkingSpace.
ParkingLot keeps array of ParkingSpaces, and a separate array of vacant ParkingSpaces in order of distance from its Entrance.
ParkingLotSign can be told to display "full", or "empty", or "blank/normal/partially occupied" by calling .Full(), .Empty() or .Normal()
Parker is a class.
Parker can Park().
Parker can Unpark().
Valet is a subclass of Parker that can call ParkingLot.FindVacantSpaceNearestEntrance(), which returns a ParkingSpace.
Parker has a ParkingSpace.
Parker can call ParkingSpace.Take() and ParkingSpace.Vacate().
Parker calls Entrance.Entering() and Entrance.Exiting() and ParkingSpace notifies ParkingLot when it is taken or vacated so that ParkingLot can determine if it is full or not. If it is newly full or newly empty or newly not full or empty, it should change the ParkingLotSign.Full() or ParkingLotSign.Empty() or ParkingLotSign.Normal().
HandicappedParker could be a subclass of Parker and CompactParker a subclass of Parker and RegularParker a subclass of Parker. (might be overkill, actually.)
In this solution, it is possible that Parker should be renamed to be Car.
Instagram deprecated their legacy APIs in support for Basic Display API during the late 2019
In Basic Display API you are supposed to use the following API endpoint to get the media id. You will need to supply a valid access token.
https://graph.instagram.com/me/media?fields=id,caption&access_token={access-token}
You can read here on how to configure test account and generate access token on Facebook developer portal.
Here is another article which also describes about how to get access token.
In case others may find this useful: I found that by adding an initial empty cell to my list of search terms, a zero value will be returned instead of error.
={INDEX(SearchTerms!$A$1:$A$38,MAX(IF(ISERROR(SEARCH(SearchTerms!$A$1:$A$38,SearchCell)),0,1)*((SearchTerms!$B$1:$B$38)+1)))}
NB: Column A has the search terms, B is the row number index.
From "Equivalent of Bash Backticks in Python", which I asked a long time ago, what you may want to use is popen
:
os.popen('cat /etc/services').read()
From the docs for Python 3.6,
This is implemented using subprocess.Popen; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.
Here's the corresponding code for subprocess
:
import subprocess
proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out
XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
Console.WriteLine(n[0].InnerText); //Will output '08:29:57'
}
or you could wrap in foreach loop to print each value
XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
foreach(XmlNode curr in n) {
Console.WriteLine(curr.InnerText);
}
}
UPDATE table1
SET
`ID` = (SELECT table2.id FROM table2 WHERE table1.`name`=table2.`name`)
.dmp files are dumps of oracle databases created with the "exp" command. You can import them using the "imp" command.
If you have an oracle client intalled on your machine, you can executed the command
imp help=y
to find out how it works. What will definitely help is knowing from wich schema the data was exported and what the oracle version was.
Scipt above can be written in one line:
find /tmp -name "*.txt" -exec bash -c 'mv $0 $(echo "$0" | sed -r \"s|.txt|.cpp|g\")' '{}' \;
This worked for me:
$('.class1[class~="class2"]').append('something');
You can copy an object to your clip board using copy(JSON.stringify(Object_Name)); in the console.
Eg:- Copy & Paste the below code in your console and press ENTER. Now, try to paste(CTRL+V for Windows or CMD+V for mac) it some where else and you will get {"name":"Daniel","age":25}
var profile = {
name: "Daniel",
age: 25
};
copy(JSON.stringify(profile));
Very simple, you create an array containing zeros using the reference shape:
result = np.zeros(b.shape)
# actually you can also use result = np.zeros_like(b)
# but that also copies the dtype not only the shape
and then insert the array where you need it:
result[:a.shape[0],:a.shape[1]] = a
and voila you have padded it:
print(result)
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
You can also make it a bit more general if you define where your upper left element should be inserted
result = np.zeros_like(b)
x_offset = 1 # 0 would be what you wanted
y_offset = 1 # 0 in your case
result[x_offset:a.shape[0]+x_offset,y_offset:a.shape[1]+y_offset] = a
result
array([[ 0., 0., 0., 0., 0., 0.],
[ 0., 1., 1., 1., 1., 1.],
[ 0., 1., 1., 1., 1., 1.],
[ 0., 1., 1., 1., 1., 1.]])
but then be careful that you don't have offsets bigger than allowed. For x_offset = 2
for example this will fail.
If you have an arbitary number of dimensions you can define a list of slices to insert the original array. I've found it interesting to play around a bit and created a padding function that can pad (with offset) an arbitary shaped array as long as the array and reference have the same number of dimensions and the offsets are not too big.
def pad(array, reference, offsets):
"""
array: Array to be padded
reference: Reference array with the desired shape
offsets: list of offsets (number of elements must be equal to the dimension of the array)
"""
# Create an array of zeros with the reference shape
result = np.zeros(reference.shape)
# Create a list of slices from offset to offset + shape in each dimension
insertHere = [slice(offset[dim], offset[dim] + array.shape[dim]) for dim in range(a.ndim)]
# Insert the array in the result at the specified offsets
result[insertHere] = a
return result
And some test cases:
import numpy as np
# 1 Dimension
a = np.ones(2)
b = np.ones(5)
offset = [3]
pad(a, b, offset)
# 3 Dimensions
a = np.ones((3,3,3))
b = np.ones((5,4,3))
offset = [1,0,0]
pad(a, b, offset)
I've got a similar error when installing FCL that needs CCD lib(libccd) like this:
/usr/bin/ld: /usr/local/lib/libccd.a(ccd.o): relocation R_X86_64_32S against `a local symbol' can not be used when making a shared object; recompile with -fPIC
I find that there is two different files named "libccd.a" :
I solved the problem by removing the first file.
A cross join produces a cartesian product between the two tables, returning all possible combinations of all rows. It has no on
clause because you're just joining everything to everything.
A full outer join
is a combination of a left outer
and right outer
join. It returns all rows in both tables that match the query's where
clause, and in cases where the on
condition can't be satisfied for those rows it puts null
values in for the unpopulated fields.
This wikipedia article explains the various types of joins with examples of output given a sample set of tables.
In SQL Server 2005+ with Full-Text indexing switched on, I'd do the following:
SELECT *
FROM T
WHERE CONTAINS(C, '"David" OR "Robi" OR "Moses"');
If you wanted your search to bring back results where the result is prefixed with David, Robi or Moses you could do:
SELECT *
FROM T
WHERE CONTAINS(C, '"David*" OR "Robi*" OR "Moses*"');
The code returns the nth occurrence positions substring aka field width. Example. if string "Stack overflow in low melow" is the string to search 2nd occurance of token "low", you will agree with me that it 2nd occurance is at subtring "18 and 21". indexOfOccurance("Stack overflow in low melow", low, 2) returns 18 and 21 in a string.
class Example{
public Example(){
}
public String indexOfOccurance(String string, String token, int nthOccurance) {
int lengthOfToken = token.length();
int nthCount = 0;
for (int shift = 0,count = 0; count < string.length() - token.length() + 2; count++, shift++, lengthOfToken++)
if (string.substring(shift, lengthOfToken).equalsIgnoreCase(token)) {
// keeps count of nthOccurance
nthCount++;
if (nthCount == nthOccurance){
//checks if nthCount == nthOccurance. If true, then breaks
return String.valueOf(shift)+ " " +String.valueOf(lengthOfToken);
}
}
return "-1";
}
public static void main(String args[]){
Example example = new Example();
String string = "the man, the woman and the child";
int nthPositionOfThe = 3;
System.out.println("3rd Occurance of the is at " + example.indexOfOccurance(string, "the", nthPositionOfThe));
}
}
Note that if you want to comment out a single line of printing erb you should do like this
<%#= ["Buck", "Papandreou"].join(" you ") %>
best way is to create an accessor like this:
/**
* @var object $db : map to database connection.
*/
public static $db= null;
/**
* db Function for initializing variable.
* @return object
*/
public static function db(){
if( !isset(static::$db) ){
static::$db= new \Helpers\MySQL( array(
"hostname"=> "localhost",
"username"=> "root",
"password"=> "password",
"database"=> "db_name"
)
);
}
return static::$db;
}
then you can do static::db(); or self::db(); from anywhere.
In your phone go to Settings->Connect
to PC.
There you will see the option Default Connection Type
. Select it and set it to your preference.
If you're using SQLAlchemy, you don't need to mess with hand-crafting the string because SQLAlchemy supports generating a multi-row VALUES
clause for a single INSERT
statement:
rows = []
for i, name in enumerate(rawdata):
row = {
'id': i,
'name': name,
'valid': True,
}
rows.append(row)
if len(rows) > 0: # INSERT fails if no rows
insert_query = SQLAlchemyModelName.__table__.insert().values(rows)
session.execute(insert_query)
Try using ctrl + c twice to get the prompt for terminating the batch job.
I found this approach simple and useful: How to "merge" specific files from another branch
As it turns out, we’re trying too hard. Our good friend git checkout is the right tool for the job.
git checkout source_branch <paths>...
We can simply give git checkout the name of the feature branch A and the paths to the specific files that we want to add to our master branch.
Please read the whole article for more understanding
Either run in SQL:
ALTER TABLE tableName
ADD PRIMARY KEY (id) ---or Drugid, whichever you want it to be PK
or use the PHPMyAdmin interface (Table Structure)
By referring this(http://www.excelforum.com/excel-programming-vba-macros/867665-application-cutcopymode-false.html) link the answer is as below:
Application.CutCopyMode=False
is seen in macro recorder-generated code when you do a copy/cut cells and paste . The macro recorder does the copy/cut and paste in separate statements and uses the clipboard as an intermediate buffer. I think Application.CutCopyMode = False
clears the clipboard. Without that line you will get the warning 'There is a large amount of information on the Clipboard....'
when you close the workbook with a large amount of data on the clipboard.
With optimised VBA code you can usually do the copy/cut and paste operations in one statement, so the clipboard isn't used and Application.CutCopyMode = False
isn't needed and you won't get the warning.
Since version 49+, Chrome has supported styling <option>
elements with font-weight
. Source: https://code.google.com/p/chromium/issues/detail?id=44917#c22
New SELECT Popup: font-weight style should be applied.
This CL removes themeChromiumSkia.css.
|!important|
in it prevented to applyfont-weight
. Now html.css has|font-weight:normal|
, and|!important|
should be unnecessary.
There was a Chrome stylesheet, themeChromiumSkia.css, that used font-weight: normal !important;
in it all this time. It was introduced to the stable Chrome channel in version 49.0.
It means you're trying to install an app with the same packageName as an app that's already installed on the emulator, but the one you're trying to install has a lower versionCode (integer value for your version number).
You might have installed from a separate copy of the code where the version number was higher than the copy you're working with right now. In either case, either:
uninstall the currently installed copy
or open up your phone's Settings > Application Manager to determine the version number for the installed app, and increment your <manifest android:versionCode
to be higher in the AndroidManifest.
You could use for()
with assign()
to create many objects.
See the example from assign()
:
for(i in 1:6) { #-- Create objects 'r.1', 'r.2', ... 'r.6' --
nam <- paste("r", i, sep = ".")
assign(nam, 1:i)
Looking the new objects
ls(pattern = "^r..$")
I am using in the way and it is working for me.
public static void main(String[] args) {
new CarpoolDBAppTest();
}
public CarpoolDBAppTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
Student stud = (Student) context.getBean("yourBeanId");
}
Here Student is my classm you will get the class matching yourBeanId.
Now work on that object with whatever operation you want to do.
This is an improvement over the accepted answer.
Changes:
(1) Using random IV and prepend it to the encrypted text
(2) Using SHA-256 to generate a key from a passphrase
(3) No dependency on Apache Commons
public static void main(String[] args) throws GeneralSecurityException {
String plaintext = "Hello world";
String passphrase = "My passphrase";
String encrypted = encrypt(passphrase, plaintext);
String decrypted = decrypt(passphrase, encrypted);
System.out.println(encrypted);
System.out.println(decrypted);
}
private static SecretKeySpec getKeySpec(String passphrase) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return new SecretKeySpec(digest.digest(passphrase.getBytes(UTF_8)), "AES");
}
private static Cipher getCipher() throws NoSuchPaddingException, NoSuchAlgorithmException {
return Cipher.getInstance("AES/CBC/PKCS5PADDING");
}
public static String encrypt(String passphrase, String value) throws GeneralSecurityException {
byte[] initVector = new byte[16];
SecureRandom.getInstanceStrong().nextBytes(initVector);
Cipher cipher = getCipher();
cipher.init(Cipher.ENCRYPT_MODE, getKeySpec(passphrase), new IvParameterSpec(initVector));
byte[] encrypted = cipher.doFinal(value.getBytes());
return DatatypeConverter.printBase64Binary(initVector) +
DatatypeConverter.printBase64Binary(encrypted);
}
public static String decrypt(String passphrase, String encrypted) throws GeneralSecurityException {
byte[] initVector = DatatypeConverter.parseBase64Binary(encrypted.substring(0, 24));
Cipher cipher = getCipher();
cipher.init(Cipher.DECRYPT_MODE, getKeySpec(passphrase), new IvParameterSpec(initVector));
byte[] original = cipher.doFinal(DatatypeConverter.parseBase64Binary(encrypted.substring(24)));
return new String(original);
}
everyone has answered excellently using the date, let me try to answer it using pandas
dt = pd.to_datetime('2008/08/18', format='%Y/%m/%d')
dt1 = pd.to_datetime('2008/09/26', format='%Y/%m/%d')
(dt1-dt).days
This will give the answer. In case one of the input is dataframe column. simply use dt.days in place of days
(dt1-dt).dt.days
def matrixmult (A, B):
C = [[0 for row in range(len(A))] for col in range(len(B[0]))]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j] += A[i][k]*B[k][j]
return C
at second line you should change
C = [[0 for row in range(len(B[0]))] for col in range(len(A))]
I deleted file inside svn.simple
directory at below path on windows machine (Windows 7):
C:\Users\[user_name]\AppData\Roaming\Subversion\auth
Problem solved.
If the properties are for XML or HTML, it's safest to use XML entities. They're uglier to read, but it means that the properties file can be treated as straight ASCII, so nothing will get mangled.
Note that HTML has entities that XML doesn't, so I keep it safe by using straight XML: http://www.w3.org/TR/html4/sgml/entities.html
This may become useful to someone in the future as the new framework, when setup through VS, gets a default web.config
, web.Debug.config
and web.Release.config
. In the web.release.config
you will find this line:
<compilation xdt:Transform="RemoveAttributes(debug)" />
this was seeming to override any inline changes I made. I commented this line out and we were gravy (in terms of seeing non-minified code in a "release" build)
Get input1 data to send them to input2 immediately
<div>
<label>Input1</label>
<input type="text" id="input1" value="">
</div>
</br>
<label>Input2</label>
<input type="text" id="input2" value="">
<script type="text/javascript">
$(document).ready(function () {
$("#input1").keyup(function () {
var value = $(this).val();
$("#input2").val(value);
});
});
</script>
Leaving out the parenthesis and simply calling 'setParameter' now works with at least Hibernate.
String jpql = "from A where name in :names";
Query q = em.createQuery(jpql);
q.setParameter("names", l);
public class ApiClient {
private static Retrofit retrofit = null;
private static final Object LOCK = new Object();
public static void clear() {
synchronized (LOCK) {
retrofit = null;
}
}
public static Retrofit getClient() {
synchronized (LOCK) {
if (retrofit == null) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(40, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
// Log.e("jjj", "=" + (MySharedPreference.getmInstance().isEnglish() ? Constant.WEB_SERVICE : Constant.WEB_SERVICE_ARABIC));
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl(Constants.WEB_SERVICE)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}`enter code here`
}
public static RequestBody plain(String content) {
return getRequestBody("text/plain", content);
}
public static RequestBody getRequestBody(String type, String content) {
return RequestBody.create(MediaType.parse(type), content);
}
}
-------------------------------------------------------------------------
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
WHERE column_name LIKE '%save 50[%] off!%'
I would suggest reading PEP 483 and PEP 484 and watching this presentation by Guido on type hinting.
In a nutshell: Type hinting is literally what the words mean. You hint the type of the object(s) you're using.
Due to the dynamic nature of Python, inferring or checking the type of an object being used is especially hard. This fact makes it hard for developers to understand what exactly is going on in code they haven't written and, most importantly, for type checking tools found in many IDEs (PyCharm and PyDev come to mind) that are limited due to the fact that they don't have any indicator of what type the objects are. As a result they resort to trying to infer the type with (as mentioned in the presentation) around 50% success rate.
To take two important slides from the type hinting presentation:
TypeErrors
..
and having methods/attributes pop up which aren't defined for an object.As a closing note for this small introduction: This is an optional feature and, from what I understand, it has been introduced in order to reap some of the benefits of static typing.
You generally do not need to worry about it and definitely don't need to use it (especially in cases where you use Python as an auxiliary scripting language). It should be helpful when developing large projects as it offers much needed robustness, control and additional debugging capabilities.
In order to make this answer more complete, I think a little demonstration would be suitable. I'll be using mypy
, the library which inspired Type Hints as they are presented in the PEP. This is mainly written for anybody bumping into this question and wondering where to begin.
Before I do that let me reiterate the following: PEP 484 doesn't enforce anything; it is simply setting a direction for function annotations and proposing guidelines for how type checking can/should be performed. You can annotate your functions and hint as many things as you want; your scripts will still run regardless of the presence of annotations because Python itself doesn't use them.
Anyways, as noted in the PEP, hinting types should generally take three forms:
# type: type
comments that complement the first two forms. (See: What are variable annotations? for a Python 3.6 update for # type: type
comments)Additionally, you'll want to use type hints in conjunction with the new typing
module introduced in Py3.5
. In it, many (additional) ABCs (abstract base classes) are defined along with helper functions and decorators for use in static checking. Most ABCs in collections.abc
are included, but in a generic form in order to allow subscription (by defining a __getitem__()
method).
For anyone interested in a more in-depth explanation of these, the mypy documentation
is written very nicely and has a lot of code samples demonstrating/describing the functionality of their checker; it is definitely worth a read.
First, it's interesting to observe some of the behavior we can get when using special comments. Special # type: type
comments
can be added during variable assignments to indicate the type of an object if one cannot be directly inferred. Simple assignments are
generally easily inferred but others, like lists (with regard to their contents), cannot.
Note: If we want to use any derivative of containers and need to specify the contents for that container we must use the generic types from the typing
module. These support indexing.
# Generic List, supports indexing.
from typing import List
# In this case, the type is easily inferred as type: int.
i = 0
# Even though the type can be inferred as of type list
# there is no way to know the contents of this list.
# By using type: List[str] we indicate we want to use a list of strings.
a = [] # type: List[str]
# Appending an int to our list
# is statically not correct.
a.append(i)
# Appending a string is fine.
a.append("i")
print(a) # [0, 'i']
If we add these commands to a file and execute them with our interpreter, everything works just fine and print(a)
just prints
the contents of list a
. The # type
comments have been discarded, treated as plain comments which have no additional semantic meaning.
By running this with mypy
, on the other hand, we get the following response:
(Python3)jimmi@jim: mypy typeHintsCode.py
typesInline.py:14: error: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"
Indicating that a list of str
objects cannot contain an int
, which, statically speaking, is sound. This can be fixed by either abiding to the type of a
and only appending str
objects or by changing the type of the contents of a
to indicate that any value is acceptable (Intuitively performed with List[Any]
after Any
has been imported from typing
).
Function annotations are added in the form param_name : type
after each parameter in your function signature and a return type is specified using the -> type
notation before the ending function colon; all annotations are stored in the __annotations__
attribute for that function in a handy dictionary form. Using a trivial example (which doesn't require extra types from the typing
module):
def annotated(x: int, y: str) -> bool:
return x < y
The annotated.__annotations__
attribute now has the following values:
{'y': <class 'str'>, 'return': <class 'bool'>, 'x': <class 'int'>}
If we're a complete newbie, or we are familiar with Python 2.7 concepts and are consequently unaware of the TypeError
lurking in the comparison of annotated
, we can perform another static check, catch the error and save us some trouble:
(Python3)jimmi@jim: mypy typeHintsCode.py
typeFunction.py: note: In function "annotated":
typeFunction.py:2: error: Unsupported operand types for > ("str" and "int")
Among other things, calling the function with invalid arguments will also get caught:
annotated(20, 20)
# mypy complains:
typeHintsCode.py:4: error: Argument 2 to "annotated" has incompatible type "int"; expected "str"
These can be extended to basically any use case and the errors caught extend further than basic calls and operations. The types you
can check for are really flexible and I have merely given a small sneak peak of its potential. A look in the typing
module, the
PEPs or the mypy
documentation will give you a more comprehensive idea of the capabilities offered.
Stub files can be used in two different non mutually exclusive cases:
What stub files (with an extension of .pyi
) are is an annotated interface of the module you are making/want to use. They contain
the signatures of the functions you want to type-check with the body of the functions discarded. To get a feel of this, given a set
of three random functions in a module named randfunc.py
:
def message(s):
print(s)
def alterContents(myIterable):
return [i for i in myIterable if i % 2 == 0]
def combine(messageFunc, itFunc):
messageFunc("Printing the Iterable")
a = alterContents(range(1, 20))
return set(a)
We can create a stub file randfunc.pyi
, in which we can place some restrictions if we wish to do so. The downside is that
somebody viewing the source without the stub won't really get that annotation assistance when trying to understand what is supposed
to be passed where.
Anyway, the structure of a stub file is pretty simplistic: Add all function definitions with empty bodies (pass
filled) and
supply the annotations based on your requirements. Here, let's assume we only want to work with int
types for our Containers.
# Stub for randfucn.py
from typing import Iterable, List, Set, Callable
def message(s: str) -> None: pass
def alterContents(myIterable: Iterable[int])-> List[int]: pass
def combine(
messageFunc: Callable[[str], Any],
itFunc: Callable[[Iterable[int]], List[int]]
)-> Set[int]: pass
The combine
function gives an indication of why you might want to use annotations in a different file, they some times clutter up
the code and reduce readability (big no-no for Python). You could of course use type aliases but that sometime confuses more than it
helps (so use them wisely).
This should get you familiarized with the basic concepts of type hints in Python. Even though the type checker used has been
mypy
you should gradually start to see more of them pop-up, some internally in IDEs (PyCharm,) and others as standard Python modules.
I'll try and add additional checkers/related packages in the following list when and if I find them (or if suggested).
Checkers I know of:
Related Packages/Projects:
The typeshed
project is actually one of the best places you can look to see how type hinting might be used in a project of your own. Let's take as an example the __init__
dunders of the Counter
class in the corresponding .pyi
file:
class Counter(Dict[_T, int], Generic[_T]):
@overload
def __init__(self) -> None: ...
@overload
def __init__(self, Mapping: Mapping[_T, int]) -> None: ...
@overload
def __init__(self, iterable: Iterable[_T]) -> None: ...
Where _T = TypeVar('_T')
is used to define generic classes. For the Counter
class we can see that it can either take no arguments in its initializer, get a single Mapping
from any type to an int
or take an Iterable
of any type.
Notice: One thing I forgot to mention was that the typing
module has been introduced on a provisional basis. From PEP 411:
A provisional package may have its API modified prior to "graduating" into a "stable" state. On one hand, this state provides the package with the benefits of being formally part of the Python distribution. On the other hand, the core development team explicitly states that no promises are made with regards to the the stability of the package's API, which may change for the next release. While it is considered an unlikely outcome, such packages may even be removed from the standard library without a deprecation period if the concerns regarding their API or maintenance prove well-founded.
So take things here with a pinch of salt; I'm doubtful it will be removed or altered in significant ways, but one can never know.
** Another topic altogether, but valid in the scope of type-hints: PEP 526
: Syntax for Variable Annotations is an effort to replace # type
comments by introducing new syntax which allows users to annotate the type of variables in simple varname: type
statements.
See What are variable annotations?, as previously mentioned, for a small introduction to these.
Look this:
List<Client> result = clients
.stream()
.filter(c ->
(users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
.collect(Collectors.toList());
This is not possible. I tried to do so, too. I could figure out the package name and the activity which will be started. But in the end you will get a security exception because of a missing permission you can't declare.
UPDATE:
Regarding the other answer I also recommend to open the App settings screen. I do this with the following code:
public static void startInstalledAppDetailsActivity(final Activity context) {
if (context == null) {
return;
}
final Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + context.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);
}
As I don't want to have this in my history stack I remove it using intent flags.
From the javadoc:
The serialization runtime associates with each serializable class a version number, called a
serialVersionUID
, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a differentserialVersionUID
than that of the corresponding sender's class, then deserialization will result in anInvalidClassException
. A serializable class can declare its ownserialVersionUID
explicitly by declaring a field named"serialVersionUID"
that must be static, final, and of type long:
You can configure your IDE to:
As per your additional question "Can it be that the discussed warning message is a reason why my GUI application freeze?":
No, it can't be. It can cause a problem only if you are serializing objects and deserializing them in a different place (or time) where (when) the class has changed, and it will not result in freezing, but in InvalidClassException
.
I would check them one-by-one; i.e. look for a number \d+
, then if that fails you can tell the user they need to add a digit. This avoids returning an "Invalid" error without hinting to the user whats wrong with it.
I am sure the following code will help you to get ip address.
<script type="application/javascript">
function getip(json){
alert(json.ip); // alerts the ip address
}
</script>
<script type="application/javascript" src="http://www.telize.com/jsonip?callback=getip"></script>
GOOGLEFINANCE can have a 20 minutes delay, so refreshing every minute would not really help.
Instead of GOOGLEFINANCE you can use different source. I'm using this RealTime stock prices(I tried a couple but this is the easiest by-far to implement. They have API that retuen JSON { Name: CurrentPrice }
Here's a little script you can use in Google Sheets(Tools->Script Editor)
function GetStocksPrice() {
var url = 'https://financialmodelingprep.com/api/v3/stock/real-time-
price/AVP,BAC,CHK,CY,GE,GPRO,HIMX,IMGN,MFG,NIO,NMR,SSSS,UCTT,UMC,ZNGA';
var response = UrlFetchApp.fetch(url);
// convert json string to json object
var jsonSignal = JSON.parse(response);
// define an array of all the object keys
var headerRow = Object.keys(jsonSignal);
// define an array of all the object values
var values = headerRow.map(function(key){ return jsonSignal[key]});
var data = values[0];
// get sheet by ID -
// you can get the sheet unqiue ID from the your current sheet url
var jsonSheet = SpreadsheetApp.openById("Your Sheet UniqueID");
//var name = jsonSheet.getName();
var sheet = jsonSheet.getSheetByName('Sheet1');
// the column to put the data in -> Y
var letter = "F";
// start from line
var index = 4;
data.forEach(function( row, index2 ) {
var keys = Object.keys(row);
var value2 = row[keys[1]];
// set value loction
var cellXY = letter + index;
sheet.getRange(cellXY).setValue(value2);
index = index + 1;
});
}
Now you need to add a trigger that will execute every minute.
And your set :)
Also as important is to make sure that, your database name matches the data base name in the backup you are trying to restore. If it does not match, you will get the same error.
That's not a good solution because you're relying on exceptions for control flow. In your solution it's normal to get exceptions, it's normal to have them in the log.
public String test() {
String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
List<String> certs = jdbc.queryForList(sql, String.class);
if (certs.isEmpty()) {
return null;
} else {
return certs.get(0);
}
}
This is what I used.
$('#foo').popover({
placement : 'bottom',
title : 'Title',
content : '<div id="popOverBox"><img src="http://i.telegraph.co.uk/multimedia/archive/01515/alGore_1515233c.jpg" /></div>'
});
and for the HTML
<b id="foo" rel="popover">text goes here</b>
If you want to make address directly, the worksheet must exist.
Turning off automatic recalculation want help you :)
But... you can get value indirectly...
.FormulaR1C1 = "=INDIRECT(ADDRESS(2,7,1,0,""" & strProjectName & """),FALSE)"
At the time formula is inserted it will return #REF error, because strProjectName sheet does not exist.
But after this worksheet appear Excel will calculate formula again and proper value will be shown.
Disadvantage: there will be no tracking, so if you move the cell or change worksheet name, the formula will not adjust to the changes as in the direct addressing.
SELECT
CASE
WHEN course_enrollment_settings.base_price = 0 THEN 1
WHEN course_enrollment_settings.base_price>0 AND
course_enrollment_settings.base_price<=100 THEN 2
WHEN course_enrollment_settings.base_price>100 AND
course_enrollment_settings.base_price<201 THEN 3
ELSE 6
END AS 'calc_base_price',
course_enrollment_settings.base_price
FROM
course_enrollment_settings
WHERE course_enrollment_settings.base_price = 0
I would recommend the first option, where you actually build elements using jQuery. the second approach simply sets the innerHTML property of the element to a string, which happens to be HTML, and is more error prone and less flexible.
Building on @JustinBarber's example and noting @eric.frederich's comment, if you want to format negative values like -$1,000.00
rather than $-1,000.00
and don't want to use locale
:
def as_currency(amount):
if amount >= 0:
return '${:,.2f}'.format(amount)
else:
return '-${:,.2f}'.format(-amount)
You can use the os Module:
var os = require("os");
os.hostname();
See http://nodejs.org/docs/latest/api/os.html#os_os_hostname
Caveats:
if you can work with the IP address -- Machines may have several Network Cards and unless you specify it node will listen on all of them, so you don't know on which NIC the request came in, before it comes in.
Hostname is a DNS matter -- Don't forget that several DNS aliases can point to the same machine.
Through Xml you can do easily as type following code in xml (editText)...
android:digits="abcdefghijklmnopqrstuvwxyz"
only characters will be accepted...
Here is a link to an excellent wiki that explains how to put greek symbols in ggplot2. In summary, here is what you do to obtain greek symbols
parse = T
inside geom_text
or annotate
.expression(alpha)
to get greek alpha.labeller = label_parsed
inside facet
.bquote(alpha == .(value))
in legend label.You can see detailed usage of these options in the link
EDIT. The objective of using greek symbols along the tick marks can be achieved as follows
require(ggplot2);
data(tips);
p0 = qplot(sex, data = tips, geom = 'bar');
p1 = p0 + scale_x_discrete(labels = c('Female' = expression(alpha),
'Male' = expression(beta)));
print(p1);
For complete documentation on the various symbols that are available when doing this and how to use them, see ?plotmath
.
You can use ILIKE
. i.e.
SELECT id FROM groups where name ILIKE 'administrator'
"net send" is a command using a background service called "messenger". This service has been removed from Windows 7. ie You cannot use 'net send' on Vista nor Win7 / Win8.
Pity though , I loved using it.
There is alternatives, but that requires you to download and install software on each pc you want to use, this software runs as background services, and i would advise one to be very very very very careful of using these kind of software as they can potentially cause seriously damage one's system or impair the systems securities.
winsent innocenti / winsent messenger
****This command is risky because of what is stated above***
This is a way to invoke one or more JavaScript methods from the code behind. By using Script Manager we can call the methods in sequence. Consider the below code for example.
ScriptManager.RegisterStartupScript(this, typeof(Page), "UpdateMsg",
"$(document).ready(function(){EnableControls();
alert('Overrides successfully Updated.');
DisableControls();});",
true);
In this first method EnableControls() is invoked. Next the alert will be displayed. Next the DisableControls() method will be invoked.
This started happening with 6.0.4 recently for me, I don't think this is a very good solution but here is what helped me. Close Visual Studio
See this Link
HTML
<div id="products"></div>
JS
var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
};
var name = $("<div/>",{"text":someone.name,"class":"name"
});
var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);
No this will be a problem. PHP Variable Functions
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
Use Java 8's removeIf(),
To remove safely,
letters.removeIf(x -> !x.equals("A"));
The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.
If you have a big archive and you only need one single file out of it, you have to decompress the whole gzip file to get to that file. This is not required if you have a zip file.
On the other hand, if you compress 10 similiar or even identical files, the zip archive will be much bigger because each file is compressed individually, whereas in gzip in combination with tar a single file is compressed which is much more effective if the files are similiar (equal).
This error:
python: can't open file 'test.py': [Errno 2] No such file or directory
Means that the file "test.py" doesn't exist. (Or, it does, but it isn't in the current working directory.)
I must save the file in any specific folder to make it run on terminal?
No, it can be where ever you want. However, if you just say, "test.py", you'll need to be in the directory containing test.py.
Your terminal (actually, the shell in the terminal) has a concept of "Current working directory", which is what directory (folder) it is currently "in".
Thus, if you type something like:
python test.py
test.py
needs to be in the current working directory. In Linux, you can change the current working directory with cd
. You might want a tutorial if you're new. (Note that the first hit on that search for me is this YouTube video. The author in the video is using a Mac, but both Mac and Linux use bash
for a shell, so it should apply to you.)
Tried everything. I deleted m2e and installed m2e version 2.7.0. Then deleted the .m2 directory and force updated maven. It worked!
In recent Git (I'm using v2.15.1), the following will merge upstream submodule changes into the submodules recursively:
git submodule update --recursive --remote --merge
You may add --init
to initialize any uninitialized submodules and use --rebase
if you want to rebase instead of merge.
You need to commit the changes afterwards:
git add . && git commit -m 'Update submodules to latest revisions'
GTK3:
#!/usr/bin/python3
from gi.repository import Gtk, Gdk
class Hello(Gtk.Window):
def __init__(self):
super(Hello, self).__init__()
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
clipboard.set_text("hello world", -1)
Gtk.main_quit()
def main():
Hello()
Gtk.main()
if __name__ == "__main__":
main()
It is very simple, just add a property:
public string Value {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
If you need this, you shouldn't use forEach
, but one of the other methods available on streams; which one, depends on what your goal is.
For example, if the goal of this loop is to find the first element which matches some predicate:
Optional<SomeObject> result =
someObjects.stream().filter(obj -> some_condition_met).findFirst();
(Note: This will not iterate the whole collection, because streams are lazily evaluated - it will stop at the first object that matches the condition).
If you just want to know if there's an element in the collection for which the condition is true, you could use anyMatch
:
boolean result = someObjects.stream().anyMatch(obj -> some_condition_met);
FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the
android:layout_gravity
attribute.Child views are drawn in a stack, with the most recently added child on top. The size of the FrameLayout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).
A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout.
(Current docs here)
A TableLayout consists of a number of
TableRow
objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.The width of a column is defined by the row with the widest cell in that column.
Note: Absolute Layout is deprecated.
In swift 4.0
var viewController: UIViewController? = storyboard().instantiateViewController(withIdentifier: "Identifier")
var navi = UINavigationController(rootViewController: viewController!)
navigationController?.pushViewController(navi, animated: true)
var yearsToAdd = 5;
var current = new Date().toISOString().split('T')[0];
var addedYears = Number(this.minDate.split('-')[0]) + yearsToAdd + '-12-31';
You can clear the input field by using $('#shares').val('');
If you are able to copy the actual SQLite database file to your desktop, you can use this tools to browse the data.
Only want to clone the structure of table:
CREATE TABLE foo SELECT * FROM bar WHERE 1 = 2;
Also wants to copy the data:
CREATE TABLE foo as SELECT * FROM bar;
Here's a bug report on the feature you're requesting.
It's status is "reviewed" but I don't believe it's been implemented yet.
VBA does not have an internal implementation of a dictionary, but from VBA you can still use the dictionary object from MS Scripting Runtime Library.
Dim d
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "aaa"
d.Add "b", "bbb"
d.Add "c", "ccc"
If d.Exists("c") Then
MsgBox d("c")
End If
Try this:
Write-Host ($obj | Format-Table | Out-String)
or
Write-Host ($obj | Format-List | Out-String)
Create a class for maintain hit counters
public static class Counter
{
private static long hit;
public static void HitCounter()
{
hit++;
}
public static long GetCounter()
{
return hit;
}
}
Increment the value of counter at page load event
protected void Page_Load(object sender, EventArgs e)
{
Counter.HitCounter(); // call static function of static class Counter to increment the counter value
}
Redirect the page on itself and display the counter value on button click
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(Request.RawUrl.ToString()); // redirect on itself
Response.Write("<br /> Counter =" + Counter.GetCounter() ); // display counter value
}
Yes. you can't remember all the shortcuts. You will forget many of them for sure. In this way, you can recall it and get the work done quickly.
Press Ctrl+3
And type whatever the hell you want :) It's a shortcut for shortcuts
You can't, you'll have to do something like
<script type="text/javascript">
var php_var = "<?php echo $php_var; ?>";
</script>
You can also load it with AJAX
rhino is right, the snippet lacks of a type for the sake of brevity.
Also, note that if $php_var
has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.
$(document).ready(function(){_x000D_
$(":button").click(function(){_x000D_
$("p").toggle();_x000D_
_x000D_
if (this.value=="Add") this.value = "Save";_x000D_
else this.value = "Add";_x000D_
_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<input type='button' value='Add' id='btnAddProfile'>_x000D_
_x000D_
<p>This is a paragraph with little content.</p>_x000D_
<p>This is another small paragraph.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register
parameter, independently of the module used.
Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:
---
- hosts: localhost
tasks:
- shell: ls
register: shell_result
- debug:
var: shell_result.stdout_lines
Here register
tells ansible to save the response of the module into the shell_result
variable, and then we use the debug
module to print the variable out.
An example run would look like the this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
changed: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => {
"shell_result.stdout_lines": [
"play.yml"
]
}
Responses can contain multiple fields. stdout_lines
is one of the default fields you can expect from a module's response.
Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout
or stdout_lines
values, however the msg
field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.
Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v
, -vvv
and -vvvv
. For example when running the playbook with verbosity (-vvv
) you get this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
(...)
changed: [localhost] => {
"changed": true,
"cmd": "ls",
"delta": "0:00:00.007621",
"end": "2017-02-17 23:04:41.912570",
"invocation": {
"module_args": {
"_raw_params": "ls",
"_uses_shell": true,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"warn": true
},
"module_name": "command"
},
"rc": 0,
"start": "2017-02-17 23:04:41.904949",
"stderr": "",
"stdout": "play.retry\nplay.yml",
"stdout_lines": [
"play.retry",
"play.yml"
],
"warnings": []
}
As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines
is available, and its contents are what we expect.
To answer your main question about the jenkins_script
module, if you check its documentation, you can see that it returns the output in the output
field, so you might want to try the following:
tasks:
- jenkins_script:
script: (...)
register: jenkins_result
- debug:
var: jenkins_result.output
def multiples(n,m,starting_from=1,increment_by=1):
"""
# Where n is the number 10 and m is the number 2 from your example.
# In case you want to print the multiples starting from some other number other than 1 then you could use the starting_from parameter
# In case you want to print every 2nd multiple or every 3rd multiple you could change the increment_by
"""
print [ n*x for x in range(starting_from,m+1,increment_by) ]
In my recent tests with IE8 and Firefox 3.5, it seems that both are RFC-compliant. However, they differ in their "friendliness" to the origin server. IE8 treats no-cache
responses with the same semantics as max-age=0,must-revalidate
. Firefox 3.5, however, seems to treat no-cache
as equivalent to no-store
, which sucks for performance and bandwidth usage.
Squid Cache, by default, seems to never store anything with a no-cache
header, just like Firefox.
My advice would be to set public,max-age=0
for non-sensitive resources you want to have checked for freshness on every request, but still allow the performance and bandwidth benefits of caching. For per-user items with the same consideration, use private,max-age=0
.
I would avoid the use of no-cache
entirely, as it seems it has been bastardized by some browsers and popular caches to the functional equivalent of no-store
.
Additionally, do not emulate Akamai and Limelight. While they essentially run massive caching arrays as their primary business, and should be experts, they actually have a vested interest in causing more data to be downloaded from their networks. Google might not be a good choice for emulation, either. They seem to use max-age=0
or no-cache
randomly depending on the resource.
If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
In newer versions of OS X (especially Yosemite, EL Capitan), Apple has removed Java support for security reasons. To fix this you have to do the following.
Mount the disk image file and install Java 6 runtime for OS X.
After this you should not be seeing any of the below messages:
- Unable to find any JVMs matching version "(null)"
- No Java runtime present, try --request to install.
Try Base64 encoding/decoding your binary data. Also look into CDATA sections
WSDL: Stands for Web Service Description Language
In SOAP(simple object access protocol), when you use web service and add a web service to your project, your client application(s) doesn't know about web service Functions. Nowadays it's somehow old-fashion and for each kind of different client you have to implement different WSDL
files. For example you cannot use same file for .Net
and php
client.
The WSDL
file has some descriptions about web service functions. The type of this file is XML
. SOAP
is an alternative for REST
.
REST: Stands for Representational State Transfer
It is another kind of API service, it is really easy to use for clients. They do not need to have special file extension like WSDL
files. The CRUD operation can be implemented by different HTTP Verbs
(GET for Reading, POST for Creation, PUT or PATCH for Updating and DELETE for Deleting the desired document) , They are based on HTTP
protocol and most of times the response is in JSON
or XML
format. On the other hand the client application have to exactly call the related HTTP Verb
via exact parameters names and types. Due to not having special file for definition, like WSDL
, it is a manually job using the endpoint. But it is not a big deal because now we have a lot of plugins for different IDEs to generating the client-side implementation.
SOA: Stands for Service Oriented Architecture
Includes all of the programming with web services concepts and architecture. Imagine that you want to implement a large-scale application. One practice can be having some different services, called micro-services and the whole application mechanism would be calling needed web service at the right time.
Both REST
and SOAP
web services are kind of SOA
.
JSON: Stands for javascript Object Notation
when you serialize an object for javascript the type of object format is JSON. imagine that you have the human class :
class Human{
string Name;
string Family;
int Age;
}
and you have some instances from this class :
Human h1 = new Human(){
Name='Saman',
Family='Gholami',
Age=26
}
when you serialize the h1 object to JSON the result is :
[h1:{Name:'saman',Family:'Gholami',Age:'26'}, ...]
javascript
can evaluate this format by eval()
function and make an associative array from this JSON
string. This one is different concept in comparison to other concepts I described formerly.
you can try this... ALTER TABLE Your_Table ADD table_ID int NOT NULL PRIMARY KEY auto_increment;
You can KILL the processid.
mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www | Sleep | 25946 | | NULL |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
mysql> kill 1193777;
But:
Or you configure your mysql-server by setting a shorter timeout on wait_timeout
and interactive_timeout
mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| table_lock_wait_timeout | 50 |
| wait_timeout | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)
Set with:
set global wait_timeout=3;
set global interactive_timeout=3;
(and also set in your configuration file, for when your server restarts)
But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...
This came in handy for one of my requirements where I did not want to use CTE and also did not want to go with the inner join.
DECLARE @Ids varchar(50);
SET @Ids = '1,2,3,5,4,6,7,98,234';
SELECT
cn1,cn2,cn3
FROM tableName
WHERE columnName in (select Value from fn_SplitList(@ids, ','))
Yes you can. Just check my fiddle for clarification. For demo purpose i kept the code in fiddle at same location. You can extract that code as shown in two different Javascript files and load them in html file.
https://jsfiddle.net/mvora/mrLmkxmo/
/******** PUT THIS CODE IN ONE JS FILE *******/
var secondFileFuntion = function(){
this.name = 'XYZ';
}
secondFileFuntion.prototype.getSurname = function(){
return 'ABC';
}
var secondFileObject = new secondFileFuntion();
/******** Till Here *******/
/******** PUT THIS CODE IN SECOND JS FILE *******/
function firstFileFunction(){
var name = secondFileObject.name;
var surname = secondFileObject.getSurname()
alert(name);
alert(surname );
}
firstFileFunction();
If you make an object using the constructor function and trying access the property or method from it in second file, it will give you the access of properties which are present in another file.
Just take care of sequence of including these files in index.html
Brian Ramsay’s code, de-pseudofied:
- (NSString*)formattedStringForDuration:(NSTimeInterval)duration
{
NSInteger minutes = floor(duration/60);
NSInteger seconds = round(duration - minutes * 60);
return [NSString stringWithFormat:@"%d:%02d", minutes, seconds];
}
sb.Append(Environment.Newline);
sb.Append("\t");
For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.
However, if you had multiple rules like this:
#foo > ul > li > ul > li > a:nth-child(3n+1) {
color: red;
}
#foo > ul > li > ul > li > a:nth-child(3n+2) {
color: green;
}
#foo > ul > li > ul > li > a:nth-child(3n+3) {
color: blue;
}
You could condense them to one of the following:
/* Sass */
#foo > ul > li > ul > li
> a:nth-child(3n+1)
color: red
> a:nth-child(3n+2)
color: green
> a:nth-child(3n+3)
color: blue
/* SCSS */
#foo > ul > li > ul > li {
> a:nth-child(3n+1) { color: red; }
> a:nth-child(3n+2) { color: green; }
> a:nth-child(3n+3) { color: blue; }
}
Activity
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:id="@+id/mytable"
android:layout_width="match_parent"
android:layout_height="match_parent">
</TableLayout>
</HorizontalScrollView>
Your Class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testtable);
table = (TableLayout)findViewById(R.id.mytable);
showTableLayout();
}
public void showTableLayout(){
Date date = new Date();
int rows = 80;
int colums = 10;
table.setStretchAllColumns(true);
table.bringToFront();
for(int i = 0; i < rows; i++){
TableRow tr = new TableRow(this);
for(int j = 0; j < colums; j++)
{
TextView txtGeneric = new TextView(this);
txtGeneric.setTextSize(18);
txtGeneric.setText( dateFormat.format(date) + "\t\t\t\t" );
tr.addView(txtGeneric);
/*txtGeneric.setHeight(30); txtGeneric.setWidth(50); txtGeneric.setTextColor(Color.BLUE);*/
}
table.addView(tr);
}
}
NULL
isn't a native part of the core C++ language, but it is part of the standard library. You need to include one of the standard header files that include its definition. #include <cstddef>
or #include <stddef.h>
should be sufficient.
The definition of NULL
is guaranteed to be available if you include cstddef
or stddef.h
. It's not guaranteed, but you are very likely to get its definition included if you include many of the other standard headers instead.